You are on page 1of 78

Chapter 3

SQL and QBE Transparencies

© Pearson Education Limited, 2004

1

Chapter 3 - Objectives
     

Purpose and importance of SQL. How to retrieve data using SELECT. How to insert data using INSERT. How to update data using UPDATE. How to delete data using DELETE. How to create new tables using CREATE TABLE. About an alternative language, QBE.
© Pearson Education Limited, 2004 2

SQL
 

Main language for relational DBMSs. Main characteristics:  relatively easy to learn;  non-procedural - you specify what information you require, rather than how to get it;  essentially free-format;  consists of standard English words like SELECT, INSERT, and UPDATE;  can be used by Pearson Education Limited, © range of users.
2004

3

Importance of SQL     First and. 2004 4 . so far. only standard database language to gain widespread acceptance. Used as the basis for other standards. Huge investment from both vendors and users. Federal Information Processing Standard (FIPS). © Pearson Education Limited.

© Pearson Education Limited. delete. Must perform these tasks with minimal user effort. update. Must be easy to learn.Objectives of SQL    Ideally database language should let user:  create database and table structures.  perform both simple and complex queries.  perform basic tasks like insert. 2004 5 .

Objectives of SQL    SQL is a transform-oriented language with 2 major components:  a DDL for defining database structure. C++). SQL can be used interactively or embedded in a high-level language (eg.  a DML for retrieving and updating data. SQL did not contain flow of control commands (not computationally complete). Until SQL3. © Pearson Education Limited. 2004 6 . C.

views.Writing SQL Commands  SQL statement consists of reserved words and user-defined words. 2004 7 – – . Reserved words: fixed part of SQL and must be spelt exactly as required and cannot be split across lines. © Pearson Education Limited. User-defined words: made up by user and represent names of various database objects such as tables. columns.

2004 8 . except for literal character data. … indicates optional repetition (0 or more). © Pearson Education Limited. Use extended form of BNF notation: . Square brackets indicate an optional element. Lower-case letters represent user-defined words.Upper-case letters represent reserved words. | indicates a choice among alternatives. Curly braces indicate a required element.Writing SQL Commands   Most components of an SQL statement are case insensitive.

00). „London‟). All non-numeric literals must be enclosed in single quotes (eg. 2004 9 . All numeric literals must not be enclosed in quotes (eg.Literals    Literals are constants used in SQL statements. 650. © Pearson Education Limited.

2004 10 . ..] [WHERE condition] [GROUP BY columnList] [HAVING condition] [ORDER BY columnList] © Pearson Education Limited..] } FROM TableName [alias] [.SELECT Statement SELECT [DISTINCT | ALL] {* | [columnExprn [AS newName]] [....

SELECT Statement FROM Specifies table(s) to be used. © Pearson Education Limited. HAVING Filters groups subject to some condition. ORDER BY Specifies the order of the output. WHERE Filters rows. 2004 11 . SELECT Specifies which columns are to appear in output. GROUP BY Forms groups of rows with same column value.

Only SELECT and FROM are mandatory.  © Pearson Education Limited. 2004 12 .SELECT Statement  Order of the clauses cannot be changed.

directorNo FROM Video. SELECT catalogNo. 2004 13 . price. category.3. All Rows List full details of all videos. © Pearson Education Limited. dailyRental.  Can use * as an abbreviation for „all columns‟: SELECT * FROM Video.1 All Columns. title.

2004 14 .1 All Columns.3. All Rows © Pearson Education Limited.

title. © Pearson Education Limited.3. title and daily rental rate of all videos. dailyRental FROM Video.2 Specific Columns. All Rows List the catalog number. 2004 15 . SELECT catalogNo.

2 Specific Columns. All Rows © Pearson Education Limited.3. 2004 16 .

2004 17 .3. SELECT category FROM Video. © Pearson Education Limited.3 Use of DISTINCT List all video categories.

© Pearson Education Limited.3 Use of DISTINCT  Use DISTINCT to eliminate duplicates: SELECT DISTINCT category FROM Video.3. 2004 18 .

title.3. dailyRental*3 FROM Video. © Pearson Education Limited. 2004 19 .4 Calculated Fields List rate for renting videos for 3 days. SELECT catalogNo.

title. dailyRental*3 AS threeDayRate FROM Video. use AS clause: SELECT catalogNo.3. 2004 20 .4 Calculated Fields  To name column. © Pearson Education Limited.

3. 2004 21 .5 Comparison Search Condition List all staff with a salary greater than $10. salary FROM Staff WHERE salary > 10000. name. SELECT staffNo.000. © Pearson Education Limited. position.

000 and $50.6 Range Search Condition List all staff with a salary between $45.000. 2004 22 . salary FROM Staff WHERE salary BETWEEN 45000 AND 50000. © Pearson Education Limited.  BETWEEN test includes the endpoints of range.3. name. SELECT staffNo. position.

2004 23 .6 Range Search Condition © Pearson Education Limited.3.

though.3. name.  Useful. BETWEEN does not add much to SQL‟s expressive power. Could also write: SELECT staffNo. 2004 24 . salary FROM Staff WHERE salary >= 45000 AND salary <= 50000. for a range of values. position.6 Range Search Condition   Also a negated version NOT BETWEEN. © Pearson Education Limited.

7 Set Membership List all videos in the Action and Children categories. title. category FROM Video WHERE category IN („Action‟. © Pearson Education Limited.3. SELECT catalogNo. 2004 25 . „Children‟).

title.  IN does not add much to SQL‟s expressive power. Could have expressed this as:  SELECT catalogNo.7 Set Membership There is a negated version (NOT IN). category FROM Video WHERE category =„Action‟ OR category =„Children‟  IN is more efficient when set contains many values.3. 2004 26 . © Pearson Education Limited.

© Pearson Education Limited.3.8 Pattern Matching List all staff whose first name is Sally. position. 2004 27 . name. SELECT staffNo. salary FROM Staff WHERE name LIKE „Sally*‟.

8 Pattern Matching  SQL has two special pattern matching symbols:   *: sequence of zero or more characters. 2004 28 . ? (question mark): any single character.3.  LIKE „Sally*‟ means the first 5 characters must be Sally followed by anything. © Pearson Education Limited.

videoNo FROM RentalAgreement WHERE dateReturn IS NULL. © Pearson Education Limited.3.  Have to test for null explicitly using special keyword IS NULL: SELECT dateOut. memberNo. 2004 29 .9 NULL Search Condition List the video rentals that have not yet been returned.

9 NULL Search Condition  Negated version (IS NOT NULL) can test for non-null values.3. © Pearson Education Limited. 2004 30 .

© Pearson Education Limited. 2004 31 . SELECT * FROM Video ORDER BY price DESC.10 Single Column Ordering List all videos in descending order of price.3.

2004 32 .3.10 Single Column Ordering © Pearson Education Limited.

SUM returns sum of values in specified column.Aggregates  ISO SQL defines five aggregate functions: COUNT returns number of values in specified column. MAX returns largest value in specified column.SELECT Statement . 2004 33 . MIN returns smallest value in specified column. © Pearson Education Limited. AVG returns average of values in specified column.

MIN. Apart from COUNT(*). 2004 34   .SELECT Statement . but SUM and AVG only for numeric fields. and MAX apply to numeric and non-numeric fields. COUNT. each function eliminates nulls first and operates only on remaining non-null values. © Pearson Education Limited.Aggregates  Each operates on a single column of a table and returns a single value.

regardless of whether nulls or duplicate values occur.Aggregates    COUNT(*) counts all rows of a table. DISTINCT has no effect with MIN/MAX. Can use DISTINCT before column name to eliminate duplicates. © Pearson Education Limited. but may have with SUM/AVG.SELECT Statement . 2004 35 .

following is illegal: SELECT staffNo. SELECT list cannot reference a column out with an aggregate function. © Pearson Education Limited. For example. COUNT(salary) FROM Staff.Aggregates    Aggregate functions can be used only in SELECT list and in HAVING clause.SELECT Statement . 2004 36 . If SELECT list includes an aggregate function and there is no GROUP BY clause.

SELECT COUNT(staffNo) AS totalStaff. © Pearson Education Limited.11 Use of COUNT and SUM List total number of staff with salary greater than $40.000 and the sum of their salaries.3. 2004 37 . SUM(salary) as totalSalary FROM Staff WHERE salary > 40000.

2004 38 .3.11 Use of COUNT and SUM © Pearson Education Limited.

3. maximum. MAX(salary) AS maxSalary. AVG(salary) AS avgSalary FROM Staff. MAX and AVG List the minimum. average staff salary. 2004 39 .12 Use of MIN. and SELECT MIN(salary) AS minSalary. © Pearson Education Limited.

SELECT and GROUP BY closely integrated: each item in SELECT list must be singlevalued per group. 2004 40 . and SELECT clause may only contain:  column names  aggregate functions  constants  expression with combination of above.SELECT Statement .Grouping   Use GROUP BY clause to get sub-totals. © Pearson Education Limited.

© Pearson Education Limited. 2004 41   .Grouping  All column names in SELECT list must appear in GROUP BY clause unless used only in an aggregate function. ISO considers two nulls to be equal for purposes of GROUP BY. then groups are formed from remaining rows satisfying predicate. WHERE is applied first.SELECT Statement . If used.

COUNT(staffNo) AS totalStaff. SELECT branchNo.13 Use of GROUP BY Find number of staff in each branch and sum of their salaries. © Pearson Education Limited. SUM(salary) AS totalSalary FROM Staff GROUP BY branchNo ORDER BY branchNo.3. 2004 42 .

13 Use of GROUP BY © Pearson Education Limited.3. 2004 43 .

Column names in HAVING clause must also appear in the GROUP BY list or be contained within an aggregate function.Restricted Groupings – HAVING clause  HAVING clause designed for use with GROUP BY to restrict groups that appear in final result table. © Pearson Education Limited. Similar to WHERE. but WHERE filters individual rows whereas HAVING filters groups. 2004   44 .

find number of staff in each branch and sum of their salaries. 2004 45 . SELECT branchNo.3. COUNT(staffNo) AS totalStaff. SUM(salary) AS totalSalary FROM Staff GROUP BY branchNo HAVING COUNT(staffNo) > 1 ORDER BY branchNo. © Pearson Education Limited.14 Use of HAVING For each branch with more than 1 member of staff.

3. 2004 46 .14 Use of HAVING © Pearson Education Limited.

and DELETE statements. where it is called a subquery or nested query. A subselect can be used in WHERE and HAVING clauses of an outer SELECT. © Pearson Education Limited.Subqueries  Some SQL statements can have a SELECT embedded within them. UPDATE. Subselects may also appear in INSERT. 2004 47   .

name. position FROM Staff WHERE branchNo = (SELECT branchNo FROM Branch WHERE street=„8 Jefferson Way‟). © Pearson Education Limited.3.15 Subquery with Equality Find staff who work in branch at „8 Jefferson Way‟. 2004 48 . SELECT staffNo.

2004 49 . Outer SELECT then becomes: SELECT staffNo.3.15 Subquery with Equality    Inner SELECT finds branch number for branch at „8 Jefferson Way‟ („B001‟). name. Outer SELECT then retrieves details of all staff who work at this branch. © Pearson Education Limited. position FROM Staff WHERE branchNo = „B001‟.

3. 2004 50 .15 Subquery with Equality © Pearson Education Limited.

2004 51 . position FROM Staff WHERE salary > (SELECT AVG(salary) FROM Staff). SELECT staffNo.16 Subquery with Aggregate List all staff whose salary is greater than the average salary. © Pearson Education Limited.3. name.

name.67. 2004 52 . © Pearson Education Limited. and then use outer SELECT to find those staff with salary greater than this: SELECT staffNo.67). use subquery to find average salary (41166.16 Subquery with Aggregate   Cannot write „WHERE salary > AVG(salary)‟ Instead. position FROM Staff WHERE salary > 41166.3.

2004 53 .3.16 Subquery with Aggregate © Pearson Education Limited.

2004 54 . By default. Can refer to a table in FROM using an alias. © Pearson Education Limited.Subquery Rules    ORDER BY clause may not be used in a subquery (although it may be used in outermost SELECT). column names refer to table name in FROM clause of subquery. Subquery SELECT list must consist of a single column name or expression. except for subqueries that use EXISTS.

Subquery Rules   When subquery is an operand in a comparison. A subquery may not be used as an operand in an expression. subquery must appear on righthand side. © Pearson Education Limited. 2004 55 .

To perform join. © Pearson Education Limited. 2004 56 . Use comma as separator with typically a WHERE to specify join column(s).Multi-Table Queries     Can use subqueries provided result columns come from same table. include more than one table in FROM clause. If result columns come from more than one table must use a join.

Alias can be used to qualify column names when there is ambiguity. © Pearson Education Limited. Alias is separated from table name with a space. 2004 57 .Multi-Table Queries    Also possible to use an alias for a table named in FROM clause.

Director d WHERE v. title. 2004 58 .3. v.directorNo.17 Simple Join List all videos along with the name of the director. SELECT catalogNo.directorNo = d.directorNo. directorName FROM Video v. category. © Pearson Education Limited.

3.directorNo) included in result. © Pearson Education Limited.17 Simple Join  Only those rows from both tables with identical values in the directorNo columns (v. 2004 59 .directorNo = d.

Alternative JOIN Constructs  Alternative ways to specify joins: FROM Video v JOIN Director d ON v. first produces table with two identical directorNo columns. © Pearson Education Limited. 2004 60 .directorNo = d.directorNo FROM Video JOIN Director USING directorNo FROM Video NATURAL JOIN Director  FROM replaces original FROM and WHERE. However.

18 Four Table Join List all videos along with name of director and names of actors and their associated roles. Actor a. title. actorName.actorNo = a.catalogNo AND r. Director d. 2004 61 .directorNo AND v. category. © Pearson Education Limited.directorNo = v. SELECT v.catalogNo = r. directorName. character FROM Video v.actorNo.3. Role r WHERE d.catalogNo.

2004 62 .3.18 Four Table Join © Pearson Education Limited.

Any columns omitted must have been declared as NULL or a DEFAULT was specified when table was created. 2004 63 .INSERT INSERT INTO TableName [ (columnList) ] VALUES (dataValueList)   columnList is optional. if omitted. © Pearson Education Limited. SQL assumes a list of all columns in their original CREATE TABLE order.

© Pearson Education Limited.INSERT  dataValueList must match columnList as follows:  number of items in each list must be same.  data type of each item in dataValueList must be compatible with data type of corresponding column.  must be direct correspondence in position of items in two lists. 2004 64 .

„Die Another „Action‟ 5. 21.19 INSERT Insert a row into the Video table.3.99. „D1001‟ ).00. Day‟. 2004 65 . INSERT INTO Video VALUES („207132‟. © Pearson Education Limited.

] [WHERE searchCondition]   TableName can be name of a base table or an updatable view. © Pearson Education Limited. 2004 66 . SET clause specifies names of one or more columns that are to be updated. columnName2 = dataValue2.UPDATE UPDATE TableName SET columnName1 = dataValue1 [...

2004 67 . © Pearson Education Limited.  if specified. named columns are updated for all rows in table.UPDATE   WHERE clause is optional:  if omitted. only those rows that satisfy searchCondition are updated. New dataValue(s) must be compatible with data type for corresponding column.

20 UPDATE Rows in a Table Modify the daily rental rate of videos in the „Thriller‟ category by 10% .3. 2004 68 . UPDATE Video SET dailyRental = dailyRental*1. © Pearson Education Limited.1 WHERE category = „Thriller‟.

© Pearson Education Limited. if omitted. This does not delete table. If searchCondition specified. 2004 69 . only those rows that satisfy condition are deleted. all rows are deleted from table.DELETE DELETE FROM TableName [WHERE searchCondition]   TableName can be name of a base table or an updatable view. searchCondition is optional.

3. © Pearson Education Limited. 2004 70 .21 DELETE Specific Rows Delete rental videos number 634817 . for catalog DELETE FROM VideoForRent WHERE catalogNo = „634817‟.

2004 71 .Data Definition  Two main SQL DDL statements:   CREATE TABLE – to create a new table. © Pearson Education Limited. CREATE VIEW – to create a new view.

[ON UPDATE referentialAction] [ON DELETE referentialAction ]] [..]} [PRIMARY KEY (listOfColumns)..]} {[FOREIGN KEY (listOfFKColumns) REFERENCES ParentTableName [(listOfCKColumns)]..] {[UNIQUE (listOfColumns).…]} © Pearson Education Limited.CREATE TABLE Statement CREATE TABLE TableName {(columnName dataType [NOT NULL] [UNIQUE] [DEFAULT defaultOption][.] […. 2004 72 .

Defining a column
columnName dataType [NOT NULL] [UNIQUE] [DEFAULT defaultOption]

Supported data types of SQL are:

© Pearson Education Limited, 2004

73

PRIMARY KEY and entity integrity

Entity integrity supported by PRIMARY KEY clause. For example:
CONSTRAINT pk PRIMARY KEY (catalogNo) CONSTRAINT pk1 PRIMARY KEY (catalogNo, actorNo)

© Pearson Education Limited, 2004

74

FOREIGN KEY and ref. integrity

Use FOREIGN KEY clause to define any foreign keys in the table. SQL rejects any INSERT or UPDATE that attempts to create a FK value in child table without matching CK value in parent table. The action SQL takes for any UPDATE or DELETE that attempts to update or delete a CK value in the parent table with some matching rows in child table is dependent upon specified referential action.
© Pearson Education Limited, 2004 75

SET DEFAULT . SET NULL .Update/delete row from parent and set FK values in child table to NULL. © Pearson Education Limited. and so on in cascading manner.FOREIGN KEY and ref. Possible values are:     CASCADE – Update/delete row from parent and automatically update/ matching rows in child table. 2004 76 . integrity  Referential actions with ON UPDATE and ON DELETE subclauses.Update/delete row from parent and set FK values in child table to specified default value. NO ACTION – Reject the update/delete.

]] AS Subselect CREATE VIEW StaffBranch1 AS SELECT staffNo.CREATE VIEW Statement CREATE VIEW ViewName [(newColumnName [. 2004 77 . position FROM Staff WHERE branchNo = „B001‟. name... © Pearson Education Limited..

Query database by illustrating query to be answered using a template. One of easiest ways for non-technical users to query database. 2004 78 .Query-By-Example (QBE)    QBE alternative graphical-based “point-andclick” way of querying database. © Pearson Education Limited.