Structured Query Language IV Asma Ahmad (C. J. Date) Database Systems
The Suppliers-Parts ERD SUPPLIER PART STATUS CITY P# PNAME COLOR WEIGHT CITY TOTQTY S# SNAME QTY
Logical Schema S{S#, Sname, City, Status} Constraint NOT ( Constraint NOT ( CITY='London' AND STATUS <> 20), CITY='London' AND STATUS <> 20), Constraint Sname UNIQUE NOT NULL; Constraint Sname UNIQUE NOT NULL; P{P#, Pname, Color, Weight, City} Constraint Color IN ('Red', 'Green', 'Blue', 'Yellow', 'White', 'Black', 'Other'), Constraint Weight >= 0 AND Weight = 0 AND Weight <= 10000;
Logical Schema (Cont.) SP{S#, P#, QTY} Constraint QTY NOT NULL, Constraint QTY >= 0 AND QTY = 0 AND QTY <= 60000, Foreign key {S#} References S, Foreign key {P#} References P; Constraint DB_STATUS20 “No suppliers with status less than 20 can supply any part in a quantity greater than 500.”; “No suppliers with status less than 20 can supply any part in a quantity greater than 500.”;
CREATE TABLE (Cont.) CREATE TABLE P ( P_ID char(2), P_ID char(2), Pname text(10), Pname text(10), Color text(10), Color text(10), Weight number, Weight number, City text(10), City text(10), primary key (P_ID) primary key (P_ID));
CREATE TABLE (Cont.) CREATE TABLE SP ( S_ID char(2) references S(S_ID), S_ID char(2) references S(S_ID), P_ID char(2) references P(P_ID), P_ID char(2) references P(P_ID), QTY number NOT NULL, QTY number NOT NULL, primary key (S_ID, P_ID) primary key (S_ID, P_ID));
The Suppliers-Parts DB: Tables S#SNAMESTATUSCITY S1 S2 S3 S4 S5 Smith Jones Blake Clark Adams London Paris London Athens P#PNAMECOLORWEIGHT P1 P2 P3 P4 P5 P6 Nut Bolt Screw Cam Cog Red Green Blue Red Blue Red CITY London Paris Rome London Paris London S# S1 S2 S3 S4 P# P1 P2 P3 P4 P5 P6 P1 P2 P4 P5 QTY S P SP
Restrict to Some Rows Q1: Which suppliers are located in London? SELECT* FROMS WHEREcity = 'London'; WHEREcity = 'London'; The restriction condition is specified in the WHERE clause.
Comparison Operators Q2: Which suppliers have status over 20? SELECT* FROMs WHEREstatus > 20; WHEREstatus > 20; Comparison operators: >, >=, =, <>,, >=, =, <>, <, <=
Logical Operators Q3: Which suppliers have status 20 and are located in London? SELECT* FROMs WHEREstatus = 20 AND city='London'; WHEREstatus = 20 AND city='London'; Logical operators: AND, OR, NOT
BETWEEN Q4: Which suppliers have status between 10 and 20? SELECT* FROMs WHEREstatus BETWEEN 10 AND 20; WHEREstatus BETWEEN 10 AND 20; SELECT* FROMs WHEREstatus >= 10 AND status = 10 AND status <= 20;
IN Q5: Which parts have color Red or Green? SELECT* FROMp WHEREcolor IN ('Red', 'Green'); WHEREcolor IN ('Red', 'Green'); SELECT* FROMp WHEREcolor = 'Red' OR color = 'Green'; WHEREcolor = 'Red' OR color = 'Green';
NOT IN Q6: Which parts DO NOT have color Red or Green? SELECT* FROMp WHEREcolor NOT IN ('Red', 'Green'); WHEREcolor NOT IN ('Red', 'Green'); SELECT* FROMp WHEREcolor <> 'Red' AND color <> 'Green'; WHEREcolor <> 'Red' AND color <> 'Green';
DISTINCT Removes Duplicates Q7: Which cities are suppliers located in? SELECT cityFROMs; SQL SELECT do not automatically remove duplicated rows in the result. Use DISTINCT to remove duplicated rows. SELECTDISTINCT cityFROMs;
Query Multiple Tables Q8: Which suppliers supply part ‘P1’? SELECTs.* FROMs, sp WHEREp#='P1'; Is the result correct? Why? SELECTs.* FROMs, sp WHEREs.s# = sp.s# AND p#='P1';
Cartesian Product Cartesian product of 2 sets, R and S is a set of pairs formed by choosing an element from R and another from S. Example: R={a,b,c}, S={b,e} R X S ={ a.b, a.e, b.b, b.e, c.b, c.e } R X S ={ a.b, a.e, b.b, b.e, c.b, c.e }
Cartesian Product If multiple tables are specified in the FROM clause, the result is always the Cartesian product of the tables, There will be |S|*|SP| rows in the result. Q9: Display the suppliers and their shipments? SELECT* FROMs, sp; Is the result correct?
Join If you need a join, that is, match a row in SP to its corresponding row in S with the same S#, you MUST specify the join condition in the WHERE clause. SELECT* FROMs, sp WHEREs.s# = sp.s#; You often need JOIN rather than Cartesian Product. Attribute names must be qualified with the table name when confusion rises, e.g., s.s# = sp.s#
Natural Join A natural join eliminates one of the duplicated columns (S#) The natural join is the most commonly used form of join operation SELECTs.*, sp.p#, sp.qty FROMs, sp WHEREs.s# = sp.s#;
Cartesian Product Q10: What are all current supplier-name/part- name PAIRS (may not be actually shipped)? SELECTsname, pname FROMs, p; If multiple tables are specified in the FROM clause, the result is the Cartesian product of the tables.
Join Q11: What are the supplier name and part name of each shipment? SELECTs.sname, p.pname FROMs, sp, p WHEREs.s# = sp.s# AND p.p# = sp.p#; If multiple tables are specified in the FROM clause, the result is the Cartesian product of the tables. If you need a join, specify the join condition in the WHERE clause. Note that other restriction condition may be specified in the WHERE clause too. e.g., city = 'London'.
Set Operator: Union Q1: Which suppliers are located in London OR supply part P1 (or both)? (SELECT* FROMs FROMs WHEREcity='London') UNION WHEREcity='London') UNION (SELECTs.* FROMs, sp FROMs, sp WHEREs.s#=sp.s# AND p#='P1'); WHEREs.s#=sp.s# AND p#='P1');
IN Subquery SELECT* SELECT* FROMs FROMs WHEREcity='London' WHEREcity='London' OR s# IN (SELECT s.s# FROMs, sp FROMs, sp WHEREs.s#=sp.s# WHEREs.s#=sp.s# AND p#='P1'); Nested Query: Query within another query. IN
Extend the Result with New Attributes Q2: Get the weights of shipments. SELECTp.*, s#, qty, weight*qty as shipwt FROMp, sp WHEREp.p# = sp.p#;
Aggregate Functions Q3: Get the number of parts supplied by each supplier. SELECTs#, COUNT(*) as np FROMsp GROUP BY s#; Calculate aggregates - SUM, COUNT, AVG, MAX, MIN - within GROUPs.
GROUP BY Q4: Get the total quantity supplied by each supplier. SELECTs#, SUM(qty)as ‘total qty’ SELECTs#, SUM(qty)as ‘total qty’ FROMsp GROUP BY s#; In the result: There is one tuple for each S# in SP, There is one tuple for each S# in SP, containing S# and the corresponding total quantity. containing S# and the corresponding total quantity. SP is grouped based on S#. SP is grouped based on S#. qty is summarized within each group of S#. qty is summarized within each group of S#.
Aggregate without GROUP BY Q5: Get the grand total quantity of all shipments. SELECT SUM(qty) as ‘grandtot’ FROMsp; In the result: There is totally one tuple. There is totally one tuple. All rows in sp are grouped together. All rows in sp are grouped together. qty is summarized over all rows. qty is summarized over all rows.
Aggregate on Aggregates Q6: Get the maximum total quantity among all parts. SELECT max(total_qty) FROM ( SELECT sum(qty) as ‘total_qty’ FROM SP GROUP BY p# )
Operators and Functions Operators and functions take some operands or arguments and return a value. We have encountered some operators (e.g., +, *, >, =) and functions (SUM, COUNT, MAX, MIN, AVG). There are more built-in operators and functions.
Summary of SELECT (read- only) SELECT Columns to be displayed. FROM Tables. [WHERE] Join or Restrict conditions. [GROUP BY] Summarize by groups. [HAVING] Eliminates some groups. [ORDER BY] Order the results. [optional clause] Set operators: UNION, INTERSECT, MINUS.