Query by Example | Sql | Table (Database)

Chapter 3

SQL and QBE Transparencies


© 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

 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.


© Pearson Education Limited, 2004

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

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

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

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

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

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

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

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

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

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

3.1 All Columns. 2004 . All Rows 14 © Pearson Education Limited.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2004 . AVG MIN returns average 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. SUM returns sum of values in specified column.SELECT Statement . 33 © Pearson Education Limited. returns smallest value in specified column.

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

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

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

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

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

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

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

SELECT Statement .  If used.  ISO considers two nulls to be equal for purposes of GROUP BY.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. WHERE is applied first. 41 © Pearson Education Limited. 2004 .

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

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

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

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

2004 .3.14 Use of HAVING 46 © Pearson Education Limited.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Defining a column
columnName dataType [NOT NULL] [UNIQUE] [DEFAULT defaultOption]
 Supported data types of SQL are:

© Pearson Education Limited, 2004


PRIMARY KEY and entity integrity
 Entity integrity supported by PRIMARY KEY

clause.  For example:



© 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

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

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

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. Query database by illustrating query to be answered using a template. 78 © Pearson Education Limited.

Sign up to vote on this title
UsefulNot useful