IST 210 SQL Todd Bacastow IST 210: Organization of Data.

33
IST 210 SQL Todd Bacastow IST 210: Organization of Data

Transcript of IST 210 SQL Todd Bacastow IST 210: Organization of Data.

Page 1: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 SQL

Todd BacastowIST 210: Organization of Data

Page 2: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 SELECT StatementSELECT [DISTINCT | ALL]

{* | [column_expression [AS new_name]] [,...] }FROM table_name [alias] [, ...][WHERE condition][GROUP BY column_list] [HAVING condition][ORDER BY column_list]

Reserved Keywords and User-defined words Case insensitive, free format Proper formatting for readability. Common norms:

Each clause should begin on a new line. Start of a clause should line up with start of other clauses. If clause has several parts, should each appear on a separate

line and be indented under start of clause.

Page 3: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 SELECT Statement

FROM Specifies table(s) to be used.

WHERE Filters rows.GROUP BY Forms groups of rows

with same column value.HAVING Filters groups subject to

somecondition.

SELECT Specifies which columns are to

appear in output.ORDER BY Specifies the order of the

output.

Page 4: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 DreamHome ExampleDreamHome is a company which

specializes in the management of properties for rent on behalf of the owners.

Services: Advertising propertiesInterviewing rentersOrganizing visits to propertiesNegotiating lease agreements.

Page 5: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210

DreamHome Example Database

Branch (Bno, Street, Area, City, Pcode, Tel_No, Fax_No)

Staff (Sno, FName, LName, Address, Tel_No, Position, Sex, DOB, Salary, NIN, Bno)

Property_for_rent (Pno, Street, Area, City, Pcode, Type, Rooms, Rent, Ono, Sno, Bno)

Renter (Rno, Fname, Lname, Adress, Tel_No, Pref_Type, Max_Rent, Bno)

Owner (Ono, Fname, Lname, Address, Tel_No)

Viewing (Rno, Pno, Date, Comment)

Page 6: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 All Columns, All Rows Example:

List full details of all staff.SELECT sno, fname, lname, address,

tel_no, position, sex, dob, salary, nin, bno

FROM staff;

Can use * as an abbreviation for 'all columns':

SELECT *FROM staff;

Page 7: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Specific Columns, All Rows Example

Produce a list of salaries for all staff, showing only the staff number, Sno, the first and last names, and the salary details.

SELECT sno, fname, lname, salaryFROM staff;

Page 8: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Use of DISTINCT

SELECT pnoFROM viewing;

SELECT DISTINCT pno

FROM viewing;

List the property numbers of all properties that have been viewed.

Page 9: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Calculated Fields Query

Produce a list of monthly salaries for all staff, showing the staff number, the first and last names, and the salary details.

SELECT sno, fname, lname, salary/12

FROM staff;To name column, use AS clause:

SELECT sno, fname, lname, salary/12 AS monthly_salary

FROM staff;

Monthly_salary

Page 10: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210

Comparison Search Condition

Query: List all staff with a salary greater than 10,000.

SELECT sno, fname, lname, position, salary

FROM staffWHERE salary > 10000;

Page 11: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210

Compound Comparison Search

Condition

Query: List the addresses of all branch offices in

London or Glasgow.

SELECT bno, street, area, city, pcodeFROM branchWHERE city = 'London' OR city = 'Glasgow';

Page 12: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Range Search Condition - BETWEEN

Query:List all staff with a salary between

20,000 and 30,000.

SELECT sno, fname, lname, position, salaryFROM staffWHERE salary BETWEEN 20000 AND 30000;

Page 13: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210

Range Search Condition (Cont…)

BETWEEN test includes the endpoints of range. Equivalent to

SELECT sno, fname, lname, position, salaryFROM staffWHERE salary>=20000 AND salary <= 30000;

BETWEEN does not add much to SQL's expressive power

Also a negated version NOT BETWEEN.

Page 14: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210

Set Membership - IN / NOT IN Query: List all Managers and Deputy

Managers.

SELECT sno, fname, lname, position

FROM staffWHERE position IN ('Manager', 'Deputy');

Page 15: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Pattern Matching - LIKE SQL has two special pattern matching symbols:

%: sequence of zero or more characters; _ (underscore): any single character.

LIKE '%Glasgow%' means a sequence of characters of any length containing 'Glasgow'.

Query: Find all staff with the string 'Glasgow' in their address.

SELECT sno, fname, lname, address, salaryFROM staffWHERE address LIKE '%Glasgow%';

Page 16: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 NULL Search Condition NULL value can not be checked by comparison

operators Have to test for null explicitly using special

keyword IS NULL IS NOT NULL can test for non-null values. Example query:

List details of all viewings on property PG4 where a comment has not been supplied.

SELECT rno, dateFROM viewingWHERE pno = 'PG4' AND

comment IS NULL;

Page 17: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 ORDER BY Example Query:

List salaries for all staff, arranged in descending order of salary.

SELECT sno, fname, lname, salaryFROM staffORDER BY salary DESC;

When no (ASC/DESC) is indicated, default order is ascending (ASC).

Can sort on multiple columns.SELECT pno, type, rooms, rentFROM property_for_rentORDER BY type, rent DESC;

Page 18: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 SELECT Statement - Aggregates Five aggregate functions:

COUNT returns number of values in a specified column.

SUM returns sum of values in a specified column.

AVG returns average of values in a specified column.

MIN returns smallest value in a specified column.

MAX returns largest value in a specified column.

Page 19: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Aggregates - Examples

Example 1: How many different properties viewed in May ‘98?SELECT COUNT (DISTINCT pno) AS countFROM viewingWHERE date BETWEEN DATE'1998-05-01’ AND DATE'1998-05-31';

