SQL | Sql | Databases

Structured Query Language (SQL


Topics of the Talk
and importance of SQL.  How to retrieve data from database using SELECT and: 
Purpose ± ± ± ± ±

Use compound WHERE conditions. Sort query results using ORDER BY. Use aggregate functions. Group data using GROUP BY and HAVING. Use subqueries.

Topics of the Talk
± ±

Join tables together. Perform set operations (UNION, INTERSECT, EXCEPT). INSERT,

to update database using UPDATE, and DELETE.  Data types supported by SQL-92.  How to create and delete tables. 


deletion of data from relations. modification.  It must be portable.Objectives of SQL database language should allow user to: ± create the database and relation structures.  Ideally.  Must perform these tasks with minimal user effort and command structure and syntax must be easy to learn. ± perform insertion. 4 . ± perform simple and complex queries.

a  SQL does not contain flow control commands.Characteristics of SQL  SQL ± ± is a language with 2 major components: A DDL for defining the database structure. ± These must be implemented using programming language. 5 . A DML for retrieving and updating data.

It is essentially free-format. 6 .you specify what information you require. rather than how to get it.Characteristics of SQL  SQL is relatively easy to learn: ± ± It is a non-procedural language .

lname.2)). salary FROM staff WHERE salary > 10000. 'Brown'. SELECT sno.Characteristics of SQL  Consists of standard English words: CREATE TABLE staff(sno VARCHAR(5). lname VARCHAR(15). salary DECIMAL(7. 7 . INSERT INTO staff VALUES ('SG16'. 8300).

8 . making it both the formal and de facto standard language for relational databases. application programmers.Characteristics of SQL  Can be used by a range of users including DBAs.  An ISO standard now exists for SQL. management. and other types of end users.

D.  In 9 .History of SQL 1974. Chamberlin (IBM San Jose Laboratory) defined language called 'Structured English Query Language' or SEQUEL.  A revised version SEQUEL/2 was defined in 1976 but name was subsequently changed to SQL for legal reasons.

based on SEQUEL/2. 10 .  IBM subsequently produced a prototype DBMS called System R.History of SQL  Still pronounced 'see-quel'. though official pronunciation is 's-q-l'.

History of SQL late 70s.  In 11 .  In 1987.  In 1992. ANSI and ISO published an initial standard for SQL.  In 1989. first major revision to ISO standard occurred. ORACLE appeared and was probably first commercial RDBMS based on SQL. referred to as SQL2 or SQL/92. ISO published an addendum that defined an 'Integrity Enhancement Feature'.

 It is strategic choice of many large and influential organizations (e.Importance of SQL  SQL has become part of application architectures such as IBM's Systems Application Architecture (SAA).g.  SQL is Federal Information Processing Standard (FIPS) to which conformance is required for all sales of databases to American Government. X/OPEN). 12 .

13 . such as ± ± ISO's Information Resource Directory System (IRDS) Standard Remote Data Access (RDA) Standard.  SQL is used in other standards and even influences development of other standards.Importance of SQL  SQL Access Group trying to define enhancements that will support interoperability across disparate systems.

columns. User-defined words are made up by user and represent names of various database objects such as relations. ± ± Reserved words are a fixed part of SQL and must be spelt exactly as required and cannot be split across lines. 14 . views.Writing SQL Commands  SQL statements consist of reserved words and user-defined words.

should each appear on a separate line and be indented under start of clause.  More readable with indentation and lineation: ± Each clause should begin on a new line. except for literal character data (name = ³banchong´/´Banchong´/´BANCHONG´).  Most 15 . ± Start of a clause should line up with start of other clauses.Writing SQL Commands components of an SQL statement are case insensitive. ± If clause has several parts.

Curly braces ({}) indicate a required element. | indicates a choice among alternatives. 16 .Writing SQL Commands  Use ± ± extended form of BNF notation: ± ± ± ± Upper case letters represent reserved words. « indicates optional repetition (0 or more). Square brackets ([]) indicate an optional element. Lower case letters represent user-defined words.

SELECT Statement SELECT [DISTINCT | ALL] {* | [column_expression [AS new_name]] [.. ...] } FROM table_name [alias] [..] [WHERE condition] [GROUP BY column_list] [HAVING condition] [ORDER BY column_list] 17 ..

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

19 .SELECT Statement  Order  Only of the clauses cannot be changed. SELECT and FROM are mandatory.

sex. lname. SELECT sno. bno FROM staff. tel_no. address. All Rows List full details of all staff.1 All Columns. nin. dob.Example 13. fname.  Can use * as an abbreviation for 'all columns': SELECT * FROM staff. position. 20 . salary.

Example 13.1 All Columns. All Rows 21 .

showing only the staff number. the first and last names. and the salary details.2 Specific Columns. All Rows Produce a list of salaries for all staff. 22 . lname. Sno. SELECT sno. fname.Example 13. salary FROM staff.

2 Specific Columns. All Rows 23 .Example 13.

SELECT pno FROM viewing.3 Use of DISTINCT List the property numbers of all properties that have been viewed.Example 13. 24 .

25 .Example 13.3 Use of DISTINCT  Use DISTINCT to eliminate duplicates: SELECT DISTINCT pno FROM viewing.

showing the staff number.Example 13. 26 . salary/12 FROM staff. SELECT sno. the first and last names. lname. fname. and the salary details.4 Calculated Fields Produce a list of monthly salaries for all staff.

27 . fname.Example 13. use AS clause: SELECT sno. salary/12 AS monthly_salary FROM staff.4 Calculated Fields  To name column. lname.

lname.5 Comparison Search Condition List all staff with a salary greater than 10.000. position.Example 13. fname. 28 . salary FROM staff WHERE salary > 10000. SELECT sno.

Example 13.5 Comparison Search Condition 29 .

SELECT bno.6 Compound Comparison Search Condition List the addresses of all branch offices in London or Glasgow. pcode FROM branch WHERE city = 'London' OR city = 'Glasgow'. area.Example 13. 30 . city. street.

6 Compound Comparison Search Condition 31 .Example 13.

000 and 30. lname. SELECT sno. fname. salary FROM staff WHERE salary BETWEEN 20000 AND 30000. 32 . position.000.7 Range Search Condition List all staff with a salary between 20.  BETWEEN test includes the endpoints of range.Example 13.

7 Range Search Condition 33 .Example 13.

 BETWEEN does not add much to SQL's expressive power Could also write:  Also SELECT sno.Example 13. 34 . salary FROM staff WHERE salary>=20000 AND salary <= 30000. lname. position. fname.7 Range Search Condition a negated version NOT BETWEEN. though.  Useful. for a range of values.

Example 13. fname. 'Deputy'). position FROM staff WHERE position IN ('Manager'. lname.8 Set Membership List all Managers and Deputy Managers. 35 . SELECT sno.

8 Set Membership 36 .Example 13.

lname. 37 .  Could have expressed this as:  SELECT sno. position FROM staff WHERE position='Manager' OR position='Deputy'.Example 13. fname.  IN does not add much to SQL's expressive power.8 Set Membership There is a negated version (NOT IN).

9 Pattern Matching Find all staff with the string 'Glasgow' in their address. address. SELECT sno.Example 13. lname. salary FROM staff WHERE address LIKE '%Glasgow%'. fname. 38 .

9 Pattern Matching 39 .Example 13.

40 . _ (underscore): any single character.Example 13.9 Pattern Matching  SQL ± ± has two special pattern matching symbols: %: sequence of zero or more characters. of  LIKE '%Glasgow%' means a sequence characters of any length containing 'Glasgow'.

Example 13.10 NULL Search Condition
List details of all viewings on property PG4 where a comment has not been supplied. are 2 viewings for property PG4, one with and one without a comment.  Have to test for null explicitly using special keyword IS NULL: 

SELECT rno, date FROM viewing WHERE pno = 'PG4' AND comment IS NULL;

Example 13.10 NULL Search Condition 


version (IS NOT NULL) can test for nonnull values.

Example 13.11 Single Column Ordering
List salaries for all staff, arranged in descending order of salary. SELECT sno, fname, lname, salary FROM staff ORDER BY salary DESC;


Example 13.11 Single Column Ordering 44 .

Example 13. rooms. type. 45 . SELECT pno. rent FROM property_for_rent ORDER BY type.12 Multiple Column Ordering Produce abbreviated list of properties in order of property type.

12 Multiple Column Ordering 46 .Example 13.

specify minor order: SELECT pno. rent FROM property_for_rent ORDER BY type.  To arrange in order of rent. rent DESC.Example 13. 47 . rooms.as no minor sort key specified. system arranges these rows in any order it chooses.12 Multiple Column Ordering  Four flats in this list . type.

12 Multiple Column Ordering 48 .Example 13.

SUM returns sum of values in a specified column.Aggregates  ISO standard defines five aggregate functions: COUNT returns number of values in a specified column. MIN returns smallest value in a specified column. 49 . AVG returns average of values in a specified column.SELECT Statement . MAX returns largest value in a specified column.

50 . and MAX apply to numeric and non-numeric fields.SELECT Statement .  Apart from COUNT(*).  COUNT. each function eliminates nulls first and operates only on remaining non-null values. but SUM and AVG may be used on numeric fields only. MIN.Aggregates  Each operates on a single column of a table and return single value.

Aggregates  COUNT(*) counts all rows of a table.  DISTINCT has no effect with MIN/MAX.  Aggregate functions can be used only in SELECT clause and in HAVING clause.  Can use DISTINCT before column name to eliminate duplicates. regardless of whether nulls or duplicate values occur.SELECT Statement . but may have with SUM/AVG. 51 .

13 Use of COUNT(*) How many properties cost more than 350 per month to rent? SELECT COUNT(*) AS count FROM property_for_rent WHERE rent > 350. 53 .Example 13.

54 .Example 13.14 Use of COUNT(DISTINCT) How many different properties viewed in May µ98? SELECT COUNT(DISTINCT pno) AS count FROM viewing WHERE date BETWEEN DATE'1998-05-01¶ AND DATE'1998-05-31'.

55 . SUM(salary) AS sum FROM staff WHERE position = 'Manager'. SELECT COUNT(sno) AS count.Example 13.15 Use of COUNT and SUM Find number of Managers and sum of their salaries.

AVG(salary) AS avg FROM staff. AVG Find minimum. maximum.16 Use of MIN. and average staff salary. MAX. SELECT MIN(salary) AS min. MAX(salary) AS max.Example 13. 56 .

Grouping GROUP BY clause to get sub-totals.17 also).  A SELECT clause may only contain: ± Column names.SELECT Statement . ± Aggregate functions.  Each item in a result table must be single-valued per group (see table 13.  Use 57 . ± An expression involving combinations of the above. ± Constants.

Grouping  All column names in SELECT clause must appear in GROUP BY clause unless name is used only in an aggregate function (See exam 13.  If WHERE is used with GROUP BY. considers two nulls to be equal for purposes of GROUP BY. 58  ISO .SELECT Statement . WHERE is applied first. then groups are formed from remaining rows satisfying condition.17 also).

Example 13. bno.17 Use of GROUP BY Find number of staff in each branch and their total salaries. SUM(salary) AS sum FROM staff GROUP BY bno ORDER BY bno. COUNT(sno) AS count. 59 SELECT .

Example 13.17 Use of GROUP BY 60 .

 Column names in HAVING clause must also appear in the GROUP BY clause or be contained within an aggregate function. 61 .  Similar to WHERE. but WHERE filters individual rows whereas HAVING filters groups.Restricted Grouping  HAVING clause is designed for use with GROUP BY clause to restrict groups that appear in final result table.

SELECT bno.Example 13.18 Use of HAVING For each branch with more than 1 member of staff. 62 . find number of staff in each branch and sum of their salaries. SUM(salary) AS sum FROM staff GROUP BY bno HAVING COUNT(sno) > 1 ORDER BY bno. COUNT(sno) AS count.

18 Use of HAVING 63 .Example 13.

where it is called a subquery or nested query.Subqueries  Some SQL statements can have a SELECT embedded within them. and DELETEs. 64 .  Subselects may also appear in INSERT. UPDATE. A subselect can be used in WHERE and HAVING clauses of an outer SELECT.

position FROM staff WHERE bno = (SELECT bno FROM branch WHERE street = '163 Main St').19 Subquery with Equality List staff who work in branch at '163 Main St'.Example 13. SELECT sno. fname. 65 . lname.

 Outer SELECT then becomes:  Inner SELECT sno.19 Subquery with Equality SELECT finds branch number corresponding to branch at '163 Main St' ('B3'). position FROM staff WHERE bno = 'B3'.Example 13. 66 . lname.  Outer SELECT then retrieves details of all staff who work at this branch. fname.

19 Subquery with Equality 67 .Example 13.

lname.20 Subquery with Aggregate List all staff whose salary is greater than the average salary. fname. position. salary FROM staff WHERE salary > (SELECT AVG(salary) FROM staff).Example 13. SELECT sno. 68 .

Example 13.20 Subquery with Aggregate 70 .

20 also).Subquery Rules  ORDER BY clause may not be used in a subquery (although it may be used in outermost SELECT).  When subquery is an operand in a comparison. 71 . subquery must appear on right-hand side (See exam 13.

area. city. rent FROM property_for_rent WHERE sno IN (SELECT sno FROM staff WHERE bno = (SELECT bno FROM branch WHERE street = '163 Main St')). type. pcode. SELECT pno. 73 . street. rooms.Example 13.21 Nested subquery: use of IN List properties handled by staff at '163 Main St'.

21 Nested subquery: use of IN 74 .Example 13.

ANY and ALL  ANY and ALL may be used with subqueries that produce a single column of numbers. (numerical) a subquery is preceded by ALL. condition will be true if it is satisfied by any values produced by the subquery.  If  If a subquery is preceded by ANY. condition will only be true if it is satisfied by all values produced by the subquery. 75 .

ANY returns false. standard allows SOME to be used in place of ANY.  ISO 76 .ANY and ALL  If subquery is empty. ALL returns true.

lname. salary FROM staff WHERE salary > SOME (SELECT salary FROM staff WHERE bno = 'B3').22 Use of ANY/SOME Find staff whose salary is larger than salary of at least 1 member of staff at branch B3.Example 13. fname. 77 . SELECT sno. position.

Example 13. 78 . 24000} and outer query selects those staff whose salaries are greater than any of the values in this set.22 Use of ANY/SOME  Inner query produces set {12000. 18000.

position. SELECT sno. lname. fname. 79 . salary FROM staff WHERE salary > ALL (SELECT salary FROM staff WHERE bno = 'B3').23 Use of ALL Find staff whose salary is larger than salary of every member of staff at branch B3.Example 13.

Example 13.23 Use of ALL 80 .

81  Use .Multi-Table Queries (sub)queries shown earlier.  If result columns come from more than one table must use a join.  In  To perform join. comma as separator and typically include WHERE clause to specify join column(s). note that all result columns come from same table. include more than one table in FROM clause.

 Alias is separated from table name with a space (See exam 13.  Alias 82 .24 also). 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.

fname. comment FROM renter r. pno. 83 . lname.rno. SELECT r.rno = v.24 Simple Join List names of all renters who have viewed a property along with any comment supplied.rno. viewing v WHERE r.Example 13.

to equi-join in relational algebra. (See Renter and Viewing Tables)  These two columns are the matching columns for two tables. include only those rows from both tables that have identical values in the Rno columns: r.rno = v.24 Simple Join  To obtain correct rows. 84  Equivalent .Example 13.rno.

Example 13.24 Simple Join 85 .

86 .rno=v. remaining two produce table with single Rno column.rno (equi) FROM renter JOIN viewing USING rno (natural) FROM renter NATURAL JOIN viewing (natural)  In each case. However. first produces table with two identical Rno columns.Alternative JOIN Constructs  SQL2 provides alternative ways to specify joins: FROM renter r JOIN viewing v ON r. FROM replaces original FROM and WHERE.

property_for_rent p WHERE s.sno = p.bno. 87 .sno.bno. s. pno FROM staff s. SELECT s. lname.sno ORDER BY s.25 Sorting a join For each branch.sno. fname.Example 13. pno. s. list names of staff who manage properties.

25 Sorting a join 88 .Example 13.

89 .sno.bno.bno AND s. fname. property_for_rent p WHERE b. b. lname.sno.sno ORDER BY b.26 Three Table Join For each branch. SELECT b. staff s. pno FROM branch b. including city in which branch is located and properties they manage. list staff who manage properties.Example 13.bno.sno = p. s. s.city. pno.bno = s.

26 Three Table Join 90 .Example 13.

26 Three Table Join  SQL2 provides alternative formulations for FROM and WHERE: FROM (branch b JOIN staff s USING bno) AS bs JOIN property_for_rent p USING sno 91 .Example 13.

property_for_rent p WHERE s.bno.Example 13. s. s. SELECT s. 92 .sno GROUP BY s. COUNT(*) AS count FROM staff s.sno ORDER BY s.bno.sno.27 Multiple Grouping Columns Find number of properties handled by each staff member in each branch. s.bno.sno.sno = p.

27 Multiple Grouping Columns 93 .Example 13.

if one row of a table is unmatched.  The outer join operations retain rows that do not satisfy the join condition. that row is omitted from result table.  Consider following two simplified tables: BRANCH1 bno city B3 Glasgow B4 Bristol B2 London PROPERTY_FOR_RENT1 pno pcity PA14 Aberdeen PL94 London PG4 Glasgow 97 .Outer Joins  With a join.

* FROM branch1 b.Outer Joins  The (inner) join of these two tables: SELECT b. 98 . p.*.bcity = p. property_for_rent1 p WHERE b.pcity.

 To include unmatched rows in result table. use an outer join.Outer Joins  Result table has two rows where the cities are the same. 99 .  There are no rows corresponding to branches in Bristol and Aberdeen.

* FROM branch1 b LEFT JOIN property_for_rent1 p ON b.28 Left Outer Join List branches and properties that are in same city along with any unmatched branches.bcity = p.pcity.Example 13.*. 100 . p. SELECT b.

Example 13.  Columns from second table are filled with NULLs.28 Left Outer Join those rows of first (left) table unmatched with rows from second (right) table.  Includes 101 .

*.pcity. p.bcity = p.29 Right Outer Join List branches and properties in same city and any unmatched properties.Example 13.* FROM branch1 b RIGHT JOIN property_for_rent1 p ON b. 102 . SELECT b.

29 Right Outer Join  Right outer join includes those rows of second (right) table that are unmatched with rows from first (left) table. 103 .Example 13.  Columns from first table are filled with NULLs.

p.*. 104 .Example 13. SELECT b.pcity.30 Full Outer Join List branches and properties in same city and any unmatched branches or properties.bcity = p.* FROM branch1 b FULL JOIN property_for_rent1 p ON b.

105 .Example 13.  Unmatched columns are filled with NULLs.30 Full Outer Join  Includes those rows that are unmatched in both tables.

106 .  They produce a simple true/false result.  NOT EXISTS is the opposite of EXISTS.EXISTS and NOT EXISTS  EXISTS and NOT EXISTS are for use only with subqueries.  EXISTS is true if and only if there exists at least one row in result table returned by subquery.  It is false if subquery returns an empty result table.

EXISTS and NOT EXISTS  Since EXISTS and NOT EXISTS check only for existence or non-existence of rows in subquery result table.) 107 .. subquery can contain any number of columns.  Subqueries following (NOT) EXISTS are of the form: (NOT) EXISTS (SELECT * ..

lname.bno = b.bno AND city = 'London'). 108 .Example 13. position FROM staff s WHERE EXISTS (SELECT * FROM branch b WHERE s. fname.31 Query using EXISTS  Find all staff who work in a London branch. SELECT sno.

Example 13.31 Query using EXISTS 109 .

branch b WHERE s. position FROM staff s.31 Query using EXISTS  Could also have written this query using join construct: SELECT sno. 111 .bno AND city = 'London'. fname.Example 13. lname.bno = b.

 Two tables must be union compatible. and Difference (Except)  Can use normal set operations of union. Intersect.  Union of two tables.Union. and difference to combine results of two or more queries into a single result table. 112 . is table containing all rows in either A or B or both. intersection.  Intersection is table containing all rows common to both A and B.  Difference is table containing all rows in A but not in B. A and B.

and Difference (Except)  Format of set operator clause in each case is: op [ALL] [CORRESPONDING [BY { column1 [.] } ] ] CORRESPONDING BY specified.. Intersect.  If CORRESPONDING specified but not BY clause. operation performed on common columns.  If ALL specified. set operation performed on the named column(s). .  If 113 .Union.. result can include duplicate rows.

and Difference (Except) 114 . Intersect.Union.

Example 13. 115 .32 Use of UNION List all areas where there is either a branch or rental property. (SELECT area FROM branch WHERE area IS NOT NULL) UNION (SELECT area FROM property_for_rent WHERE area IS NOT NULL).

116 .Example 13.32 Use of UNION ± Or (SELECT * FROM branch WHERE area IS NOT NULL) UNION CORRESPONDING BY area (SELECT * FROM property_for_rent WHERE area IS NOT NULL).

Example 13.32 Use of UNION 

result tables from both queries and merges both tables together.


Example 13.33 Use of INTERSECT
List all cities where there is both a branch and rental property. (SELECT city FROM branch) INTERSECT (SELECT city FROM property_for_rent);


Example 13.33 Use of INTERSECT 

(SELECT * FROM branch) INTERSECT CORRESPONDING BY city (SELECT * FROM property_for_rent);


33 Use of INTERSECT  Produces result tables from both queries and creates single result table consisting of those rows that are common to both result tables.Example 13. 120 .

33 Use of INTERSECT  Could rewrite this query without INTERSECT operator: SELECT city FROM branch b property_for_rent p WHERE b. 121 .city.Example 13.city = p.

33 Use of INTERSECT  Or SELECT distinct city FROM branch b WHERE EXISTS (SELECT * FROM property_for_rent p WHERE p.  Ability to write a query in several equivalent forms is one of the (dis)advantages of SQL. 122 .Example 13.city).city = b.

(SELECT city FROM branch) EXCEPT (SELECT city FROM property_for_rent).34 Use of EXCEPT List of all cities where there is a branch but no rental properties. 123 .Example 13.

Example 13.34 Use of EXCEPT  Or (SELECT * FROM branch) EXCEPT CORRESPONDING BY city (SELECT * FROM property_for_rent). 124 .

Example 13. 125 .34 Use of EXCEPT  Produces result tables from both queries and then creates single result table consisting of those rows appearing in first result table but not in second.

126 .34 Use of EXCEPT  Could rewrite this query without EXCEPT: SELECT distinct city FROM branch WHERE city NOT IN (SELECT city FROM property_for_rent).Example 13.

127 .city).city = b.Example 13.34 Use of EXCEPT  Or SELECT distinct city FROM branch b WHERE NOT EXISTS (SELECT * FROM property_for_rent p WHERE p.

INSERT INSERT INTO table_name [ (column_list) ] VALUES (data_value_list)  column_list is optional. SQL assumes a list of all columns in their original CREATE TABLE order.  If omitted. 128 .

 data_value_list 129 .  Must be direct correspondence in position of items in two lists.INSERT must match column_list as follows:  Number of items in each list must be the same.  Data type of each item in data_value_list must be compatible with data type of corresponding column.

'25-May57'. 'Assistant'.Example 13. 8300. 'Alan'. 'M'. INSERT INTO staff VALUES ('SG16'. '0141-211-3001'. 130 .35 INSERT « VALUES Insert a new record into Staff table supplying data for all columns. '67 Endrick Rd. 'Brown'. 'B3'). 'WN848391H'. Glasgow G32 8QX'.

bno) VALUES ('SG44'. 'Anne'. 131 . fname. position. INSERT INTO staff (sno. 8100. 'Assistant'. salary.Example 13.36 INSERT using Defaults Insert a new record into Staff table supplying data for all mandatory columns. lname. 'Jones'. 'B3').

36 INSERT using Defaults  Or INSERT INTO staff VALUES ('SG44'. 'B3'). 132 . 'Jones'. NULL. 8100. NULL. NULL.Example 13. 'Assistant'. NULL. NULL. 'Anne'.

.INSERT « SELECT  Second form of INSERT allows multiple rows to be copied from one or more tables to another: INSERT INTO table_name [ (column_list) ] SELECT . 133 ..

Example 13.37 INSERT « SELECT
Assume there is a table Staff_Prop_Count that contains names of staff and the number of properties they manage: Staff_Prop_Count(sno, fname, lname, prop_cnt) Populate Staff_Prop_Count Property_for_Rent. using Staff and


Example 13.37 INSERT « SELECT
INSERT INTO staff_prop_count (SELECT s.sno, fname, lname, COUNT(*) FROM staff s, property_for_rent p WHERE s.sno = p.sno (staff with some properties) GROUP BY s.sno, fname, lname) UNION (SELECT sno, fname, lname, 0 FROM staff WHERE sno NOT IN (staff with no property) (SELECT DISTINCT sno FROM property_for_rent));


Example 13.37 INSERT « SELECT 


second part of UNION is omitted, excludes those staff who currently do not manage any properties.


 SET clause specifies names of one or more columns that are to be updated.UPDATE UPDATE table_name SET column_name1 = data_value1 [..] [WHERE search_condition] can be name of a base table or an updatable view.  table_name 137 . column_name2 = data_value2..

UPDATE  WHERE clause is optional: ± If omitted. named columns are updated for all rows in table. 138 . only those rows that satisfy search_condition are updated.  New data_value(s) must be compatible with data type for corresponding column. ± If specified.

139 .03. UPDATE staff SET salary = salary*1.Example 13.38 UPDATE All Rows Give all staff a 3% pay increase.

Example 13.39 UPDATE Specific Rows Give all Managers a 5% pay increase. UPDATE staff SET salary = salary*1. 140 .  WHERE clause finds rows that contain data for Managers. Update is applied only to these particular rows.05 WHERE position = 'Manager'.

Example 13. UPDATE staff SET position = 'Manager'.000. 141 . salary = 18000 WHERE sno = 'SG14'.40 UPDATE Multiple Columns Promote David Ford (sno = 'SG14') to Manager and change his salary to 18.

DELETE DELETE FROM table_name [WHERE search_condition] can be name of a base table or an updatable view. only those rows that satisfy condition are deleted. This does not delete table. all rows are deleted from table. If search_condition is specified.  search_condition is optional. if omitted.  table_name 142 .

41 DELETE Specific Rows Delete all viewings that relate to property PG4. 143 . DELETE FROM viewing WHERE pno = 'PG4'.Example 13.

144 .Example 13.42 DELETE All Rows Delete all records from the Viewing table. DELETE FROM viewing.

ISO SQL Data Types 145 .

and each catalog consists of set of schemas.  In 146 . and assertions). relations and other database objects exist in an environment. views. domains.  Schema is a named collection of related database objects (tables.Data Definition SQL92.  Each environment contains one or more catalogs.

DROP SCHEMA fails.  With CASCADE.Data Definition CREATE SCHEMA [name | AUTHORIZATION creator_id ] DROP SCHEMA name [RESTRICT | CASCADE ]  With RESTRICT (default). schema must be empty or operation fails. 147 . operation cascades to drop all objects associated with schema. If any of these operations fail.

system rejects any attempt to insert a null in the column.  With NOT NULL.CREATE TABLE (Basic) CREATE TABLE table_name (col_name data_type [NULL | NOT NULL] [.. 148 .  NULL (default) indicates whether column can contain nulls..])  Creates a table with one or more columns of the specified data_type..

149 .CREATE TABLE (Basic)  Primary keys should always be specified as NOT (but not always) NULL.  Foreign keys are often candidates for NOT NULL.

bno VARCHAR(3) NOT NULL.Example 13. NOT NULL. dob DATETIME. 150 . position VARCHAR(10) sex CHAR.43 CREATE TABLE CREATE TABLE staff( sno VARCHAR(5) fname VARCHAR(15) lname VARCHAR(15) address VARCHAR(50). salary DECIMAL(7. NOT NULL. NOT NULL.2) nin CHAR(9). NOT NULL. tel_no VARCHAR(13). NOT NULL).

NOT NULL). NOT NULL. NOT NULL. NOT NULL. NOT NULL. NOT NULL. city VARCHAR(15) pcode VARCHAR(8). NOT NULL.43 CREATE TABLE CREATE TABLE property_for_rent( pno VARCHAR(5) street VARCHAR(25) area VARCHAR(15). 151 .2) ono VARCHAR(5) sno VARCHAR(5). type CHAR(1) rooms SMALLINT rent DECIMAL(6. bno VARCHAR(3) NOT NULL.Example 13.

named table and all rows within it.  With CASCADE.  With RESTRICT. SQL does not allow request.DROP TABLE DROP TABLE tbl_name [RESTRICT | CASCADE] e.g.  Removes DROP TABLE property_for_rent. if any other objects depend for their existence on continued existence of this table. SQL drops all dependent objects (and objects dependent on these objects). 152 .

Sign up to vote on this title
UsefulNot useful