Published on

Introduction to database lecture# 7: This lecture is all about Scalar Subqueries and More...

Published in: Education, Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. SQL1Fall 2001 Database Systems 1Scalar subqueries• A scalar subquery is any expression that produces asingle value (single tuple/ single column)• Examples:SELECT max(amount) FROM bidsSELECT count(*) FROM items• Scalar subqueries can be used as if they were“constants”– in expressions in the WHERE clause, and– to output values in the SELECT clauseFall 2001 Database Systems 2Scalar subqueries• Find items with average bid 60 or more. Print thename of the item and the average bid.SELECT I.name, avg(B.amount)FROM Items I, Bids BWHERE I.iid=B.iidGROUP BY I.iid, I.nameHAVING avg(B.amount) > 60
  2. 2. SQL2Fall 2001 Database Systems 3Scalar subqueries• Find items with average bid 60 or more. Print the nameof the item and the average bid.SELECT I.name,FROM Items IWHERE 60 < (SELECT avg(B.amount)FROM bids BWHERE B.iid = I.iid)(SELECT avg(B2.amount)FROM Bids B2WHERE B2.iid = I.iid) avgAmountReturn a singlevalue for each tupleCheck the boolean conditionfor each tupleFall 2001 Database Systems 4What can’t you do with SQLor can you?• You are limited by the functions implemented in thedatabase– Not allowed: SELECT median(salary) …– You can add new functions to the database engine andimplement new types in a native programming language likeC,C++ (support varies)• You can have subselects in FROM and WHERE thatreturn a set of values, but not in SELECT– Allowed: SELECT * FROM (SELECT b.bid FROM bids bWHERE b.amount>20)– Not allowed: SELECT avg(SELECT b.amount FROM .. ) FROM..
  3. 3. SQL3Fall 2001 Database Systems 5What can’t you do with SQLor can you?• You cannot ask transitive queries– Given a relation “emp(A,B)” for immediate managers B or A, you cannotfind all managers of a person A.– SQL3 includes a recursive query definition construct –not implementedin Oracle.WITH RECURSIVE manages(emp, mgr) AS(SELECT E1.emp, E1.mgr FROM employee E1)UNION(SELECT M.emp, E2.mgr FROM manages M, employee E2WHERE M.mgr = E.id)SELECT M2.empFROM manages M2WHERE M2.emp = M2.mgr ;Recursive queries may produce infinite loops and it is best left to programmerswith solid logic background.Fall 2001 Database Systems 6Embedded SQL• You can embed SQL statements into many programminglanguages procedural power (loops, variables, etc.)• The main components of embedded SQL programming:– Regular program blocks– SQL code– Methods to connect to the database, invoke the SQL code andretrieve results– Methods to pass data from program variables to the SQL code– Methods to retrieve data from the result of queries to programvariables
  4. 4. SQL4Fall 2001 Database Systems 7#include <stdio.h>exec sql include sqlca;char user_prompt[] = "Please enter username and password: ";char cid_prompt[] = "Please enter customer ID: ";int main(){exec sql begin declare section; /* declare SQL host variables */char cust_id[5];char cust_name[14];float cust_discnt; /* host var for discnt value */char user_name[20], user_pwd[20];exec sql end declare section;exec sql whenever sqlerror goto report_error; /* error trap condition */exec sql whenever not found goto notfound; /* not found condition */exec sql connect :user_nameidentified by :user_pwd; /* ORACLE format: connect */while (prompt(cid_prompt, 1, cust_id, 4) >= 0) {exec sql select cname,discnt into :cust_name, :cust_discnt /* retrieve cname, discnt */from customers where cid = :cust_id;exec sql commit work; /* release read lock on row */printf("CUSTOMERS NAME IS %s AND DISCNT IS %5.1fn",cust_name, cust_discnt); /* NOTE, (:) not used here */continue;Fall 2001 Database Systems 8ProC• Each ESQL statement starts with EXEC SQL keywordand ends with a semicolon ;• A pre-compiler will scan a program file and only read thestatements enclosed within EXEC SQL statements anddisregard everything else.• SQLCA is a specific data structure for storing statuscodes of all SQL operations/* always have this for error handling*/exec sql include sqlca ;
  5. 5. SQL5Fall 2001 Database Systems 9Program.pcProgram.cFall 2001 Database Systems 10Variables in ESQL• All variables that will be used in an SQL statement must be declaredusing an ESQL declaration and data typeexec sql begin declare section ;VARCHAR e_name[30], username[30], passwd[30] ;INTEGER e_ssn, e_dept_id ;exec sql end declare section ;• You can use almost any SQL command in ESQL as long as properinput to these commands are provided in the form of programvariables.• To execute any command, you must first connect to a database inwhich all your tables reside.exec sql connect :username identified by :passwd ;
  6. 6. SQL6Fall 2001 Database Systems 11Executing SQL commands• Suppose we want to find the name of an employee given his/herSSN (input by the user of the program):exec sql select name, dept_id into :e_name, :e_dept_idfrom employeewhere ssn = :e_ssn ;Read the value of the variable “e_ssn” and execute the SQLstatement using this value, store the returned values of columns“name” and “dept_id” in the program variables “e_name” and“e_dept_id”.Compare the above query with the expression below. What is the difference?exec sql select name, dept_idfrom employee where ssn = e_ssn ;Program variables arepreceded by “:”Fall 2001 Database Systems 12Dealing with Strings• There is a mismatch between the definition of a string in Oracle andin C/C++.– In C, the end of a string is identified by the null character ‘0’. Hence,“Sibel” would be stored as characters ‘S’,’i’,’b’,’e’,’l’,’0’.– In Oracle, the length of a string is stored together with the string andthere is no special end of string character.– If you convert a data string from Oracle to C, you must pad it with ‘0’manually!• The data type VARCHAR e_name[30] is translated by the pre-compiler to the following structure:struct {unsigned short lenunsigned char arr[30]} e_name ;
  7. 7. SQL7Fall 2001 Database Systems 13More on stringsPutting the pieces together:strcpy(username.arr, “Sibel Adali”) ;username.len = strlen(“Sibel Adali”) ;strcpy(passwd.arr, “tweety-bird”) ;passwd.len = strlen(“tweety-bird”) ;exec sql connect :username identified by :passwd ;scanf(“%d”, &e_ssn) ;exec sql select name, dept_id into :e_name, :e_dept_idfrom employee where ssn = :e_ssn ;e_name.arr[e_name.len] = ‘0’ ; /* so can use string in C*/printf(“%s”, e_name.arr) ;exec sql commit work ; /* make any changes permanent */exec sql disconnect ; /* disconnect from the database */Fall 2001 Database Systems 14ESQL - Cursors• When a select statement returns a set of tuples, then thetuples (rows) can only be retrieved one by one.– programming language variables can contain only onevalue at a time– this is sometimes called an impedance mismatch• Cursor operations– declare a cursor using a regular SQL query (no “into”).exec sql declare emps_dept cursor forselect ssn, name from employeewhere dept_id = :e_dept_id ;
  8. 8. SQL8Fall 2001 Database Systems 15ESQL – More Cursors• More cursor operations– open a cursor: means the corresponding SQL query isexecuted, the results are written to a file (or a datastructure) and the cursor is pointing to the first row.exec sql open emps_dept ;– read the current row pointed to by the cursor using“fetch”. At the end of fetch, the cursor is moved to pointto the next tuple.exec sql fetch emps_dept into :e_ssn, :e_name ;Fall 2001 Database Systems 16How do we know when wereach the end of a cursor?• Each SQL statement executed in a program producesa status code that can be retrieved from the SQLCommunication Area (SQLCA) variables.• Check the “sqlcode” to see if the end of a cursor isreached (its expected value depends on the system).if (sqlca.sqlcode == -1) { … }• Error handling statementsexec sql whenever sqlerror{continue, stop, goto label, call function}– exec sql whenever is a trap condition, it hold for allexec sql statements unless a new trap conditionoverrides the current one.
  9. 9. SQL9Fall 2001 Database Systems 17Transactions• The most common ESQL statements are SELECT, INSERTINTO, and UPDATE statements.• A transaction in a program starts with the first read or write toa database (not with connect) and ends when either one ofthe following commands is executed– exec sql commit work ; /* changes to the databaseare made permanent */– exec sql rollback work ; /* restore all tuples to theiroriginal values */• If a program did not complete correctly, then changes can beundone to restore a consistent state.Fall 2001 Database Systems 18Dynamic SQL• In Dynamic SQL, embedded SQL statements are created on the flyusing strings!– these strings are fed to an exec sql statementexec sql execute immediate :sql_string• Since dynamic SQL statements are not known to the pre-compiler atcompile time, they must be optimized at run time!• Create a query once using a prepare statement and run it multipletimes using the execute statement.strcopy(sqltext.arr, “delete from employee where ssn = ?”) ;sqltext.len=str.len(sqltext.arr) ;exec sql prepare del_emp from :sqltext ;exec sql execute del_emp using :cust_id ;
  10. 10. SQL10Fall 2001 Database Systems 19SQLDA• When we execute a dynamic SQL statement, we do not know whichcolumns will be returned and how many columns will be returned.• The SQLDA descriptor definition allows us to find the number ofcolumns and the value for each column.exec sql include sqlda ;exec sql declare sel_curs cursor for sel_emps ;exec sql prepare sel_emps from :sqltext ;exec sql describe sel_emps into sqlda ;exec sql open sel_curs ;exec sql fetch sel_curs using descriptor sqlda ;Fall 2001 Database Systems 20JDBC – Dynamic SQL• Driver is a piece of software that enablescommunication between a program and adatabase system (DMBS specific packages).• It implements a number of main classes:– Connection (opening, closing, committing)– Statement (executing queries)– Result set (going through cursors, extractinginformation)
  11. 11. SQL11Fall 2001 Database Systems 21import java.sql.*;import oracle.sql.*;import oracle.jdbc.driver.*;class Employee{public static void main (String args []) throws SQLException{//Set your user name and the passwordString userName = "dummy" ;String passWord = "dummy" ;// Load the Oracle JDBC driverDriverManager.registerDriver(neworacle.jdbc.driver.OracleDriver());Connection conn =DriverManager.getConnection("jdbc:oracle:thin:@vcmr-57.server.rpi.edu:1521:ora8",userName,passWord);Fall 2001 Database Systems 22// Create a statement which will return a cursor that will allowyou to// scroll the result set using both "next" and "previous"methodsStatement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);ResultSet rset = stmt.executeQuery("SELECT name, oid FROM items ");// Iterate through the result and print the item nameswhile (rset.next ()) {//Get item name, which is the first columnSystem.out.println (rset.getString (1));PreparedStatement pstmt = conn.prepareStatement("SELECT name FROM owners WHERE oid = ?") ;//Feed the owner id retrieved from rset into pstmtpstmt.setInt(1, rset.getInt (2));ResultSet dset = pstmt.executeQuery() ;if (dset.next())System.out.println(dset.getString (1));} } }