Upload
lucius-weaver
View
40
Download
3
Embed Size (px)
DESCRIPTION
SQL (sequel) is used on a most DBMS systems (e.g. Access, Oracle, Ingress, IBM DB2, MySQL) This course uses MySQL as the DBMS. SQL Revision. RDBMS Tables. Database consists of a set of tables Each table has vertical columns (attributes) and horizontal rows (tuples or records) - PowerPoint PPT Presentation
Citation preview
SQL Revision
SQL (sequel) is used on a most DBMS systems (e.g. Access, Oracle, Ingress, IBM DB2, MySQL)
This course uses MySQL as the DBMS
RDBMS Tables
• Database consists of a set of tables• Each table has vertical columns (attributes) and horizontal
rows (tuples or records)• Each row (or record) contains fields, one for each column,
which can contain data values• A heading specifies the name and type of the values for
each of the columns• A table can have 0, 1, or more rows• Only one data value (possibly composite) is held in any
one field• Unless NOT NULL is specified in the heading, NULL
values (i.e. unknown) are allowed
Suppliers Table
• Suppliers Table S, with sample values
Yate30BrownS5
London20BlondeS4
Detroit30BlueS3
Detroit10WhiteS2
London20PinkS1
CITYSTATUSSNAMESNo
SQL Tables (cont.)
• The rows have no particular order unless an order is imposed upon them
• The columns are strictly ordered from left to right (rarely significant – unlike 3GL record structures)
• Base Table : Table with a name that exists in its own right
• View: Table derived from other tables– Looks like another table to the user, but it is generated
at the point of use rather than stored
PRIMARY and FOREIGN KEYS
• A CANDIDATE KEY is one or more attributes the value of which is unique for every row
• A PRIMARY KEY for any table is chosen from one of its candidate keys
• A table may have one and only one primary key• A FOREIGN KEY is an attribute in a table whose
values must exactly match those of a primary key of the same or a different table in order to identify the existence of a relationship between rows
SQL Indexes
• Speed up retrieval at expense of:– space
– time for updates
• They are a stored file, with each entry containing :– data value
– pointer to row containing that value in that field
• Can be created by the user• System can choose whether or not to use it
SQL Data Definition Language (DDL)
• CREATE TABLE– Creates an initially empty Base Table – Data values added by other commands– Any column can contain NULL values for one
or more rows unless NOT NULL is specified in its type
– If a column is a Primary Key it must not contain NULL values
SQL Definition of Supplier/Parts DatabaseCREATE TABLE S( SNo CHAR(5), SNAME CHAR(20), STATUS NUMERIC(5), CITY CHAR(15), PRIMARY KEY (SNo) );
CREATE TABLE P( PNo CHAR(6), PNAME CHAR(20), SIZE CHAR(6), WEIGHT NUMERIC(5,1), CITY CHAR(15), PRIMARY KEY ( PNo) );
CREATE TABLE SP( SNo CHAR(5), PNo CHAR(6), QTY NUMERIC(9),PRIMARY KEY (SNo, PNo),CONSTRAINT SP_P FOREIGN KEY ( SNo) REFERENCES S(SNo),CONSTRAINT SP_S FOREIGN KEY (PNo) REFERENCES P(PNo) );
Example Database: Supplier/Parts
S SP
P
Yate30BrownS5
London20BlondeS4
Detroit30BlueS3
Detroit10WhiteS2
London20PinkS1
CITYSTATUSSNAMESNo
London19BIGCogP6
Detroit12MEDIUMCamP5
London14BIGScrewP4
Rome17MEDIUMScrewP3
Detroit17SMALLBoltP2
London12BIGNutP1
CITYWEIGHTSIZEPNAME PNo
400P5S4
300P4S4
200P2S4
200P2S3
400P2S2
300P1S2
100P6S1
100P5S1
200P4S1
400P3S1
200P2S1
300P1S1
QTYPNoSNo
SQL DDL – Built-in Types• Common types built into SQL
– CHAR(n)– VARCHAR(n)– BIT(n)– NUMERIC(p,q)– DECIMAL(p,q)– INTEGER– SMALLINT– FLOAT(p)– DATE– TIME– TIMESTAMP– INTERVAL
SQL – Keys
• At the end of a CREATE TABLE command, specify the Primary Key for that table and any Foreign Keys e.g.
CREATE TABLE SP( SNo CHAR(5) PNo CHAR(6) QTY NUMERIC(9)PRIMARY KEY (SNo,PNo)CONSTRAINT SP_P FOREIGN KEY ( SNo) REFERENCES S(SNo),CONSTRAINT SP_S FOREIGN KEY (PNo) REFERENCES P(PNo));
SQL DDL (cont)
• Additional Commands• DROP TABLE
– Removes a Base Table from the Database
• ALTER TABLE– Allows changes to a base table
• adding types• adding/removing columns
– Must be followed by an SQL table update commande.g. ALTER TABLE S ADD DISCOUNT SMALLINT;
Suppliers Table extended
Suppliers Table S, with sample values
Yate30BrownS5
London20BlondeS4
Detroit30BlueS3
Detroit10WhiteS2
London20PinkS1
CITYSTATUSSNAMESNo DISCOUNT
SQL DDL - Indexes• CREATE INDEX and DROP INDEX
– Used to create and remove indexes– The only commands that relate to indexes– Creates index on column(s) specified of named base
table– If UNIQUE is specified, no two rows are allowed the
same value for indexed field– e.g. CREATE UNIQUE INDEX IXS ON S (SNo);
CREATE INDEX IXSP ON SP (SNo, PNo);DROP INDEX IXSP;• N.B. Indexes result in extra disc space being used and a
slowing down of updates
SQL – DDL VIEWS
• CREATE VIEW and DROP VIEW
– Allows the creation and removal of views– CREATE VIEW viewname AS sql-dml– DROP viewname– e.g. CREATE VIEW GOODSUPPLIERS AS
SELECT SNo,SNAME,CITY FROM S WHERE STATUS > 15;
– DROP VIEW GOODSUPPLIERS;
View: GOODSUPPLIERS
– N.B. Cannot access STATUS information or information, including existence, of White from this view
YateBrownS5
LondonBlondeS4
DetroitBlueS3
LondonPinkS1CitySNAMESNo
SQL – Data Manipulation Language (DML)
• Four main types of DML statements in SQL• SELECT
– Retrieve part of one or more tables– Most frequently used SQL statement
• UPDATE – Updates the data values in an existing table
• INSERT– One method of putting data values into a table
• DELETE– Remove values from a table
SQL – SELECT
• General form:-
SELECT [ DISTINCT ] fields(s) FROM tables(s) [ WHERE predicate] [ ORDER BY field(s) [ GROUP BY field(s) [ HAVING predicate ] ]
Example Database: Supplier/Parts
S SP
P
Yate30BrownS5
London20BlondeS4
Detroit30BlueS3
Detroit10WhiteS2
London20PinkS1
CITYSTATUSSNAMESNo
London19BIGCogP6
Detroit12MEDIUMCamP5
London14BIGScrewP4
Rome17MEDIUMScrewP3
Detroit17SMALLBoltP2
London12BIGNutP1
CITYWEIGHTSIZEPNAME PNo
400P5S4
300P4S4
200P2S4
200P2S3
400P2S2
300P1S2
100P6S1
100P5S1
200P4S1
400P3S1
200P2S1
300P1S1
QTYPNoSNo
SELECT Examples
• SELECT SNo, STATUS FROM S
• SELECT * FROM S
– Selects all the columns from S, i.e. result is whole table
30S5
20S4
30S3
10S2
20S1
STATUSSNo
SELECT Examples (cont.)
• SELECT SNo , STATUS FROM S WHERE CITY=`Detroit` and STATUS > 20
• Predicate can use any of the following:
– Operators = ,( != or <>), >, >= ,< , <=
– BETWEEN value1 AND value 2
– IN ( list of values )
– IS NULL
– LIKE characterpattern)
• Use AND and OR to combine predicates
• Use NOT to negate predicates
• Use parentheses where necessary
30S3
STATUSSNo
SELECT Examples (cont.)
• Ordering of rows displayed• SELECT SNo , STATUS FROM S
ORDER BY STATUS ASC
• Opposite order is given by DESC
30S5
30S3
20S4
20S1
20S2
STATUSSNo
SELECT EXAMPLES (cont.)
• The join process produces one table from more than one other table
• e.g. Get supplier names and quantities for supply of part P1
SELECT SNAME,QTYFROM S,SPWHERE (S.SNo = SP.SNo AND PNo = P1 ) ; 300White
300Pink
QTYSNAME
SELECT EXAMPLES (cont.)
• e.g. Get supplier number, supplier name , quantities and size for screws
SELECT SNo, SNAME, SIZE, QTYFROM S,SP,PWHERE (S.SNo = SP.SNo AND SP. PNo = P.PNo AND PNAME= `Screw`);
300BIGBlondeS4
200BIGPinkS1
400MEDIUMPinkS1
QTYSIZESNAMESNo
PNo PNAME SIZE WEIGHT CITY PrefSNo
P1 Nut BIG 12 London S1
P2 Bolt SMALL 17 Detroit S3
P3 Screw MEDIUM 17 Rome S1
P4 Screw BIG 14 London S4
P5 Cam MEDIUM 12 Detroit
P6 Cog BIG 19 London S1
Yate30BrownS5
London20BlondeS4
Detroit30BlueS3
Detroit10WhiteS2
London20PinkS1
CITYSTATUSSNAMESNo
P
SAdd a preferred supplier `PrefSNo` to table P
Basic Equi Joins return matched rows
SELECT PNo, PNAME, SIZE, WEIGHT, SNAME, STATUSFROM P,SWHERE (P.PrefSNo = S.SNo);
PNo PNAME SIZE WEIGHT SNAME STATUS
P1 Nut BIG 12 Pink 20
P2 Bolt SMALL 17 Blue 30
P3 Screw MEDIUM 17 Pink 20
P4 Screw BIG 14 Blonde 20
P6 Cog BIG 19 Pink 20
Inner Equi Joins return matched rowsSELECT PNo, PNAME, SIZE, WEIGHT, SNAME, STATUSFROM P NATURAL JOIN S;
Implicit match on common attributes by DBMS using the System Catalogue
Or
SELECT PNo, PNAME, SIZE, WEIGHT, SNAME, STATUSFROM P INNER JOIN SON P.PrefSNo=S.SNo;
PNo PNAME SIZE WEIGHT SNAME STATUS
P1 Nut BIG 12 Pink 20
P2 Bolt SMALL 17 Blue 30
P3 Screw MEDIUM 17 Pink 20
P4 Screw BIG 14 Blonde 20
P6 Cog BIG 19 Pink 20
Outer Joins return all rows in selected table
SELECT PNo, PNAME, SIZE, WEIGHT, SNAME, STATUS
FROM P LEFT JOIN S
ON P.PrefSNo=S.SNo;
PNo PNAME SIZE WEIGHT SNAME STATUS
P1 Nut BIG 12 Pink 20
P2 Bolt SMALL 17 Blue 30
P3 Screw MEDIUM 17 Pink 20
P4 Screw BIG 14 Blonde 20
P5 Cam MEDIUM 12
P6 Cog BIG 19 Pink 20
Outer Joins return all rows in selected table
SELECT PNo, PNAME, SIZE, WEIGHT, SNAME, STATUS
FROM P RIGHT JOIN S
ON P.PrefSNo=S.SNo;
PNo PNAME SIZE WEIGHT SNAME STATUS
P6 Cog BIG 19 Pink 20
P3 Screw MEDIUM 17 Pink 20
P1 Nut BIG 12 Pink 20
White 10
P2 Bolt SMALL 17 Blue 30
P4 Screw BIG 14 Blonde 20
Brown 30
Join Types
TS ITS - ST -Inner Join
R ight O uter JoinLeft O uter Join
S T
Full O uter Join
U)-( TS )( TS I ) -( ST)( TS I U
U)-( TS ) -( ST)( TS I U
UUnion Join
)-( TS ) -( ST
SELECT EXAMPLES (cont.)
• Aggregate functions– Enhance the power of SELECT
– calculation based on the values in the column
• Main ones are:– COUNT The number of values
– SUM The sum of the values
– AVG The average of the values
– MAX and MIN The largest and smallest of the values
• If argument preceded by DISTINCT, duplicate values are eliminated before applying function
SELECT EXAMPLES(cont.)
• DISTINCT must be specified for COUNT since COUNT(*) is used to count number of rows– e.g. SELECT COUNT(DISTINCT SNo) FROM SP returns 4
– SELECT COUNT(*) FROM SP returns 12
• GROUP BY rearranges the table represented by the FROM Clause into groups– e.g. SELECT SNAME,STATUS
FROM S GROUP BY STATUS
30 Brown
30 Blue
10 White
20 Blonde
20 Pink
STATUS SNAME
SELECT Examples (cont.)
• The clauses in the SELECT are then applied to each group– e.g. SELECT PNo, SUM(QTY) FROM SP
GROUP BY PNo;
100P6
500P5
500P4
400P3
1000P2
600P1
SUM(QTY)PNo
SELECT Examples (cont.)
• The HAVING clause can be used to select groups that meet a given condition
– e.g. SELECT PNo, SUM(QTY) FROM SP GROUP BY PNo HAVING COUNT(*) > 1;
500P5
500P4
1000P2
600P1
SUM(QTY)PNo
SQL: UPDATE
• Used to update existing information in a table
• General form:UPDATE tableSET field(s) = expression {, expression }[ WHERE predicate ] ;
e.g. Double the status of all London based suppliersUPDATE P SET STATUS = 2 * STATUSWHERE CITY = ` London` ;
SQL: INSERT
• One method for adding new values into a table
• General forms:To insert a row of specific values:-INSERT INTO table [ ( field {, field } ) ]VALUES ( constant {, constant} ) ;
or to insert a copy of the table produced by a SELECT command:-INSERT INTO table [ ( field { ,field } ) ]SELECT … FROM ... WHERE …;
e.g. INSERT INTO P (PNo, CITY, WEIGHT) VALUES (`P7`, `Yate`, 24);
SQL: DELETE
• To remove values from a table
DELETE FROM table[ WHERE predicate ] ;
e.g. DELETE FROM S WHERE SNo = `S1`;
More complex SQL queries
• Because of the power of SQL it is possible to nest queries• 1) The result of any SELECT query is a logical table and
thus a SELECT clause can be used instead of a tablename– e.g. SELECT … FROM
( SELECT … FROM … WHERE …) WHERE … ;
• 2) If the result of a SELECT is a single attribute (column), then this can also behave as a set of values in a nested WHERE section– e.g. SELECT … FROM …
WHERE … IN ( SELECT … FROM … WHERE … )
Supplier
Supplier id Supplier_name Supplier_tel Supplier_add1 Supplier_add2 Supplier_add3 Supplier_add4 Supplier_postcode
F1234 Pricey & Co 01234 45678
LB100 Bulbs R Us 01234 234567
Bulby House Bulb Lane Bulbtown BU1 1LB
LB200 Lightemups 0117 9656345
Brightlights Dimview Lane Dimwitty Darksville BS1 2UP
S1234 Really Pricey Ltd 01 01 234 234
The Palace Expensive st Niceplace Deartown DT1 2XX
W1000 Cheap Trash Plc 0898 111111 The Hut By the Allotments
Near my Nan’s Nowhere Nice NN99 1FUStock_item
Stock_id Stock_description Qty_on_hand Reorder_Qty Reorder_levelSales_price_per_uni
tSupplier_code
A12341 Light Bulbs/B - 100W 165 200 100 0.30 LB100
A12343 Light Bulbs/B - 40W 110 200 100 0.25 LB100
A12351 Light Bulbs/T - 100W 175 200 100 0.25 LB200
A12352 Light Bulbs/T - 60W 250 200 100 0.25 LB200
B123657 Fuse - 25amp 164 200 100 0.75 F1234
WG1200 Food Mixer : Big Sucker 88 5 10 25.00 WG12
WG1250 Food Mixer: Weeny thing 55 30 50 12.00 WG1200
WG6610 TV : SONY :Flash Harry 22 10 15 1550.00 S1234
WG667 TV : SONY :Cheaper thing 22 10 15 550.00 S1234
WG668 TV : SONY :Quite Dear 22 10 15 950.00 S1234
WG669 TV : SONY :Outrageous 22 10 15 3550.00 S1234
WR10000 WIRE : 25 amp 100M ROLL 100 100 50 0.05 W1000
WR10003 WIRE : 125 amp 100M ROLL
100 100 50 2.50 W1000
List all the products that are supplied by the supplier of our most expensive product.
SELECT DISTINCTROW Stock_item.Supplier_code, Supplier.Supplier_name, Stock_item.Stock_id, Stock_item.Stock_description, Stock_item.Sales_price_per_unit
FROM Supplier INNER JOIN Stock_item ON Supplier.Supplier id = Stock_item.Supplier_code
WHERE Stock_item.Supplier_code=(SELECT Supplier_code FROM Stock_itemWHERE Stock_item.Sales_price_per_unit=(SELECT
Max(Sales_price_per_unit)FROM Stock_item))ORDER BY Stock_item.Sales_price_per_unit;
Query Result
Supplier_code Supplier_name Stock_id Stock_description Sales_price_per_unit
S1234 Really Pricey Ltd WG667 TV : SONY :Cheaper thing 550.00
S1234 Really Pricey Ltd WG668 TV : SONY :Quite Dear 950.00
S1234 Really Pricey Ltd WG6610 TV : SONY :Flash Harry 1550.00
S1234 Really Pricey Ltd WG669 TV : SONY :Outrageous 3550.00
Database System
DAT AO BJECT S
+DAT A
Data File
Q UERYPRO CESSO R
DAT ABASEM ANAG ER
FILE M ANAG ER
DDLPRO CESSO R
DM LPRO CESSO R
CAT ALO GM ANAG ER
SYST EMCAT ALO G
DAT AO BJECT S
DBM S
DAT ABASEADM INIST RAT O R
DAT ABASEAPPLICAT IO N
PRO G RAM
DBMS has to deal with things like:•Data Integrity
•Transaction Handling
•Record Locking
•Commit & Rollback
•Before/After Imaging
•Backup and Recovery
•Running Stored Procedures & Triggers
create table EMPLOYEE ( EMP_ID NUMERIC(12) not null, DEPT_ID NUMERIC(8) not null, EMP_SSN CHAR(9) not null, EMP_FIRST_NAME VARCHAR(20) not null, EMP_LAST_NAME VARCHAR(30) not null, EMP_BIRTH_DATE DATE not null, EMP_GENDER CHAR(1) not null, EMP_HIRE_DATE DATE not null, EMP_STREET VARCHAR(80), EMP_CITY VARCHAR(40), EMP_STATE CHAR(2), EMP_ZIP CHAR(5), constraint PK_EMPLOYEE primary key (EMP_ID), constraint AK_EMP_UID2_EMPLOYEE unique (EMP_SSN), constraint AK_EMP_UID3_EMPLOYEE unique (EMP_FIRST_NAME, EMP_LAST_NAME, EMP_BIRTH_DATE, EMP_GENDER), constraint FK_EMPLOYEE_RELATIONS_DEPARTME foreign key (DEPT_ID) references DEPARTMENT (DEPT_ID))
create table EXEMPT_EMPLOYEE ( EMP_ID NUMERIC(12) not null, EMP_MONTHLY_SALARY NUMERIC(8,2) not null, EMP_VACATION_WEEKS SMALLINT not null, constraint PK_EXEMPT_EMPLOYEE primary key (EMP_ID), constraint FK_EXEMPT_E_INHERITAN_EMPLOYEE foreign key (EMP_ID) references EMPLOYEE (EMP_ID))
create table NON_EXEMPT_EMPLOYEE ( EMP_ID NUMERIC(12) not null, UNION_ID NUMERIC(8) not null, EMP_HOURLY_RATE NUMERIC(5,2) not null, EMP_OVERTIME_RATE NUMERIC(5,2) not null, constraint PK_NON_EXEMPT_EMPLOYEE primary key (EMP_ID), constraint FK_NON_EXEM_RELATIONS_UNION foreign key (UNION_ID) references "UNION" (UNION_ID), constraint FK_NON_EXEM_INHERITAN_EMPLOYEE foreign key (EMP_ID) references EMPLOYEE (EMP_ID)
Trigger1 to prevent the same emp_id value appearing in both employee subtype tables
CREATE TRIGGER exempt_employee_checkBEFORE INSERT OR UPDATE OF emp_idON exempt_employeeFOR EACH ROWDECLARE dummy INTEGER := 0;BEGIN IF ( INSERTING OR (UPDATING AND :new.emp_id <> :old.emp_id)) THEN SELECT COUNT(*) INTO dummy FROM nonexempt_employee WHERE emp_id = :new.emp_id IF (dummy <> 0) THEN RAISE DUP_VAL_ON_INDEX; END IF; END IF;END;
Trigger2 to prevent the same emp_id value appearing in both employee subtype tables
CREATE TRIGGER non_exempt_employee_checkBEFORE INSERT OR UPDATE OF emp_idON non_exempt_employeeFOR EACH ROWDECLARE dummy INTEGER := 0;BEGIN IF ( INSERTING OR (UPDATING AND :new.emp_id <> :old.emp_id)) THEN SELECT COUNT(*) INTO dummy FROM exempt_employee WHERE emp_id = :new.emp_id IF (dummy <> 0) THEN RAISE DUP_VAL_ON_INDEX; END IF; END IF;END;
MySQL Doesn’t Support:
• Views
• Subselects
• Triggers
• Multi-Table Transaction Control
• See Chris’ paper for MySQL limitations and an overview of SQL1-SQL4 features