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

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

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

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

2004 .Writing SQL Commands  SQL statement consists of reserved words and user-defined words. columns. 7 © Pearson Education Limited. – 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. views.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

7 Set Membership  There is a negated version (NOT IN). Could have expressed this as: SELECT catalogNo. title. 2004 .3. 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. 26 © Pearson Education Limited.

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

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

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

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

31 © Pearson Education Limited.3. SELECT * FROM Video ORDER BY price DESC. 2004 .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.SELECT Statement . 2004 . returns smallest value in specified column. 33 © Pearson Education Limited.Aggregates  ISO SQL defines five aggregate functions: COUNT returns number of values in specified column. AVG MIN returns average of values in specified column. MAX returns largest value in specified column.

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

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

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

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.000 and the sum of their salaries.3. 37 © Pearson Education Limited. SELECT COUNT(staffNo) AS totalStaff. 2004 .

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

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

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

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

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

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

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

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

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

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

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

49 © Pearson Education Limited. 2004 .  Outer SELECT then becomes: SELECT staffNo.3. name. position FROM Staff WHERE branchNo = „B001‟.  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‟).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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)//-->