Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 SQL n Structured Query Language n Declarative l Specify the properties that should hold in the result, not how to obtain the result l Complex queries.

Similar presentations


Presentation on theme: "1 SQL n Structured Query Language n Declarative l Specify the properties that should hold in the result, not how to obtain the result l Complex queries."— Presentation transcript:

1 1 SQL n Structured Query Language n Declarative l Specify the properties that should hold in the result, not how to obtain the result l Complex queries have procedural elements n International Standard l SQL1 (1986) l SQL2 (SQL-92) l SQL3 (pieces have started to appear) n Two components l DDL statements l DML statements

2 2 n Basic SQL structure SELECTA 1, A 2, …, A n FROM R 1, R 2, …, R m WHEREP where A i are attributes from… R i which are relations P is a predicate * can replace A i ’s if all attributes are to be retrieved SQL Queries

3 3 What Kind of Predicates? n Simple predicates: l Expression  Value where Expression can be an attribute or an arithmetic expression involving attributes  = {, =, =, <>} and Value can be from one of the data types l Example: à Name = ‘J. Doe’ à (Age + 30) >= 65 n Compound predicates l Simple predicates combined with logical connectives AND, OR, NOT

4 4 Example Simple Queries n List names of all branches in the bank. SELECTB-name FROMbranch n List names of all customers who have an account together with their account numbers. SELECTC-name, Acc-number FROMdeposit n Find all cities where at least one customer lives. SELECT DISTINCT City FROM customer branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

5 5 Queries With Predicates n Find the names of all branches with assets greater than $2,500,000. SELECTB-name FROMbranch WHEREAssets > 2500000 n Find the names of all branches in Edmonton with assets greater than $2,500,000. SELECTB-name FROMbranch’ WHEREAssets>2500000 AND City=‘Edmonton’ branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

6 6 Ordering the Results n Find the names and assets of all branches with assets greater than $2,500,000 and order the result in ascending order of asset values. SELECTB-name, Assets FROMbranch WHEREAssets > 2500000 ORDER BYAssets n Default is ascending order, but descending order can be specified by the DESC keyword. branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

7 7 Queries Over Multiple Relations n List the name and cities of all customers who has an account with balance greater than $2,000. SELECTC-name, City FROMcustomer, deposit WHEREBalance > 2000 ANDcustomer.C-name = deposit.C-name n Find the name and assets of all branches which have customers living in Jasper. SELECTB-name, Assets FROMbranch,customer,deposit WHEREcustomer.City = ‘Jasper’ AND customer.C-name = deposit.C-name ANDdeposit.B-name = branch.B-name branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

8 8 Queries Over Multiple Relations n List the pairs of customer names who have loans from the same bank branch. SELECTP1.C-name, P2.C-name FROMborrow P1, borrow P2 WHEREP1.B-name = P2.B-name branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

9 9 n UNION, MINUS, INTERSECT n Operands may be specified by l create temp relations ASSIGN TO temp-1ASSIGN TO temp-1 SELECTA 1,..., A n SELECTB 1,..., B p FROMR 1,..., R m FROMS 1,..., S r WHEREP;WHEREQ; temp-1 UNION temp-2; l use parentheses (SELECT A 1,..., A n FROMR 1,..., R m WHEREP) UNION (SELECTB 1,..., B p FROMS 1,..., S r WHEREQ); Queries Involving Set Operators

10 10 Queries With Set Operators n Find all cities where there is either a customer or a branch. (SELECTCity FROMcustomer) UNION (SELECTCity FROMbranch) n Find all cities that has a branch but no customers. (SELECTCity FROMbranch) MINUS (SELECTCity FROMcustomer) branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

11 11 Queries With Set Operators n Find all the cities that have both customers and bank branches. (SELECTCity FROMcustomer) INTERSECT (SELECTCity FROMbranch) branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

12 12 n Queries within the WHERE clause of an outer query SELECT FROM WHEREOPERATOR (SELECT FROM WHERE) n There can be multiple levels of nesting n These can usually be written using other constructs (UNION, JOIN, etc). n Three operators: IN, (NOT) EXISTS, CONTAINS Queries With Nested Structures

13 13 SELECT FROM WHERE A 1,..., A n IN (SELECTA 1,..., A n FROMR 1,..., R m WHEREP) n Semantics: Values of attributes A 1,..., A n are found in the relation that is returned as a result of the calculation of the inner query. n Other comparison operators {, >=, <>} can be used in place of IN. “IN” Construct

