P. 1
Query by Example

Query by Example

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

More info:

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

Availability:

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

10/28/2013

pdf

text

original

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

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

2004 . update. 5 © Pearson Education Limited.  Must perform these tasks with minimal user effort.  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. delete.

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

columns. 2004 . views. – 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. 7 © Pearson Education Limited.

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

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

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

2004 . GROUP BY Forms groups of rows with same column value. 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. HAVING Filters groups subject to some condition. WHERE Filters rows.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.  _ (underscore): any single character. 28 © Pearson Education Limited.

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

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

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

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

returns smallest value in specified column. 2004 .SELECT Statement . MAX returns largest value in specified column. SUM returns sum of values 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.

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

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

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

11 Use of COUNT and SUM List total number of staff with salary greater than $40.3.000 and the sum of their salaries. SELECT COUNT(staffNo) AS totalStaff. 2004 . 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 .

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

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

then groups are formed from remaining rows satisfying predicate. WHERE is applied first.SELECT Statement . 2004 .  ISO considers two nulls to be equal for purposes of GROUP BY.  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.

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

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

WHERE HAVING filters filters  Column names in HAVING clause must also 44 © Pearson Education Limited. but individual rows whereas groups.  Similar to WHERE. .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.

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

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

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

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

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

3.15 Subquery with Equality 50 © Pearson Education Limited. 2004 .

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

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

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

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

subquery must appear on righthand side. 2004 .  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.

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

 Alias is separated from table name with a space. 2004 . 57 © Pearson Education Limited.  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.

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

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

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

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

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

INSERT INSERT INTO TableName [ (columnList) ] VALUES (dataValueList)  columnList is optional. 63 © Pearson Education Limited. 2004 . 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. if omitted.

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

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

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

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

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

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

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

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

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

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

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

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

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

You're Reading a Free Preview

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