SWEN502 Foundations of Databases Session 2 Victoria University of Wellington, 2017, Term 2 Markus Luczak-Roesch (@mluczak)
Contact Markus Luczak-Roesch markus.luczak-roesch@vuw.ac.nz @mluczak 04 463 5878 RH516
Introduction to SQL as a DML
Data modification insert into "tablename" (first_column,...last_column) values (first_value,...last_value);
Change the contents of an existing table A modification command does not return a result as a query does, but it changes the data stored in the database in some way. There are three kinds of modifications: 1. Insert a new row or rows. 2. Delete a row or rows. 3. Update (change) the value(s) of an existing row or rows.
Insertion To insert a new row into a table: INSERT INTO <table> VALUES ( <list of values> ); Example: Mary Johnson recently received a certificate for British Aerospace Jetstream 41. The Certificate table needs a new row to show this.
Insertion (eid for Mary Johnson is 141582651 aid for Jetstream 41 is 4). Certificate (eid: integer, aid: integer) INSERT INTO Certificate VALUES (141582651, 4);
Insertion (eid for Mary Johnson is 141582651 aid for Jetstream 41 is 4). Certificate (eid: integer, aid: integer) INSERT INTO Certificate VALUES (141582651, 4); The sequence of numbers is important First value is put into first column, second value into second column etc.
Specifying the Columns in INSERT INSERT INTO table_name( column1, column2...columnn) VALUES ( value1, value2...valuen); We may add to the table_name a list of attributes. There are two reasons to do so: 1. We forget the order of attributes for the relation. 2. We don t have values for all attributes, and we want the system to fill in missing components with NULL or a default value.
Example: Specifying Attributes Another way to add the fact that Mary Johnson recently received a certificate for British Aerospace Jetstream 41 to Certificate table: INSERT INTO Certificate (aid, eid) VALUES(4, 141582651); Notice the sequence of column names has changed.
Example: Specifying Column names Flight (flno: Integer, origin: Text, destination: Text, distance: Real, departure: DateTime, arrival: DateTime, fare: Real, aid: Integer) INSERT INTO flight (flno, origin, destination, distance, departure, arrival) VALUES(8079, Wellington, Dunedin, 793, 2015-10-06 11:15:00, 2015-10-06 13:05:00 ); The type of value has to match column data type.
INSERT and AUTOINCREMENT Primary Key: Surrogate vs. Natural AUTOINCREMENT Generate a unique primary identifier or primary key every time a row is added to a table This is defined when the table is CREATED
INSERT and AUTOINCREMENT
INSERT and AUTOINCREMENT Department (DeptID: integer (auto increment), DeptName: text, Budget:real, MgrEmpID: integer) INSERT INTO Department (DeptName, Budget, MgrEmpID) VALUES( Sales, 100000, 11564812);
Inserting Many Rows We may insert the entire result of a query into a table, using the form: INSERT INTO <table> ( <subquery> );
Example: Insert using a subquery Using Flights, enter into a new table InternationalFlight (flno: integer, origin: string, destination: string, distance: real, departs: time, arrives: time, fare: real) which shows the international flights that originate from USA. In our database, we have Flights to either Sydney or Tokyo. INSERT INTO InternationalFlight ( SELECT * FROM Flight WHERE destination = Sydney OR destination = Tokyo );
Deletion To delete rows satisfying a condition from a table: DELETE FROM <table> WHERE <condition>; If Where clause is not specified, all the values in the relation will be removed. DELETE FROM <table>;
Example: Deletion Delete the pilots who earn less than 5000 Employee (eid: Integer, fname:text, lname:text, salary: Integer) DELETE FROM Employee WHERE salary < 5000;
Updates To change some of the values in rows of a table: UPDATE <table> SET <list of column names> WHERE <condition on columns>; Could be a subquery
Example: Update Salary of employee eid = 48651266 was specified to be $48,651,266. However, this was a mistake. Change the salary of this employee to $274,300: UPDATE Employee SET salary = 274300 WHERE eid = 48651266 ;
Example: Update Several Rows Make minimum crusingrange to be 1000 miles for an aircraft: UPDATE Aircraft SET crusingrange = 1000 WHERE crusingrange < 1000;
Transactions A transaction is the propagation of one or more changes to the database. For example, if you are creating a record or updating a record or deleting a record from the table, you are performing transaction on the table. It is important to control transactions to ensure data integrity and to handle database errors. To save changes, you need to add COMMIT or click write changes button
Transaction INSERT INTO Employee Values (1, 'Yi-Te', 'Chiu', 100000); INSERT INTO Employee Values (1, 'Yi-Te', 'Chiu', 100000); Commit;
Data selection select "column1" [,"column2",etc] from "tablename" [where "condition"]; [] = optional
Select-From-Where Statements The principal form of a query is: SELECT FROM WHERE desired attributes one or more tables condition about tuples/records of the tables 25
Select-From-Where Statements The principal form of a query is: SELECT FROM WHERE desired attributes one or more tables condition about tuples of the tables MUST HAVE OPTIONAL 26
Select-From-Where Statements The principal form of a query is: SELECT desired attributes FROM one or more tables 1 WHERE condition about tuples of the tables 27
Select-From-Where Statements The principal form of a query is: SELECT desired attributes FROM one or more tables 1 WHERE condition about tuples of the tables 2 28
Conditions in WHERE Clause Comparison operators: =, <>, <, >, <=, >= Apply arithmetic operations String operations Special operations for comparing dates and times 29
Select-From-Where Statements The principal form of a query is: SELECT desired attributes 3 FROM one or more tables 1 WHERE condition about tuples of the tables 2 30
ER Diagram Certificate eid {FK} aid {FK} 1..* {PK} IsAssociated 1..* 1 Aircraft aid {PK} 1 mname model cruisingrange 1 1 Receives Employee Operates 1..* Flight eid {PK} fname lname salary flno {PK} origin destination distance departure arrival fare aid {FK} 31
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 Eid Aid 1 11 2 10 2 11 4 15 5 11 CERTIFICATE AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 32
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 PRIMARY KEY Eid Aid 1 11 2 10 2 11 4 15 5 11 CERTIFICATE AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 33
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 PRIMARY KEY Eid Aid 1 11 2 10 2 11 4 15 5 11 FOREIGN KEY AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 CERTIFICATE 34
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 Eid Aid 1 11 2 10 2 11 4 15 5 11 AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 PRIMARY KEY CERTIFICATE FOREIGN KEY 35
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 FOREIGN KEYS LINK TABLES TOGETHER CERTIFICATE Eid Aid 1 11 2 10 2 11 4 15 5 11 LINKING TABLE AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 36
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 CERTIFICATE Eid Aid 1 11 2 10 2 11 4 15 5 11 LINKING TABLE AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 THIS IS A 'JOIN' 37
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 Do we have a pilot who is certified to fly a Boeing 727? Eid Aid 1 11 2 10 2 11 4 15 5 11 CERTIFICATE AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 38
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 Do we have a pilot who is certified to fly a Boeing 727? Eid Aid 1 11 2 10 2 11 4 15 5 11 CERTIFICATE AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 FIND THE PK of the 727 row 39
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 Eid Aid 1 11 2 10 2 11 4 15 5 11 CERTIFICATE AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 FIND THE FK of the 727 row in the link table 40
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 FIND THE MATCHING FK in the link table Eid Aid 1 11 2 10 2 11 4 15 5 11 CERTIFICATE AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 41
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 FIND THE MATCHING PK in the EMPLOYEE table Eid Aid 1 11 2 10 2 11 4 15 5 11 CERTIFICATE AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 42
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 FIND THE MATCHING PK in the EMPLOYEE table Eid Aid 1 11 2 10 2 11 4 15 5 11 CERTIFICATE AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 So, Li Hong is certified to fly a Boeing 727 43
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 Do we have a pilot who is certified to fly a Boeing 777-300? Eid Aid 1 11 2 10 2 11 4 15 5 11 CERTIFICATE AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 44
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 Do we have a pilot who is certified to fly a Boeing 777-300? Eid Aid 1 11 2 10 2 11 4 15 5 11 CERTIFICATE AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 There are three rows WHERE aid = aid 45
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 Do we have a pilot who is certified to fly a Boeing 777-300? Eid Aid 1= 11 2 10 2= 11 4 15 5 = 11 CERTIFICATE AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 So there are three matching employees 46
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 Do we have a pilot who is certified to fly a Boeing 777-300? Eid Aid 1= 11 2 10 2= 11 4 15 5 = 11 CERTIFICATE AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 Now identify the three Employees 47
EMPLOYEE Eid Fname Lname Salary 1 John Solle 30000 2 Mary Lamb 45000 4 Li Hong 40000 5 Vejay Patel 55000 6 Jo Riise 23000 Do we have a pilot who is certified to fly a Boeing 777-300? Eid Aid 1= 11 2 10 2= 11 4 15 5 = 11 CERTIFICATE AIRCRAFT aid mname Model cruisingr ange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 15 Boeing 727 1504 These are the names of the Employees who can fly a 777-300 48
Example Using the AIRCRAFT table, show which models are made by Boeing. 1 SELECT FROM Aircraft WHERE 49
Example Using Aircraft (aid: Integer, mname: Text, model: Text, crusingrange: Integer), which models are made by Boeing? SELECT FROM Aircraft WHERE mname = 'Boeing'; 2 50
Example Using Aircraft(aid: Integer, mname: Text, model: Text, crusingrange: Integer), which models are made by Boeing? SELECT FROM Aircraft WHERE mname = 'Boeing'; 51
Example Using Aircraft(aid: Integer, mname: Text, model: Text, crusingrange: Integer), which models are made by Boeing? SELECT model FROM Aircraft WHERE mname = 'Boeing'; 3 52
Result of Query model 757-300 777-300 767-400ER 727 The answer is a relation or a table with a single attribute. 53
Operational Semantics aid mname model crusingrange 11 Boeing 777-300 6441 3 If so, include mname of the tuple/record in the result. 2 1 Visit each tuple/row of the relation/table stated in FROM Check if mname is 'Boeing' 54
* In SELECT Clauses When there is one table in the FROM clause, putting * in the SELECT clause stands for all attributes of this relation. SELECT * FROM Aircraft WHERE mname='boeing'; [= show everything] 55
Result of Query aid mname model crusingrange 10 Boeing 757-300 4010 11 Boeing 777-300 6441 12 Boeing 767-400ER 6475 15 Boeing 727 1504 56
More SQL - Date
Date Function Compute the current date SELECT date('now') AS Today; date(timestring, modifier, modifier,...) SELECT datetime('now'); datetime(timestring, modifier, modifier,...)
More SQL - Constraints
Certificate eid {FK} aid {FK} Employee eid {PK} fname lname salary 1..* 1 {PK} Receives IsAssociated 1..* 1 Aircraft aid {PK} 1 mname model cruisingrange Operates Flight flno {PK} origin destination distance departure arrival fare aid {FK} 1 1..* 1 1..* Accepts Add a new table with INTEGRITY constraints Booking bookingid {PK} flno {FK} bookdate holddate expireholddate paymentmethod
Create Table
Create Table
Create Table 63
Aircraft aid mname model cruisingrange 2 BOEING 737-800 3383 Flight flno origin destination distance departure arrival fare aid 33 Los Angles Booking Honolulu 2551 2015-09-30 09:15 2015-09-30 11:15 375.2 3 bookingid flno bookdate holddate paymentmethod 1 33 2015-09-13 15:00:00 2015-09-16 15:00:00 VISA INSERT INTO Booking (flno, bookdate,holddate, paymentmethod) VALUES (999, '2015-09-13 15:00:00', '2015-09-16 15:00:00', 'VISA'); 2 DELETE FROM Aircraft WHERE aid=2; DELETE FROM Booking WHERE flno=33; FOREIGN KEY constraint failed
Column-Based Checks To put a constraint on the value of a particular column. CHECK ( <condition> ) must be added to the declaration for the column. The condition may use the name of the column, but any other table or column name must be in a subquery. A column-based constraint is checked only when a value for that column is inserted or updated.
INSERT INTO Booking (flno, bookdate,holddate) VALUES (2, '2015-10-13 15:00:00', '2015-10-13 20:00:00');
Example Or you can do it by hand CREATE TABLE Employee ( eid integer PRIMARY KEY, fname text, lname text, salary real CHECK (salary >10000) );
More SQL - Operators
Revision The basic form of an SQL query is: SELECT some column names FROM one or more tables WHERE some condition is true in the rows of the tables 2 1 2 3
ER Diagram view Employee eid {PK} fname lname salary Receives 1 1..* Certificate eid {FK} aid {FK} {PK} IsAssociated 1..* 1 Aircraft aid {PK} 1 mname model cruisingrange 1 Operates 1..* Flight flno {PK} origin destination distance departure arrival fare aid {FK}
Additional functions for SELECT Clauses SELECT clause specifies the columns But also can do more: Listing unique values String operations Arithmetic operations Aggregate functions many others
Show unique values only DISTINCT
DISTINCT Aircraft (aid, mname, model, crusingrange) Who manufactures the Aircraft? SELECT mname FROM Aircraft; SELECT DISTINCT mname FROM Aircraft;
Manipulate Text fields in SQL STRING OPERATIONS
String Operations in SELECT Clauses We can also perform operations on strings such as combining two string columns Employees(eid: Integer, fname: Text, lname: Text, salary: Integer) Combine the fname and lname, and name the newly generated attribute as Employee Name when reporting their salaries
Example 2: String Operations in SELECT Clauses We need fname, lname, and salary attributes from employees. SELECT fname, lname, salary FROM Employee; How do we combine fname and lname attributes?
Example 2: String Operations in SELECT Clauses is for string (text) concatenation SELECT fname lname AS 'Employee Name', salary FROM Employees; concatenation = glue together
Example 2: String Operations in SELECT Clauses we need to put a space between the first name and last name of the employee. SELECT fname ' ' lname AS 'Employee Name', salary FROM Employee;
Result of Query One column, not two separate columns manufacturer Employee Name model salary Boeing James Smith 757-300 120433 Boeing 777-300 Mary Johnson 178345 John BoeingWilliams 767-400ER 153972.. Boeing.. 727.
String Pattern Matching WHERE clauses can have conditions in which a string is compared with a pattern, to see if it matches. General form: <Attribute> LIKE <pattern> or <Attribute> NOT LIKE <pattern> Pattern is a quoted string with % = any string ; E.g., WHERE ProductName LIKE % Desk _ = any single character. E.g., WHERE ProductName LIKE D_sk
Example: LIKE (%) Employee (eid: Integer, fname: Text, lname: Text, salary: Integer) Find the employees whose first name starts with J. SELECT fname, lname FROM Employee WHERE fname LIKE J% ;
Example: LIKE (_) Employee (eid: Integer, fname: Text, lname: Text, salary: Integer) Find the employees whose first name starts with J and has 5 characters in the first name. SELECT fname, lname FROM Employee WHERE fname LIKE J ; There is a space between _ characters to show how many _ is in the query. In the actual query, there is no space The result of the query should return James Smith (or Jaime, or Javin, or Joana, or. Jxxxx)
You can do calculations in SQL NUMBER OPERATIONS
Arithmetic Operators Comparison Operators: =, <>, <, >, <=, >= Arithmetic Operators: +, -, *, /, % Example : HR Manager would like to see each employee s current salary and their new salary if salary is increased by 10%. Properly name the newly calculated column.
Example: Arithmetic Operators Employee (eid, fname, lname, salary) HR Manager would like to see each employee s current salary and their new salary if salary is increased by 10%. Properly name the newly calculated column. SELECT fname, lname, salary AS 'Current Salary', salary*1.10 AS 'New Salary' FROM Employee; 10% salary increase Naming the calculated column as New Salary
Class Exercise: Arithmetic Operators Find employees whose monthly salary is greater than $10,000. Show their name and monthly salary. Sort the result by monthly salary in descending order. SELECT FROM WHERE Certificate eid {FK} aid {FK} eid {PK} fname lname salary 1..* 1 {PK} Receives Employee IsAssociated 1..* 1 Aircraft aid {PK} mcompany model cruiserange Operates 1 1 1..* Flight flno {PK} origin destination distance departure_time arrival_time fare aid {FK}
Class Exercise: Arithmetic Operators - Solution Find employees whose monthly salary is greater than $10,000. Show their name and monthly salary. Sort the result by monthly salary in descending order. SELECT fname, lname, salary/12 AS 'Monthly Salary' FROM Employee WHERE salary/12 > 10000 ORDER BY salary/12 DESC;
Class Exercise: Results
You can make decisions in SQL LOGICAL OPERATORS
Logical Operators (or Boolean Operators) AND: Joins two or more tests and returns rows only when all results are true. OR: Joins two or more tests and returns rows when any result is true. NOT: Negates an expression
Logical Operators An expression is evaluated left to right Subexpressions in brackets are evaluated first NOTs are evaluated before ANDs and ORs ANDs are evaluated before ORs
The AND Operator Syntax: SELECT desired attributes FROM table or tables WHERE [condition1] AND [condition2]...and [conditionn];
Example: AND Operator Find the employees whose first name is not James earn more than 250000. SELECT fname, lname FROM Employee WHERE fname<> James Not equal AND salary > 250000 Combines two conditions
Example: AND Operator Find the employees whose first name is not James earn between $100,000 and $250,000. SELECT fname, lname FROM Employees WHERE fname<> James AND salary >= 100000 AND salary <= 250000 ALTERNATIVE: salary BETWEEN 100000 AND 250000
The OR Operator Syntax: SELECT desired attributes FROM table or tables WHERE [condition1] OR [condition2]...or [conditionn];
Example: OR Operator Find the employees whose first name is Michael or James. Also, the employees must earn more than $90,000. SELECT fname, lname, salary FROM Employee WHERE fname = Michael OR fname = James AND salary > 90000
Example: OR Operator Find the employees (fname, lname) whose first name is Michael or James. Also, the employees must earn more than $90,000. SELECT fname, lname,, salary FROM Employee WHERE (fname = Michael OR fname = James ) AND salary > 90000
WHERE Clause: Other Special Operators IS NULL: Used to check whether an attribute is null
Example: IS NULL Check the null data entry for the fare column in the Flight table SELECT * FROM Flight WHERE fare IS NULL
WHERE Clause: Other Special Operators IN: used to check whether an attribute value matches any value with in a value list. Find the details of aircraft of the following models: 747-400, 737-800, 757-300, 777-300 SELECT * FROM Aircraft WHERE model='747-400' OR model='737-800' OR model='757-300' OR model = '777-300 ;
WHERE Clause: Other Special Operators IN: used to check whether an attribute value matches any value with in a value list. Find the details of aircraft of the following models: 747-400, 737-800, 757-300, 777-300 SELECT * FROM Aircraft WHERE model IN ('747-400', '737-800', '757-300', '777-300');
More SQL - Joins
Multi-table Queries To answer some queries we often need to combine data from more than one table. This is called a JOIN The join matches row values contained in columns in two or more tables. 103
Formal Semantics Almost the same as for single table queries: Enter the list of attributes and expressions in the SELECT clause Specify all the tables in the FROM clause. Indicate the common columns used to link the tables. Apply the condition(s) to the WHERE clause. 104
Example1: Multi Table Queries Find the name of the pilots who are certified to fly aid=4 SELECT FROM Employee, Certificate WHERE Certificate eid {FK} aid {FK} 1..* 1 {PK} Receives Employee IsAssociated 1..* 1 Aircraft aid {PK} 1 mname model cruisingrange Operates 1 1..* Flight eid {PK} fname lname salary flno {PK} origin destination distance departure arrival fare aid {FK} 105
Product of Tables: NOT! REMEMBER Multi Table QUERIES MULTIPLY THE TABLES SPECIFIED IN THE FROM CLAUSE!!!! Example1: SELECT * FROM Employee, Certificate 61 records in the Certificate table 31 records in the Employee table 106
Example1: Multi Table Queries Find the name of the pilots who are certified to fly aid=4 SELECT FROM Employee, Certificate WHERE Certificate.aid=4; 3 records in the Certificate table with aid=4 31 records in the Employee table 107
Example1: Multi Table Queries Find the name of the pilots who are certified to fly aid=4 SELECT Employee.fname ' ' Employee.lnameAS 'Employee, * FROM Employee, Certificate WHERE Certificate.aid=4 AND Employee.eid=Certificate.eid ; 108
Operational Semantics eid fname lname salary eid aid 567354612 Lisa Walker 256481 567354612 4 Employees 3 If both conditions are true, output fname and lname 1 Check these are equal Certified 2 Check for aid=4 109
Certificate eid {FK} aid {FK} Employee eid {PK} fname lname salary 1..* 1 {PK} Receives IsAssociated 1..* 1 Aircraft aid {PK} 1 mname model cruisingrange Operates Flight flno {PK} origin destination distance departure arrival fare aid {FK} 1 1..* 110
Alternative ways to join multiple tables Use JOIN keyword 1. SELECT column-list FROM table 1 JOIN table 2 USING (common-column) SELECT Employee.fname ' ' Employee.lname AS Employee FROM Employee JOIN Certificate USING (eid) WHERE Certificate.aid=4 111
Alternative ways to join multiple tables Use JOIN keyword 2. SELECT column-list FROM table 1 JOIN table 2 ON joint-condition SELECT Employee.fname ' ' Employee.lname AS Employee FROM Employee JOIN Certificate ON Employee.eid=Certificate.eid AND Certificate.aid=4 112
Alternative ways to join multiple tables Use JOIN keyword 3. SELECT column-list FROM table 1 NATURAL JOIN table 2 SELECT Employee.fname ' ' Employee.lname AS Employee FROM Employee NATURAL JOIN Certificate 113
CLASS Exercise: Multi Table Queries Find the name of the pilots who are certified to fly aid=4. The query result should also include the manufacturer and model of aircraft with aid=4. Certificate eid {FK} aid {FK} 1..* 1 {PK} Receives Employee IsAssociated 1..* 1 Aircraft aid {PK} 1 mname model cruisingrange Operates 1 1..* Flight eid {PK} fname lname salary flno {PK} origin destination distance departure arrival fare aid {FK} 114
CLASS Exercise: Multi Table Queries Find the name of the pilots who are certified to fly aid=4. The query result should also include the manufacturer and model of aircraft with aid=4. This is similar to the previous example. SELECT fname ' ' lname AS 'Employee' FROM Employee, Certificate, Aircraft WHERE Employee.eid=Certificate.eid AND Aircraft.aid=4; Let s first update FROM clause 115
CLASS Exercise: Multi Table Queries Find the name of the pilots who are certified to fly aid=4. The query result should also include the manufacturer and model of aircraft with aid=4 SELECT fname ' ' lname AS 'Employee' FROM Employee, Certificate, Aircraft WHERE Employee.eid=Certificate.eidAND Aircraft.aid=Certificate.aid AND Aircraft.aid=4; Certificate eid {FK} aid {FK} 1..* {PK} IsAssociated 1..* 1 Aircraft aid {PK} 1 mname model cruisingrange 1 We need to update WHERE Clause. Certificate table is used to connect Employee and Aircraft tables. eid {PK} fname lname salary 1 Receives Employee Operates Flight flno {PK} origin destination distance departure arrival fare 1..* 116
CLASS Exercise: Multi Table Queries Find the name of the pilots who are certified to fly aid=4. The query result should also include the manufacturer and model of aircraft with aid=4 SELECT fname ' ' lname AS 'Employee, mname, model FROM Employee, Certificate, Aircraft WHERE Employee.eid=Certificate.eid AND Aircraft.aid=Certificate.aid AND Aircraft.aid=4; Finally, we update the SELECT clause 117
Result of Query Employee mname model Lisa Walker British Aerospace Jetstream 41 George Wright British Aerospace Jetstream 41 Eric Cooper British Aerospace Jetstream 41 118
Using Table Alias table_name AS table alias table_name table_alias SELECT fname ' ' lname AS 'Employee, mname, model FROM Employee E, Certificate C, Aircraft A WHERE E.eid=C.eidAND A.aid=C.aidAND A.aid=4; SELECT fname ' ' lname AS 'Employee, mname, model FROM Employee E, Certificate C, Aircraft A WHERE Employee.eid=C.eidANDA.aid=C.aid ANDA.aid=4; 119
CLASS Exercise cont d: Multi Table Queries Find the name of the pilots who are certified to fly aid=4. The query result should also include the manufacturer and model of aircraft with aid=4. Write SQL statement using JOIN keyword. SELECT column-list FROM table 1 JOIN table 2 USING (common-column) SELECT column-list FROM table 1 JOIN table 2 ON joint-condition 120
CLASS Exercise cont d: Multi Table Queries Find the name of the pilots who are certified to fly aid=4. The query result should also include the manufacturer and model of aircraft with aid=4. Write SQL statement using JOIN keyword. SELECT fname ' ' lname AS 'Employee', mname, model FROM Employee JOIN Certificate USING (eid) JOIN Aircraft USING (aid) WHERE Aircraft.aid=4; SELECT fname ' ' lname AS 'Employee', mname, model FROM Employee JOIN Certificate JOIN Aircraft ON Employee.eid=Certificate.eid AND Aircraft.aid=Certificate.aid AND Aircraft.aid=4; 121
CLASS EXERCISE Find the pilots who are certified to fly aircraft manufactured by Airbus or Boeing. We are looking pilots whose last name does NOT start with W. Your query result should show the name of the pilot, manufacturer, model, and crusingrange of the aircraft. Certificate eid {FK} aid {FK} eid {PK} fname lname salary 1..* 1 {PK} Receives Employee IsAssociated 1..* 1 Aircraft aid {PK} 1 mname model cruisingrange Operates Flight flno {PK} origin destination distance departure arrival fare aid {FK} 1 1..* 122
CLASS EXERCISE - Solution Find the pilots who are certified to fly aircrafts manufactured by Airbus or Boeing. We are looking pilots whose last name does NOT start with W. Your query result should show the name of the pilot, manufacturer, model, and crusingrange of the aircraft. SELECT fname, lname, mname, model, crusingrange FROM Aircraft A, Certificate C, Employee E WHERE A.aid=C.aid AND C.eid=E.eid AND A.mname IN ('Airbus', 'Boeing') AND E.lname NOT LIKE 'W%'; Certificate eid {FK} aid {FK} eid {PK} fname lname salary 1..* 1 {PK} Receives Employee IsAssociated 1..* 1 Aircraft aid {PK} 1 mname model cruisingrange Operates Flight flno {PK} origin destination distance departure arrival fare aid {FK} 1 1..* 123