14 14 “IN” Construct Example n Find all the customers who have a deposit at some branch at which John Doe has a deposit. SELECTC-name FROMdeposit WHEREB-name IN (SELECT B-name FROMdeposit WHEREC-name = ‘John Doe’) branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

15 15 “IN” Construct Example n Find all the customers who have either a deposit or a loan and their cities. SELECTC-name, City FROMcustomer WHEREC-nameIN(SELECTC-name FROMdeposit ) OR C-nameIN(SELECTC-name FROMborrow) branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

16 16 “IN” Construct Example n Find all the branches that have assets greater than all branches in Calgary. SELECTB-name FROMbranch WHEREAssets > ALL (SELECTAssets FROM branch WHERE City = ‘Calgary’) branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

17 17 SELECT FROM WHERE (NOT) EXISTS (SELECT* FROMR 1,..., R m WHEREP) n Semantics: For each tuple of the outer query, execute the inner query; if there is (no) at least one tuple in the result of the inner query, then retrieve that tuple of the outer query. n This accounts for the “there exists” type of queries “EXISTS” Construct

18 18 “EXISTS” Construct Example n Find the names of customers who live in a city which has a bank branch. SELECTC-name FROMcustomer WHERE EXISTS(SELECT* FROM branch WHEREcustomer.City=branch.City) n Find the names of customers who live in a city with no bank branches. SELECTC-name FROMcustomer WHERE NOT EXISTS(SELECT* FROM branch WHERE customer.City=branch.City) branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

19 19 “EXISTS” Construct Example n Find the names and addresses of all the customers who have no deposit in the bank. SELECTC-name, Street, City FROMcustomer WHERE NOT EXISTS (SELECT* FROM deposit WHEREcustomer.C-name=deposit.C-name) branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

20 20 “EXISTS” Construct Example n Find all the customers who have deposits in every branch of the bank. l Find all customers such that there is no bank branch where they do not have deposits SELECT* FROMcustomer WHERE NOT EXISTS (SELECTB-name FROM branch WHERE NOT EXISTS (SELECT* FROMdeposit WHEREbranch.B-name=deposit.B-name ANDcustomer.C-name = deposit.C-name)) branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

21 21 “CONTAINS” Construct (SELECTA 1,..., A n FROMR 1,..., R m WHERE P) CONTAINS (SELECTB 1,..., B p FROMS 1,..., S r WHERE Q) n Semantics: Compare the the result relations of the two queries and return TRUE if the second one is contained in the first.

22 22 “CONTAINS” Construct Example n Find all the customers who have a loan from every branch in Edmonton. SELECT* FROMcustomer WHERE ((SELECTB-name FROM borrow WHEREcustomer.C-name=borrow.C-name) CONTAINS (SELECTB-name FROMbranch WHERECity = ‘Edmonton’)) branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

23 23 n Specify a function that calculates a numeric value from a given relation. l The function is usually applied to an attribute. l COUNT, SUM, MAX, MIN, AVG SELECTAggFunc(A i ), …, AggFunc(A j ) FROMR 1,..., R m WHEREP Aggregate Functions

24 24 Aggregate Query Examples n Find the total assets of branches in Edmonton. SELECTSUM(Assets) FROMbranch WHERECity = ‘Edmonton’ n Find the number of cities where John Doe has an account with any bank branch. SELECTCOUNT(DISTINCT City) FROMbranch, deposit WHEREbranch.B-name = deposit.B-name AND deposit.C-name = ‘John Doe’ branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

25 25 Aggregate Query Examples n Find the names of branches which have assets greater than the average assets of all bank branches. SELECTB-name FROMbranch WHEREAssets > (SELECTAVG(Assets) FROM branch) branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

26 26 Grouping Queries n Group the results according to a set of attributes SELECTA i, …, A n FROMR 1,..., R m WHEREP GROUP BY A j …, A k n Rules: l All of the attributes in the SELECT clause that are not involved in an aggregation operation have to be included in the GROUP BY clause. l GROUP BY can have more attributes (k  n)

27 27 Grouping Query Examples n For each city, find the names of branches. SELECTCity, B-name FROMbranch GROUP BYCity, B-name n For each branch at each city, list the account numbers of the customer’s loans over $100,000. SELECTCity, C-name, Acc-number FROMcustomer, borrow WHEREcustomer.C-name = borrow.C-name ANDAmount > 100000 GROUP BYCity,B-name,C-name,Acc-number branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

