Chapter 3

SQL and QBE Transparencies

1

© Pearson Education Limited, 2004

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.
2 © Pearson Education Limited, 2004

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 range of users.

3

© Pearson Education Limited, 2004

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

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

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

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

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

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

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

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

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

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

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

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

2004 .3.2 Specific Columns. All Rows 16 © Pearson Education Limited.

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

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

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

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

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

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

2004 .3.6 Range Search Condition 23 © Pearson Education Limited.

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

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

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

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

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

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

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

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

10 Single Column Ordering 32 © Pearson Education Limited.3. 2004 .

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

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

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

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

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

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

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

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

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

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

2004 .3.13 Use of GROUP BY 43 © Pearson Education Limited.

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

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

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

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

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

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

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

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

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

2004 .16 Subquery with Aggregate 53 © Pearson Education Limited.3.

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

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

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

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

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

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

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

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

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

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

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

99. 2004 . „Action‟ 5.00. „Die Another Day‟.19 INSERT Insert a row into the Video table. „D1001‟ ). 65 © Pearson Education Limited. 21. INSERT INTO Video VALUES („207132‟.3.

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

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

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

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

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

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

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

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)

74

© Pearson Education Limited, 2004

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.
75 © Pearson Education Limited, 2004

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

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

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

Sign up to vote on this title
UsefulNot useful