32
1 Sub-queries and Views

1 Sub-queries and Views. 2 A Complex Query We would like to create a table containing 3 columns: –Sailor id –Sailor age –Age of the oldest Sailor How

  • View
    213

  • Download
    0

Embed Size (px)

Citation preview

1

Sub-queries and Views

2

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?

3

Attempt 1

SELECT S.sid, S.age, MAX(S.age)

FROM Sailors S;

Why is this wrong?

4

Attempt 2

SELECT S.sid, S.age, MAX(S.age)

FROM Sailors S

GROUP BY S.name, S.age;

Why is this wrong?

5

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).

6

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.

7

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.

8

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?

9

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;

10

Another Example of a View

CREATE OR REPLACE VIEW MaxAges as

SELECT S1.sid, S2.age as mxage

FROM Sailors S1, Sailors S2

WHERE 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;

11

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 OR REPLACE VIEW UserGrades as

SELECT *

FROM Grades

WHERE Login = User;

Pseudo-column which is equal to the user name.

12

Delete and Update

13

Deleting Tuples

• The basic form of a delete statement is:

DELETE FROM TableName

WHERE Condition;

14

Examples

DELETE FROM Sailors

WHERE rating < 3;

DELETE FROM Sailors S1

WHERE S1.rating = (SELECT MIN(S2.rating) FROM Sailors S2)

Delete Sailors with rating less than 3:

Delete Sailors with the minimum rating:

15

Updating Tuples

• The basic form of an update statement is:

UPDATE TableName

SET Column1 = Value1, …

ColumnN = ValueN

WHERE Condition;

16

Example

UPDATE Boats

SET color = ‘red’,

bname = ‘Voyager’

WHERE bid = 13;

Update boat 13: color to red and name to voyager

17

Another Example

UPDATE Sailors

SET rating = (SELECT MAX(rating)

FROM Sailors)

WHERE sname = ‘Rusty’;

Update rating of Rusty to be the maximum rating of any sailor

Note: When updating with a subquery, the subquery must return one value only!

18

Connecting to a Database with JDBC

19

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

20

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

21

Packages to Import

• In order to connect to the Oracle database from java, import the following packages:

– java.sql.*;– oracle.jdbc.driver.*;

22

Connecting to the DatabaseDriverManager.registerDriver(new

oracle.jdbc.driver.OracleDriver());

String driver = "jdbc:oracle:thin:";

String user = "sam";

String password = "samIam";

String conStr = driver + user + “/” +

password + "@sol4:1521:stud“;

Connection con = DriverManager.getConnection(conStr);

23

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

24

Querying with StatementString 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.

25

Changing DB with StatementString 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.

26

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();

27

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.

28

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();

29

Printing Query Output: Result Set (1)

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));

}

Print Column Headers:

30

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”)

31

Cleaning Up After Yourself

• Remember to close the Connections, Statements and ResultSets

con.close();

stmt.close();

rs.close()

32

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();

}

}