28 28 Predicates on Groups n Group the results according to a set of attributes if they satisfy a certain condition SELECTA i, …, A n FROMR 1,..., R m WHEREP GROUP BYA j …, A k HAVINGQ n Rules: l Q must have a single value per group. l An attribute in Q has to either appear in an aggregation operator (in the SELECT clause) or be listed in the GROUP BY

29 29 Grouping Query Examples n Find the cities with more than two bank branches. SELECTCity FROMbranch GROUP BYCity HAVINGCOUNT(*) > 2 branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

30 30 Grouping Query Examples n For each city where there are more than two branches, find the names of branches. SELECTCity, B-name FROMbranch WHERECity IN (SELECTCity FROMbranch GROUP BY City HAVINGCOUNT(*) > 2) branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

31 31 Grouping Query Examples n Find the branches where the average account balance is greater than $1,200. SELECTB-name, AVG(Balance) FROMdeposit GROUP BYB-name HAVINGAVG(Balance) > 1200 branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

32 32 Grouping Query Examples n For each branch, list the names and number of loans of customers who have more than 2 loans over $100,000. SELECTB-name, C-name, COUNT(Acc-number) FROMborrow WHEREAmount > 100000 GROUP BYB-name, C-name HAVINGCOUNT(*) > 2 branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

33 33 Update Commands n Assume R(A 1, …, A n ) n INSERT l Form INSERT INTOR VALUES(value(A 1 ), …, value(A n )) l You can explicitly specify attribute names INSERT INTOR(A i, …, A k ) VALUES(value(A i ), …, value(A k )) n DELETE DELETE FROMR WHEREP

34 34 Update Commands n Assume R(A 1, …, A n ) n UPDATE UPDATER SETA i =value, …, A k =value WHEREP

35 35 Update Command Examples n Insert a new customer record for John Smith who lives on 345 Jasper Avenue, Edmonton. INSERT INTOcustomer VALUES (‘John Smith’,‘345 Jasper Avenue’,‘Edmonton’) n Delete all the customers who have less than $1,000 in their account. DELETE FROM customer WHEREC-name IN (SELECTC-name FROMdeposit WHEREBalance < 1000) branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

36 36 Update Command Examples n Increase by 5% the balances of customers who live in Edmonton and have a balance of more than $5,000. UPDATE deposit SETBalance = Balance*1.05 WHEREBalance > 5000 ANDC-name IN (SELECTC-name FROMcustomer WHERECity = ‘Edmonton’) branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

37 37 View Definition n General form CREATEVIEWV[(A i, …, A k )] ASSELECTA 1, …, A n FROMR 1, …, R m WHEREP n In queries, treat view V as any base relation SELECTA j, …, A l FROMV WHEREQ n Updates of views may be restricted

38 38 View Definition Example n Create a view jasper-customer of customers who live in Jasper. CREATE VIEW jasper-customer ASSELECT* FROMcustomer WHERECity = ‘Jasper’ branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

39 39 View Definition Example n Create a view total-balance that gives, for each customer at each city, the number of accounts owned by the customer and the total balance. CREATE VIEW total-balance(Name, City, Number, Total) ASSELECTC.City,C.C-name,COUNT(Acc-number), SUM(Balance) FROMdeposit D, customer C WHERED.C-name=C.C-name GROUP BYC.C-name,City branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) borrow(Acc-number, C-name, B-name, Amount)

40 40 View Update n A view with a single defining table is updatable if the view attributes contain the primary key or some other candidate key. n Views defined on multiple tables using joins are generally not updatable. n Views defined using aggregate functions are not updatable.

41 41 View Management n Two strategies for view management l Query modification à A view is a virtual relation à Multiple queries on complex views à Query processor modifies a query on a view with the view definition l View materialization à View is a materialized table in the database à Incrementally update the view (update propagation)

42 42 Handling Nulls Attribute values can be NULL NULL is not a constant, nor can it be used as an operand NAME = NULL Wrong! NULL + 30Wrong! Operating on variables with NULL values If x is NULL  x constant is NULL  x y is NULL l Comparing a NULL value with any other value returns UNKNOWN (three-valued logic).

43 43 Outer Join n Ensures that tuples from one or both relations that do not satisfy the join condition still appear in the final result with other relation’s attribute values set to NULL n Only available in SQL2 via join expression l R [NATURAL] JOIN S [ON ] n Alternatives l R [NATURAL] FULL OUTER JOIN S [ON ] l R [NATURAL] LEFT OUTER JOIN S [ON ] l R [NATURAL] RIGHT OUTER JOIN S [ON ]

