P. 1
Query by Example

Query by Example

|Views: 6|Likes:
Published by Vinchi L. Lim

More info:

Published by: Vinchi L. Lim on Apr 07, 2013
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PPT, PDF, TXT or read online from Scribd
See more
See less






  • 3.3 Use of DISTINCT
  • 3.4 Calculated Fields
  • 3.5 Comparison Search Condition
  • 3.7 Set Membership
  • 3.8 Pattern Matching
  • 3.9 NULL Search Condition
  • 3.12 Use of MIN, MAX and AVG
  • 3.16 Subquery with Aggregate
  • 3.17 Simple Join
  • 3.18 Four Table Join
  • 3.19 INSERT
  • 3.20 UPDATE Rows in a Table
  • 3.21 DELETE Specific Rows

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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. 26 © Pearson Education Limited.3.  IN does not add much to SQL‟s expressive power.7 Set Membership  There is a negated version (NOT IN). 2004 . title.

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

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

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

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

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

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

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

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

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

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

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

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

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

SELECT Statement . 40 © Pearson Education Limited.Grouping  Use GROUP BY clause to get sub-totals. 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 .

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

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

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

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

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

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

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

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

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

3.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. 51 © Pearson Education Limited. 2004 . SELECT staffNo. position FROM Staff WHERE salary > (SELECT AVG(salary) FROM Staff). name.

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

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

Can refer to a table in FROM using an alias.  By default. except for subqueries that use EXISTS.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. 2004 .  Subquery SELECT list must consist of a single column name or expression. 54 © Pearson Education Limited.

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

2004 . 56 © Pearson Education Limited.Multi-Table Queries  Can use subqueries provided result columns come from same table.  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.  To perform join.

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

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

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

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. 60 © Pearson Education Limited. 2004 . However. first produces table with two identical directorNo columns.

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

18 Four Table Join © Pearson Education Limited. 2004 62 .3.

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

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

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

. columnName2 = dataValue2.] [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.UPDATE UPDATE TableName SET columnName1 = dataValue1 [. © Pearson Education Limited. 2004 66 .

 if specified. 2004 .UPDATE  WHERE clause is optional:  if omitted. named columns are updated for all rows in table.  New dataValue(s) must be compatible with data type for corresponding column. only those rows that satisfy searchCondition are updated. 67 © 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% . 68 © Pearson Education Limited.3. 2004 . UPDATE Video SET dailyRental = dailyRental*1.

This does not delete table.  searchCondition is optional. 2004 . If searchCondition specified. if omitted. 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. all rows are deleted from table.

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

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

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

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

FOREIGN KEY and ref.Update/delete row from parent and set FK values in child table to specified default value.  SET DEFAULT . 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 . 76 © Pearson Education Limited.  SET NULL . and so on in cascading manner.  NO ACTION – Reject the update/delete.

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

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

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->