Transcript ppt
Sub-queries and Views
1
A Complex Query
• We would like to create a table containing 3
columns:
– Sailor id
– Sailor age
– Age of the oldest Sailor
How can this be done?
2
Attempt 1
SELECT S.sid, S.age, MAX(S.age)
FROM Sailors S;
Why is this wrong?
3
Attempt 2
SELECT S.sid, S.age, MAX(S.age)
FROM Sailors S
GROUP BY S.name, S.age;
Why is this wrong?
4
Solution 1:
Sub-query in FROM
SELECT S.sid, S.age, M.mxage
FROM Sailors S,(SELECT MAX(S2.age) as mxage
FROM Sailors S2) M;
• We can put a query in the FROM clause instead of a
table
• The query in the FROM clause must be renamed with a
range variable (M in this case).
5
Solution 1:
Sub-query in SELECT
SELECT S.sid, S.age, (SELECT MAX(S2.age)
FROM Sailors S2)
FROM Sailors S;
• A query in the SELECT clause must return at most one
value for each row returned by the outer query.
6
Another Example of a
Sub-query in SELECT
SELECT S.sid, S.age, (SELECT MAX(S2.age)
FROM Sailors S2
WHERE S2.age<S.age)
FROM Sailors S;
• This query returns for each sailor the age of the oldest
sailor that is younger than him.
• Note the use of S (defined in the outer query) within the
inner query.
7
Another Example of a
Sub-query in FROM??
SELECT S.sid, S.age, M.mxage
FROM Sailors S, (SELECT MAX(S2.age) as mxage
FROM Sailors S2
WHERE S2.age<S.age);
Why is this wrong?
8
Solution 3: Views
• A View is a query that looks like a table and
can be used as a table.
CREATE OR REPLACE VIEW MaxAge as
SELECT MAX(S.age) as mxage
FROM Sailors S;
SELECT S.sid, S.age, M.mxage
FROM Sailors S, MaxAge M;
9
Another Example of a View
CREATE
SELECT
FROM
WHERE
OR REPLACE VIEW MaxAges as
S1.sid, S2.age as mxage
Sailors S1, Sailors S2
S2.age = (SELECT MAX(S3.age)
FROM Sailors S3
WHERE S3.age < S1.age);
SELECT S.sid, S.age, M.mxage
FROM Sailors S, MaxAges M
WHERE S.sid = M.sid;
10
Views For Restricting Access
• Suppose that we have a table:
Grades(Login, Exercise, Grade)
• We would like a user to only be able to see his own
grades. We create the following view and grant
privileges to query the view (not the underlying table)
CREATE
SELECT
FROM
WHERE
OR REPLACE VIEW UserGrades as
*
Pseudo-column
Grades
which is equal to
Login = User;
the user name.
11
Delete and Update
12
Deleting Tuples
• The basic form of a delete statement is:
DELETE FROM TableName
WHERE Condition;
13
Examples
Delete Sailors with rating less than 3:
DELETE FROM Sailors
WHERE rating < 3;
Delete Sailors with the minimum rating:
DELETE FROM Sailors S1
WHERE S1.rating = (SELECT MIN(S2.rating)
FROM Sailors S2)
14
Updating Tuples
• The basic form of an update statement is:
UPDATE TableName
SET Column1 = Value1, …
ColumnN = ValueN
WHERE Condition;
15
Example
Update boat 13: color to red and name to
voyager
UPDATE Boats
SET color = ‘red’,
bname = ‘Voyager’
WHERE bid = 13;
16
Another Example
Update rating of Rusty to be the maximum
rating of any sailor
UPDATE Sailors
SET rating = (SELECT MAX(rating)
FROM Sailors)
WHERE sname = ‘Rusty’;
Note: When updating with a subquery, the
subquery must return one value only!
17
Connecting to a Database
with JDBC
18
Why Access a Database with
Java?
• There are queries that can not be computed
in Sql:
– Given a table Bus(Source, Destination) find all
pairs of places that it is possible to travel (paths of
any length
• Java allows for a convenient user interface to
the database
19
Learning JDBC
• On the Tirgul page of the Online
Resources of the course homepage I
will put:
– A link to a JDBC tutorial
– A link to the JDBC API
– Several Example Programs
20
Packages to Import
• In order to connect to the Oracle database
from java, import the following packages:
– java.sql.*;
– oracle.jdbc.driver.*;
21
Connecting to the Database
DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
String
String
String
String
driver = "jdbc:oracle:thin:";
user = "sam";
password = "samIam";
conStr = driver + user + “/” +
password + "@sol4:1521:stud“;
Connection con =
DriverManager.getConnection(conStr);
22
Accessing the Database
• The database is accessed using the
Connection object.
• 3 Types of statements are possible:
– Statement
– PreparedStatement
– CallableStatement (not discussed today)
• Note that CallableStatement inherits from
PreparedStatement which inherits from
Statement
23
Querying with Statement
String queryStr =
"SELECT * FROM Member " +
"WHERE Lower(Name) = 'harry potter'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(queryStr);
•Statements are used for queries that are only used
once.
•The executeQuery method returns an object
representing the query result.
24
Changing DB with Statement
String deleteStr =
“DELETE FROM Member " +
"WHERE Lower(Name) = ‘lord voldemort’";
Statement stmt = con.createStatement();
int delnum = stmt.executeUpdate(deleteStr);
•executeUpdate is used for data manipulation: insert,
delete, update, create table, etc.
•executeUpdate returns the number of rows modified.
25
Querying with
PreparedStatement
String queryStr =
"SELECT * FROM Program " +
"WHERE Name = ? and Cost < ?”;
PreparedStatement pstmt =
con.prepareStatement(queryStr);
pstmt.setString(1, “Unfogging the Future”);
pstmt.setInt(2, 1000);
ResultSet rs = pstmt.executeQuery();
26
About Prepared Statements
• Prepared Statements are used for queries
that are executed many times.
• They are parsed only once.
• Using setString(i, value) (setInt(i, value), etc.)
the i-th question mark is set to the given
value.
27
Changing DB with
PreparedStatement
String deleteStr =
“DELETE FROM Program " +
"WHERE Name = ? and Cost < ?”;
PreparedStatement pstmt =
con.prepareStatement(deleteStr);
pstmt.setString(1, “Unfogging the Future”);
pstmt.setInt(2, 1000);
int delnum = pstmt.executeUpdate();
28
Printing Query Output:
Result Set (1)
Print Column Headers:
ResultSetMetaData rsmd = rs.getMetaData();
int numcols = rsmd.getColumnCount();
for (int i = 1 ; i <= numcols; i++) {
if (i > 1) System.out.print(",");
System.out.print(rsmd.getColumnLabel(i));
}
29
Printing Query Output:
Result Set (2)
while (rs.next()) {
for (int i = 1 ; i <= numcols; i++) {
if (i > 1) System.out.print(",");
System.out.print(rs.getString(i));
}
System.out.println("");
}
To get the data in the i-th column: rs.getString(i)
To get the data in column Url: rs.getString(“Url”)
30
Cleaning Up After Yourself
• Remember to close the Connections,
Statements and ResultSets
con.close();
stmt.close();
rs.close()
31
Dealing With Exceptions
• A exception can have more exceptions in it.
catch (SQLException e) {
while (e != null) {
System.out.println(e.getSQLState());
System.out.println(e.getMessage());
System.out.println(e.getErrorCode());
e = e.getNextException();
}
}
32