44 44 SQL DDL Statements n Create schema CREATE SCHEMA Schema_Name AUTHORIZATION User_Name n Create table l Specify a new relation scheme l General form CREATE TABLE (Attribute_1 [DEFAULT ][ ], Attribute_2 [DEFAULT ][ ], … Attribute_n [DEFAULT ][ ], [ ])

45 45 Example n Given branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Account-number, C-name, B-name, Balance) n Definition of branch CREATE TABLE branch (B_nameCHAR(15), AddressVARCHAR(20), CityCHAR(9), AssetsDECIMAL(10,2)DEFAULT 0.00); n Assume customer is defined similarly

46 46 Allowable Data Types n Numeric l INT, SHORTINT l REAL (FLOAT), DOUBLE PRECISION l DECIMAL(i,j) n Character-string l CHAR(n), VARCHAR(n) n Bit-string l BIT(n), BIT VARYING(n) n Date l YYYY-MM-DD n Time l HH:MM:SS n Timestamp l both DATE and TIME fields plus a minimum of six positions for fractions of seconds

47 47 User-Defined Types n Create a DOMAIN CREATE DOMAIN AS n Example CREATE DOMAIN Gender AS CHAR(1) n Generally useful only for easy modification of type specification. n The value can be defaulted by the DEFAULT specification

48 48 n NOT NULL l specifies that an attribute cannot contain null values l should be specified for all primary keys n PRIMARY KEY l designates a set of columns as the table’s primary key n UNIQUE l specifies the alternate keys n FOREIGN KEY l designates a set of columns as the foreign key in a referential constraint Key Constraints

49 49 Example n Given branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Account-number, C-name, B-name, Balance) n Enhance the previous definition of branch: CREATE TABLE branch (B_nameCHAR(15)NOT NULL, AddressVARCHAR(20), CityCHAR(9), AssetsDECIMAL(10,2)DEFAULT 0.00, PRIMARY KEY (B_name));

50 50 n REFERENTIALLY TRIGGERED ACTION l Referential integrity: The primary key of one relation appears as an attribute (foreign key) of another relation. l Example: customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) l Deletion or update of primary key tuple requires action on the foreign key tuple. Specify constraint on delete or update. l How to manage? à reject à cascade: (on delete) automatically remove foreign keys if a referenced key is removed or (on update) change the foreign key value to the new value of the referenced key à set null à set default Referential Constraints

51 51 Example branch (B-name, Address, City, Assets) customer(C-name, Street, City) deposit(Acc-number, C-name, B-name, Balance) n Definition of deposit CREATE TABLE deposit (Acc-numberCHAR(9)NOT NULL, C-nameVARCHAR(15), B-nameVARCHAR(15), BalanceDECIMAL(10,2)DEFAULT 0.00, PRIMARY KEY (Acc-number), FOREIGN KEY (C-name) REFERENCES customer(C-name) ON DELETE SET NULL ON UPDATE CASCADE, FOREIGN KEY (B-name) REFERENCES branch(B-name));

52 52 Attribute & Domain Constraints n CHECK l specifies the condition that each row has to satisfy n Enhance the previous definition of branch: CREATE TABLE branch (B_nameCHAR(15)NOT NULL, AddressVARCHAR(20), CityCHAR(9), AssetsDECIMAL(10,2)DEFAULT 0.00 CHECK (Assets >= 0), PRIMARY KEY (B_name)); n Can be specified on domains as domain constraints CREATE DOMAIN Gender AS CHAR(1) CHECK (VALUE IN (‘F’, ‘M’));