Example 2: Find number of Managers and sum of their salaries.

SELECT COUNT(sno) AS count, SUM(salary) AS sumFROM staffWHERE position = 'Manager';

Example 3: Find minimum, maximum, and average staff salary.

SELECT MIN(salary) AS min, MAX(salary) AS max, AVG(salary) AS avg FROM staff;

Page 20: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Aggregates - summary

Each operates on a single column of a table and return single value.

COUNT, MIN, and MAX apply to numeric and non-numeric fields, but SUM and AVG may be used on numeric fields only.

Apart from COUNT(*), each function eliminates nulls first and operates only on remaining non-null values.

COUNT(*) counts all rows of a table, regardless of whether nulls or duplicate values occur.

Can use DISTINCT before column name to eliminate duplicates.

Aggregate functions can be used only in SELECT list and in HAVING clause.

Page 21: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 GROUP BY and HAVING Use GROUP BY clause to get sub-totals. SELECT and GROUP BY closely integrated: each item in

SELECT list must be single-valued per group, and SELECT clause may only contain:

Column names. Aggregate functions. Constants. An expression involving combinations of the above.

If WHERE is used with GROUP BY, WHERE is applied first, then groups are formed from remaining rows satisfying predicate.

Considers two nulls to be equal for purposes of GROUP BY.

Page 22: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210

59

Use of GROUP BY

Example: Find number of staff in each branch and their total salaries.

SELECT bno, COUNT(sno) AS count, SUM(salary) AS sumFROM staffGROUP BY bnoORDER BY bno;

Page 23: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Restricted Grouping - HAVING HAVING clause is designed for use with GROUP BY

clause to restrict groups that appear in final result table. HAVING filters groups. Column names in HAVING clause must also appear in

the GROUP BY list or be contained within an aggregate function.

Example: For each branch with more than 1 member of staff, find number of staff in each branch and sum of their salaries.

SELECT bno, COUNT(sno) AS count, SUM(salary) AS sumFROM staffGROUP BY bno HAVING COUNT(sno) > 1ORDER BY bno;

Page 24: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Subqueries A subselect can be used in WHERE clauses of an

outer SELECT, where it is called a subquery or nested query.

Example: List staff who work in branch at '163 Main St'.

SELECT sno, fname, lname, positionFROM staffWHERE bno =

(SELECT bno FROM branch WHERE street = '163 Main St');

Page 25: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Subquery with Aggregate Example: List all staff whose salary is greater than the average

salary.

SELECT sno, fname, lname, position, salaryFROM staffWHERE salary >

(SELECT avg(salary) FROM staff);

Cannot write 'WHERE salary > avg(salary)'. Instead, use subquery to find average salary (17000), and then

use outer SELECT to find those staff with salary greater than 17000

Subquery SELECT list must consist of a single column name or expression, except for subqueries that use EXISTS.

Page 26: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 ANY/SOME and ALL If subquery preceded by ALL, condition will

only be true if it is satisfied by all values produced by subquery.

If subquery preceded by ANY, condition will be true if it is satisfied by any values produced by subquery.

If subquery is empty, ALL returns true, ANY returns false.

Page 27: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Example of ANY and ALL Example1: Find staff whose salary is larger than salary of at

least 1 member of staff at branch B3.SELECT sno, fname, lname, position, salaryFROM staffWHERE salary >ANY

(SELECT salary FROM staff WHERE bno = 'B3');

Example 2: Find staff whose salary is larger than salary of every member of staff at branch B3.

SELECT sno, fname, lname, position, salaryFROM staffWHERE salary > ALL

(SELECT salary FROM staff WHERE bno = 'B3');

Page 28: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Multi-Table Queries If result columns come from more than

one table must use a join. To perform join, include more than one

table in FROM clause. Use comma as separator and typically

include WHERE clause to specify join column(s).

Page 29: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Sorting a join Consider: For each branch, list

names of staff who manage properties.

SELECT s.bno, s.sno, fname, lname, pnoFROM staff s, property_for_rent pWHERE s.sno = p.snoORDER BY s.bno, s.sno, pno;

Page 30: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Three Table Join Consider:

For each branch, list staff who manage properties, including city in which branch is located and properties they manage.

SELECT b.bno, b.city, s.sno, fname, lname, pnoFROM branch b, staff s, property_for_rent pWHERE b.bno = s.bno AND s.sno = p.snoORDER BY b.bno, s.sno, pno;

Page 31: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Outer Joins With a join, if one row of a table is unmatched,

row is omitted from result table. The outer join operations retain rows that do not

satisfy the join condition. Consider following two simplified tables:

BRANCH1 PROPERTY_FOR_RENT1bno city pno pcityB3 Glasgow PA14

AberdeenB4 Bristol PL94 LondonB2 London PG4

Glasgow

Page 32: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Outer Joins The (inner) join of these two tables:

SELECT b.*, p.*FROM branch1 b, property_for_rent1 pWHERE b.bcity = p.pcity;

Left Outer JoinSELECT b.*, p.*FROM branch1 b LEFT JOIN

property_for_rent1 p ON b.bcity = p.pcity;

Right Outer JoinSELECT b.*, p.*FROM branch1 b RIGHT JOIN

property_for_rent1 p ON b.bcity = p.pcity;

Page 33: IST 210 SQL Todd Bacastow IST 210: Organization of Data.

IST 210 Full Outer Join

Includes those rows that are unmatched in both tables.

Unmatched columns are filled with NULLs. Consider:

List branches and properties in same city and any unmatched branches or properties.

SELECT b.*, p.*

FROM branch1 b FULL JOIN

property_for_rent1 p

ON b.bcity = p.pcity;