SWEN502 Foundations of Databases Session 2. Victoria University of Wellington, 2017, Term 2 Markus Luczak-Roesch

Similar documents
Management System for Flight Information

Part 1. Part 2. airports100.csv contains a list of 100 US airports.

FINAL EXAM: DATABASES ("DATABASES") 22/06/2010 SCHEMA

Management System for Flight Information

Solutions to Examination in Databases (TDA357/DIT620)

Introduction to Data Management CSE 344

ADVANTAGES OF SIMULATION

Model Solutions. ENGR 110: Test 2. 2 Oct, 2014

ELOQUA INTEGRATION GUIDE

myldtravel USER GUIDE

Implementation challenges for Flight Procedures

Global formulas. Page1. Video filmed with GeneXus X Evolution 2

Query formalisms for relational model relational algebra

Booking flights At the restaurant Wiki. Triggers. February 24, Grégoire Détrez Tutorial 4

Kristina Ricks ISYS 520 VBA Project Write-up Around the World

E: W: avinet.com.au. Air Maestro Training Guide Flight Records Module Page 1

myidtravel Functional Description

TIMS to PowerSchool Transportation Data Import

Knowledge Creation through User-Guided Data Mining: A Database Case

e-airportslots Tutorial

TILOS & P3 DATA INTERFACE PAUL E HARRIS EASTWOOD HARRIS PTY LTD. 24 July 2007

CSCE 520 Final Exam Thursday December 14, 2017

e-crew Horizon Air Pilot Trip Trades Phase I Notes for the Crewmembers

QuickStart Guide. Concur Premier: Travel

Aviation Software. DFT Database API. Prepared by: Toby Wicks, Software Engineer Version 1.1

The System User Manual

Preliminary Staff User s Manual. CASSi The Computerized Aircraft Scheduling System Rev. 1.28a. February 10, 2001

e-crew Horizon Air Trip Trades Notes for the Flight Attendants

PASSUR Aerospace. Departure Metering Program at Toronto Pearson International Airport. Training Manual

Course Project. 1. Let staff make entries when a passenger makes reservations on a flight.

Long Haul load factors for the month remained strong relative to last February s statistics, but both Domestic and Tasman/PI were lower:

ultimate traffic Live User Guide

Guyana Civil Aviation Authority. ATR Form M Instructions

Safety Enhancement SE ASA Design Virtual Day-VMC Displays

This document (issue 1) is issued in September Comments or queries on this document should be ed to

Notification of the Department of Air Transport. Re: Flight Operations Officer or Dispatcher Training Program

Working Draft: Time-share Revenue Recognition Implementation Issue. Financial Reporting Center Revenue Recognition

WHAT S NEW in 7.9 RELEASE NOTES

Project 2 Database Design and ETL

Option 1 Live Bookings

Portability: D-cide supports Dynamic Data Exchange (DDE). The results can be exported to Excel for further manipulation or graphing.

Draft Proposal for the Amendment of the Sub-Cap on Off-Peak Landing & Take Off Charges at Dublin Airport. Addendum to Commission Paper CP4/2003

Organizing CLF Replenishment Events into CLF Voyages The CLF Voyages Template. Jason P. Jordan

USER GUIDE Cruises Section

General Information on 24-Month OPT Extension Based on Degree in Science, Technology, Engineering, or Math (STEM)

Case No COMP/M GENERAL ELECTRIC / THOMSON CSF / JV. REGULATION (EEC) No 4064/89 MERGER PROCEDURE

2019 Vacation Bidding

Concur Travel: View More Air Fares

FLIGHT TAX SYSTEMS Users Guide to Features and Reporting Advanced Topics

Additional Boarding Setup and Daily Operations Guide

Experience Feedback in the Air Transport

4 REPORTS. The Reports Tab. Nav Log

DATA APPLICATION CATEGORY 25 FARE BY RULE

Physical Security Fleets Analyzer Saved Searches... 62

SENIOR CERTIFICATE EXAMINATIONS

PREFACE. Service frequency; Hours of service; Service coverage; Passenger loading; Reliability, and Transit vs. auto travel time.

PRIVATE PILOT GROUND SCHOOL SYLLABUS. Part 61. Revision 1 03/01/2017. Steffen Franz ADVANCED GROUND INSTRUCTOR BELMONT, CA, 94002,

Income Fund Reimbursable Salary Offset

FEES (PAYMENT SYSTEMS REGULATOR) INSTRUMENT (No 6) A. The Financial Conduct Authority makes this instrument in the exercise of:

CruisePay Enhancements for 2005 Training Guide Version 1.0

SECOND QUARTER RESULTS 2018

Concur Travel: Post Ticket Change Using Sabre Automated Exchanges

Project 2 Database Design and ETL

[Docket No. FAA ; Directorate Identifier 2006-NM-204-AD; Amendment ; AD ]

GetThere User Training

Amendment Docket No. FAA ; Directorate Identifier 2002-NM-12-AD

RNP 2 JOB AID REQUEST TO CONDUCT RNP 2 OPERATIONS

Passenger Rebooking Decision Modeling Challenge

SUPERSEDED [ U] DEPARTMENT OF TRANSPORTATION. Federal Aviation Administration. 14 CFR Part 39 [66 FR /5/2001]

GFA. New South Wales State Gliding Championships COMPETITION RULES

Integration of Hotel Room Reservation and Travel Agency

Applying Integer Linear Programming to the Fleet Assignment Problem

R1 Air Tractor, Inc.: Amendment ; Docket No. FAA ; Directorate Identifier 2006-CE-005-AD.

Product information & MORE. Product Solutions

[Docket No. FAA ; Product Identifier 2016-SW-084-AD; Amendment ; AD R1]

epods Airline Management Educational Game

Module Objectives. Creating a Manual Fare Build

Simplification Using Map Method

Concur Travel User Guide

Seventh Grade 2003 pg. 4

Friday, January 17, :30 a.m. 11:45 a.m. PRESENTED BY: Joanne Barbera, Barbera & Watkins, LLC Doug Stewart, Aircraft Logs

icrew Helpful Hints A publication of the Delta MEC Scheduling Committee February 1, 2017 Version 1

2. CANCELLATION. AC 39-7B, Airworthiness Directives, dated April 8, 1987, is canceled.

Processing and issuance of NTCA approvals

CAPABILITIES LISTING INTRODUCTION

Financial Reporting: What is Your Responsibility? Tina Kettle, United Technologies Corporation Doug Stewart, AircraftLogs Monday, Jan 16, 3:30 5:00

Table of Contents. Part I Introduction 3 Part II Installation 3. Part III How to Distribute It 3 Part IV Office 2007 &

Passenger Rebooking - Decision Modeling Challenge

SQL Practice Questions

Job Aid. ESS - Create request for Self-ticketing (Low value fares)

AIRWORTHINESS PROCEDURES MANUAL CHAPTER 26. Modifications and Repairs

SARI NPA M-02-G. SARI Part M Issue 2 dated 31 July 2017 includes inconsistency with other SARI Parts, incorrect references and omissions.

TRAFFIC COMMERCIAL AIR CARRIERS

[Docket No. FAA ; Directorate Identifier 2007-NM-204-AD; Amendment ; AD ]

Measuring the Business of the NAS

Sabre Online Quick Reference Guide

Student Visa Process. CTY Summer Programs

Ryannair Holdings plc. Sample 8

Process Guide Version 2.5 / 2017

1. SUMMARY 2. ADDITIONAL PARTICIPATION

Transcription:

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