53 53 Tuple Constraints n Use CHECK command and specify condition n The condition is checked every time a tuple is inserted or updated and the action rejected if the condition is false n Example CREATE TABLE deposit (Acc-numberCHAR(9)NOT NULL, C-nameVARCHAR(15), B-nameVARCHAR(15), BalanceDECIMAL(10,2)DEFAULT 0.00, PRIMARY KEY (Acc-number), FOREIGN KEY (C-name) REFERENCES customer(C-name) ON DELETE SET NULL ON UPDATE CASCADE, FOREIGN KEY (B-name) REFERENCES branch(B-name)) CHECK (NOT(Acc-number 100000);

54 54 Assertions n Global constraints of the form CREATE ASSERTION name CHECK (condition) n Example: No branch can have more than two customers who have more than 2 loans over $100,000. CREATE ASSERTION deposit CHECK (NOT EXISTS (SELECTCOUNT(Acc-number) FROMborrow WHEREAmount > 100000 GROUP BYB-name, C-name HAVINGCOUNT(*) > 2));

55 55 Other SQL DDL Commands n DROP SCHEMA l Delete an entire schema l CASCADE: delete all the tables in the schema l RESTRICT: delete only if empty n DROP TABLE l RESTRICT: delete only if not referenced in a constraint n ALTER TABLE l change definition

56 56 Embedded SQL n Ability to access a database from within an application program. n Issues l Interface  The same as ad hoc SQL but with EXEC SQL command l Using query results within the application program à Define shared variables using the format allowed in host language  Shared variables can be used in INSERT, DELETE, UPDATE as well as regular queries and schema modification statements à Retrieval queries require care F If the result relation has a single tuple: Each value in the SELECT statement requires a shared variable F If the result relation has a set of tuples: Cursor has to be defined

57 57 Example for Update n Consider an example in which will transfer $50,000 from a customer’s account in one branch to another customer’s account in another branch. … EXEC SQL BEGIN DECLARE SECTION; int cname1, cname2; /* two customer names */ char bname1[15], bname2[15]; /* branch names */ int amount; /* amount to be transferred */ EXEC SQL END DECLARE SECTION; /* Code (omitted) to read the customer and branch names and amount */ EXEC SQL UPDATE deposit SET Balance = Balance + :amount WHERE C-name = :cname2 AND B-name = :bname2; EXEC SQL UPDATE deposit SET Balance = Balance - :amount WHERE C-name = :cname1 AND B-name = :bname1; …

58 58 Retrieval Queries n If the result is only only one tuple, follow the same approach. n Example: For a given branch, retrieve the names and number of loans of customers who have more than 2 loans over $100,000. … EXEC SQL BEGIN DECLARE SECTION; char bname[15], cname[15]; /* branch & customer name */ int no-acct; /* number of accounts */ EXEC SQL END DECLARE SECTION; … /* Code (omitted) to get the branch name from use */ EXEC SQL SELECT C-name, COUNT(Acc-number) INTO :cname, :no-acct FROM borrow WHERE B-name = :bname AND Amount > 100000 GROUP BY C-name HAVING COUNT(*) > 2; /* Code (omitted) to print the total balance */ …

59 59 More General Retrieval Queries … EXEC SQL BEGIN DECLARE SECTION; EXEC SQL END DECLARE SECTION; … EXEC SQL DECLARE [options] CURSOR FOR [options] … EXEC SQL OPEN … while(condition) { EXEC SQL FETCH FROM INTO if(tuple exists) process it else break } EXEC SQL CLOSE …

60 60 Cursors n Use when the embedded SQL query is expected to return a relation with more than one tuple n Think about it almost as a pointer to successive tuples in the result relation n General form EXEC SQL DECLARE [INSENSITIVE][SCROLL] CURSOR FOR ORDER BY [FOR READ ONLY]; INSENSITIVE: The cursor is insensitive to changes in the relations referred to in the query while the cursor is open. SCROLL: Allows the subsequent FETCH command to retrieve tuples other than the default which is moving forward. FETCH [NEXT|PRIOR|FIRST|LAST|RELATIVE [+|-]n|ABSOLUTE [+|-]n] ORDER BY: Orders the results of the query according to some attribute(s). FOR READ ONLY: Ensures that accesses to the underlying relation(s) via this cursor will not change the relation.

61 61 Cursor Example n For each branch, retrieve the names and number of loans of customers who have more than 2 loans over $100,000. … EXEC SQL BEGIN DECLARE SECTION; char bname[15], cname[15]; /* branch & customer name */ int no-acct; /* number of accounts */ EXEC SQL END DECLARE SECTION; … EXEC SQL DECLARE loans CURSOR FOR SELECT B-name, C-name, COUNT(Acc-number) FROM borrow WHERE B-name = :bname AND Amount > 100000 GROUP BY C-name HAVING COUNT(*) > 2; … EXEC SQL OPEN loans; … while(1) { EXEC SQL FETCH FROM loans INTO :bname, :cname, :no-acct if(strcmp(SQLSTATE, “02000”) then break else print the info } EXEC SQL CLOSE loans …


Download ppt "1 SQL n Structured Query Language n Declarative l Specify the properties that should hold in the result, not how to obtain the result l Complex queries."

Similar presentations


Ads by Google