SQLNotes
SQLNotes
SQL Notes
Robert E. Young
Department of Industrial & Systems Engineering
North Carolina State University
Raleigh, NC 27695
The material in these notes is from many sources. However, the database used in the
examples and many of the examples are based upon the various editions of
August 1991
Revised January 1997, October 1999, November 2000,
March 2001, September 2002, April 2003, September 2004,
September 2007, September 2008, January 2013
Copyright © 1991, 1997, 1999, 2000, 2001, 2002, 2003, 2004, 2007, 2008, 2013
by Robert E. Young, all rights reserved.
SQL Notes
Table of Contents
ii
SQL Notes
iii
SQL Notes
SUPPLIER-PARTS DATABASE
iv
SQL NOTES
2 Data Definition
4 Miscellaneous Topics
1.1 Background
2
SQL Notes
1.1 BACKGROUND
3
SQL Notes
Within each table, no two primary key values can be identical ensuring
no two rows will be identical. This reduces redundancy.
* Number - s-no
* Name - sname
* Status - status
* Location - city
These are the fields of the database table and are the column
headings. Below is the database table with its components labeled.
Record
Each row
in a table
is a record
4
SQL Notes
Let's create some data, say Smith, 10, 30, S5, London. What
meaning does the data have? How do we interpret them? Are the
numbers 10 and 30 related? Are they the same units? Etc. We can
ask many questions but without context we have no answers.
5
SQL Notes
Suppliers Parts
S-no P-no
Sname Pname
Status Color
City Weight
SuppliersCol1 City
PartsCol1
Shipments
P-no (FK)
S-no (FK)
QTY
ShipmentsCol1
6
SQL Notes
Within database tables Suppliers and Parts the S-no and P-no are
unique identifiers, the "primary keys" defined previously. As a unique
identifier, no two will be the same in these tables. The Shipments
table connects suppliers and parts. Thus, it "maps" suppliers to parts
and parts to suppliers and shows the quantity of a part supplied by a
supplier. The Shipments too has a unique identifier or "primary key".
In the Shipments table the primary key is two columns, the S-no
column and the P-no column. Taken together S-no and P-no uniquely
identify a row in the table.
1.3 SQL
7
SQL Notes
* The original paper was titled "A Relational Model of Data for
Large Shared Data Banks." The name stuck and now table-
based database management systems are called relational
DBMSs.
8
SQL Notes
WHAT IS "SQL"?
9
SQL Notes
SQL AS A STANDARD
10
SQL Notes
* suppliers table
* parts table
* shipments table
11
SQL Notes
SUPPLIERS TABLE
12
SQL Notes
SUPPLIERS TABLE
13
SQL Notes
PARTS TABLE
We assume that each type of part comes in exactly one color and is
stored in a warehouse in exactly one city.
14
SQL Notes
PARTS TABLE
15
SQL Notes
SHIPMENTS TABLE
We assume that there can be at most one shipment at any given time
for a given supplier and a given part.
16
SQL Notes
SHIPMENTS TABLE
17
SQL Notes
SHIPMENTS TABLE
The shipments table serves in a sense to connect the other two tables
together.
EXAMPLE
18
SQL Notes
19
SQL Notes
Shipments
S1 P1 300
S1 P2 200
S1 P3 400
S2 P1 300
S2 P2 400
20
SQL Notes
21
SQL Notes
city CHAR(15) ,
PRIMARY KEY ([s-no]) );
Brackets
"s-no" and "p-no" are placed in brackets as [s-no] and [p-no] to
indicate to Access that this is a single name and not "s minus no" or
"p minus no". In general, brackets are used to enclose a name (e.g.,
a column or table name) that contains one or more non-alphabetic or
non-numeric characters, or one or more spaces. The brackets tell
the SQL parser that what is between them is a character string which
may include odd characters and spaces.
22
SQL Notes
The screen "File New Database" appears. Give the database a file
name and move to the directory where you want to keep it. When
you mouseclick the "create" button, the database will be created
and saved in the directory you specified.
Type in the name of each column in the table under "Field name".
Move the cursor to the "Data Type" column and a pull-down menu
appears. For any type of character format select "text". For any
type of integer or real number select "number".
Close the form and when it asks you to save the form, type in the
table name. In this case, "Suppliers".
23
SQL Notes
OBJECTIVE
Insert the row "P1, Nut, Red, 12, London" into the parts
table.
Brackets
"p-no" is placed in brackets as [p-no] to indicate to Access that this is a
single name and not "p minus no".
24
SQL Notes
OBJECTIVE
Insert the row "P1, Nut, Red, 12, London" into the parts table.
METHODOLOGY
"open" the database table parts by highlighting its icon under the
"table" tab and mouseclicking "open".
The table will appear with columns labels for each column. Type
"P1, Nut, Red, 12, London" into the respective columns.
25
SQL Notes
OBJECTIVE
Retrieve the value of city from the table suppliers where the
supplier number, s-no, is equal to S4.
DATABASE "QUERY"
(i.e., the interactive SQL statement)
SELECT city
FROM suppliers
WHERE [s-no] = 'S4' ;
city
London
26
SQL Notes
27
SQL Notes
SQL FUNCTIONS
* CREATE TABLE
* CREATE VIEW
* CREATE INDEX
* DROP TABLE
* DROP VIEW
* DROP INDEX
28
SQL Notes
SQL FUNCTIONS
(CONTINUED)
29
SQL Notes
OBSERVATIONS ON SQL
It is a "set-level language."
It is "non-procedural."
30
SQL Notes
OBJECTIVE
QUERY
SELECT [s-no]
FROM shipments
WHERE [p-no] = 'P2' ;
RESULT
s-no
S1
S2
S3
S4
In general, brackets are used to enclose a name (e.g., a column or table name)
that contains one or more non-alphabetic or non-numeric characters, or one or
more spaces. The brackets tell the SQL parser that what is between them is a
character string which may include odd characters and spaces.
31
SQL Notes
SQL NOTES
2 Data Definition
4 Miscellaneous Topics
32
SQL Notes
2. DATA DEFINITION
2.2 Indexes
33
SQL Notes
- CREATE TABLE
- CREATE VIEW
- CREATE INDEX
- ALTER TABLE
- DROP TABLE
- DROP VIEW
- DROP INDEX
34
SQL Notes
DEFINITION OF A "TABLE"
* Each data row contains exactly one data value for each
of the columns.
35
SQL Notes
36
SQL Notes
AUTONOMOUS
The table exists in its own right and is not derived from one
or more base tables as a "view" table is.
NAMED
37
SQL Notes
GENERAL SYNTAX
NOTE
In a syntax definition, the square brackets, "[" and "]",
indicate the material enclosed within them is optional.
38
SQL Notes
RESULT
Suppliers table
s-no sname status city
39
SQL Notes
* Data can now be entered into the table via the SQL
INSERT statement.
40
SQL Notes
41
SQL Notes
42
SQL Notes
Numeric Data
43
SQL Notes
NULL VALUES
44
SQL Notes
45
SQL Notes
46
SQL Notes
DESCRIPTION
GENERAL SYNTAX
47
SQL Notes
OBJECTIVE
SQL STATEMENT
SQL STATEMENT
RESULT
Suppliers table
s-no sname status city
48
SQL Notes
49
SQL Notes
DESCRIPTION
GENERAL SYNTAX
RESULT
50
SQL Notes
51
SQL Notes
2.2 INDEXES
WHAT IS AN INDEX?
EXAMPLE
52
SQL Notes
ADVANTAGES OF INDEXING
53
SQL Notes
DISADVANTAGES OF INDEXING
54
SQL Notes
DESCRIPTION
GENERAL SYNTAX
55
SQL Notes
56
SQL Notes
OBJECTIVE
SQL STATEMENT
RESULT
57
SQL Notes
58
SQL Notes
DESCRIPTION
GENERAL SYNTAX
RESULT
59
SQL Notes
60
SQL Notes
SQL NOTES
2 Data Definition
4 Miscellaneous Topics
61
SQL Notes
3. DATA MANIPULATION
62
SQL Notes
INTRODUCTION
* Retrieving information
* Updating information
* Deleting existing rows
* Inserting new rows
63
SQL Notes
DEFINITION
64
SQL Notes
SELECT STATEMENT
DESCRIPTION
GENERAL SYNTAX
FROM table(s)
[ WHERE predicate ]
[ GROUP BY column-name(s)
[HAVING predicates ] ]
[ ORDER BY column-name(s) ] ;
SELECT column-name(s)
FROM table(s)
65
SQL Notes
OBJECTIVE
From the suppliers table, get the supplier numbers and status for
suppliers in Paris.
QUERY
RESULT
s-no status
S2 10
S3 30
66
SQL Notes
QUERY
Get the supplier numbers and the part numbers for suppliers and for
parts from Paris.
RESULT
s-no p-no
S2 P2
S3 P2
S2 P5
S3 P5
67
SQL Notes
68
SQL Notes
lastname major
Jones IE
Jones IE
Smith MAE
lastname major
Jones IE
Smith MAE
69
SQL Notes
EXAMPLE QUERY
QUERY
SELECT [p-no]
FROM shipments ;
RESULT
p-no
P1
P2
P3
P4
P5
P6
P1
P2
P2
P2
P4
P5
70
SQL Notes
QUERY
RESULT
p-no
P1
P2
P3
P4
P5
P6
71
SQL Notes
Query
RESULT
part number supplier no
P1 S1
P2 S1
P3 S1
P4 S1
P5 S1
P6 S1
P1 S2
P2 S2
P2 S3
P2 S4
P4 S4
P5 S4
72
SQL Notes
In this example, we will combine the results from [p-no] and [s-no] to
form a single output labeled “primary key” . We use the “&” operator.
The query combines the [p-no] retrieved with the character string “ and
“ and with [s-no] retrieved for each qty value.
QUERY
SELECT [p-no] & " and " & [s-no] AS [primary key ], qty
FROM shipments;
RESULT
primary key qty
P1 and S1 300
P2 and S1 200
P3 and S1 400
P4 and S1 200
P5 and S1 100
P6 and S1 100
P1 and S2 300
P2 and S2 400
P2 and S3 200
P2 and S4 200
P4 and S4 300
P5 and S4 400
Note that the entries include the "and" character string. For example,
the first row lists a primary key as "P1 and S1".
73
SQL Notes
QUALIFIED RETRIEVAL
-- THE WHERE PREDICATE --
74
SQL Notes
COMPARISON OPERATORS
=, <>, >, >=, <, <=
OBJECTIVE
Get the supplier numbers, part numbers and quantity from the
shipments table where the quantity is equal to 200.
QUERY
RESULT
75
SQL Notes
COMPARISON OPERATORS
=, <>, >, >=, <, <=
OBJECTIVE
Get the supplier numbers, part numbers and quantity from the
shipments table where the quantity is not equal to 200.
QUERY
RESULT
76
SQL Notes
COMPARISON OPERATORS
=, <>, >, >=, <, <=
OBJECTIVE
Get the supplier numbers, part numbers and quantity from the
shipments table where the quantity is greater than 200.
QUERY
RESULT
77
SQL Notes
COMPARISON OPERATORS
=, <>, >, >=, <, <=
OBJECTIVE
Get the supplier numbers, part numbers and quantity from the
shipments table where the quantity is greater than or equal to 200.
QUERY
RESULT
78
SQL Notes
BOOLEAN OPERATORS
AND, OR, XOR, EQV, NOT
OBJECTIVE
Get supplier numbers for suppliers in Paris with a status > 20.
QUERY
SELECT [s-no]
FROM suppliers
WHERE city = 'Paris'
AND status > 20 ;
RESULT
s-no
S3
79
SQL Notes
BOOLEAN OPERATORS
AND, OR, XOR, EQV, NOT
OBJECTIVE
Get the entries in the shipments table for those shipments with a
quantity less than or equal to 200 and has part number of either P2 or
P5.
QUERY
RESULT
80
SQL Notes
BOOLEAN OPERATORS
AND, OR, XOR, EQV, NOT
RESULT
Notice the result contains a value for P5 greater than 200. In this
example, the parentheses create a different set of conditions. These
conditions state where either quantity is less than equal to 200 and
part number is P2, or the part number is P5. So, there are two
conditions either of which can apply.
81
SQL Notes
Result:
s-no p-no
S1 P1
S1 P2
S1 P4
S2 P1
S3 P2
S4 P2
S4 P4
82
SQL Notes
In this example we retrieve the entries from the shipments table with a
quantity that is not between 200 and 300.
83
SQL Notes
For IN, if the value matches a value in the list then the comparison
operator evaluates to true and the corresponding row in the table
becomes a row in the result table.
For NOT IN, if the value does not match a value in the list then the
comparison operator evaluates to true and the corresponding row in
the table becomes a row in the result table.
These operators are useful when you need to find a match for many
items. For example,
Find the entries in the shipments table for P1, P2, or P6.
84
SQL Notes
Incorrect Query
SELECT sname
FROM suppliers
WHERE city, sname IN (“London”, “Smith, “Athens”, “Adams”);
Correct Query
SELECT sname
FROM suppliers
WHERE city IN (“London”, “Athens”)
AND sname IN (“Smith, “Adams”);
85
SQL Notes
SELECT sname
FROM suppliers
WHERE city = "London" OR city = "Athens";
Result
sname
Smith
Clark
Adams
SELECT sname
FROM suppliers
WHERE city IN ("London", "Athens");
Result
sname
Smith
Clark
Adams
86
SQL Notes
SELECT sname
FROM suppliers
WHERE city, sname IN (“London”, “Jones”, “Athens”, “Adams”);
SELECT sname
FROM suppliers
WHERE (city AND sname) IN (“London”, “Jones”, “Athens”,
“Adams”);
SELECT sname
FROM suppliers
WHERE city IN (“London”, “Athens”)
AND sname IN (“Jones”, “Adams”);
Result:
sname
Adams
SELECT sname
FROM suppliers
WHERE city AND sname IN (“London”, “Jones”, “Athens”, “Adams”);
This is actually only testing to see if sname is in the list. city is not
tested.
87
SQL Notes
For LIKE, if the string matches the specified string then the operator
evaluates to true and the corresponding row in the table becomes a
row in the result table. The LIKE operator retrieves all rows that
match. If wildcard characters are used then the LIKE operator
succeeds when a partial match is identified.
For NOT LIKE, if the string does not match the specified string then
the comparison operator evaluates to true and the corresponding row
in the table becomes a row in the result table. The NOT LIKE
operator retrieves all rows that don't match. If wildcard characters are
used then the NOT LIKE operator retrieves all rows that don't satisfy a
partial match.
88
SQL Notes
WILDCARD CHARACTERS
89
SQL Notes
Get the names of parts from the Parts table that begin with "c".
SELECT pname
FROM parts
WHERE pname LIKE "c*"; Note the use of the wildcard character * .
Results: pname
Cam
Cog
SELECT sname
FROM suppliers
WHERE sname LIKE "*a*"; Note the use of the wildcard character * .
Results:
sname
Blake
Clark
Adams
SELECT sname
FROM suppliers
WHERE sname NOT LIKE "*a*"; Note the use of the wildcard character *.
Results:
sname
Smith
Jones
90
SQL Notes
In clauses that specify an exact match use equality (i.e., = ) and not
the LIKE operator.
In clauses that specify a partial match use LIKE and not the equality
(i.e., = ) operator.
91
SQL Notes
Get the names of parts from the Parts table that begin with "c".
SELECT pname
FROM parts
WHERE pname LIKE "c*"; Note the use of the wildcard character * .
Results: pname
Cam
Cog
SELECT pname
FROM parts
WHERE pname = "c*";
pname
92
SQL Notes
ORDER BY CLAUSE
RETRIEVAL WITH ORDERING
DESCRIPTION
GENERAL SYNTAX
93
SQL Notes
OBJECTIVE
Retrieve the part number (p-no) and quantity (qty) from the shipments
table ordered by ascending quantity (qty).
QUERY
RESULT
p-no qty
P6 100
P5 100
P4 200
P2 200
P1 300
P3 400
94
SQL Notes
OBJECTIVE
Retrieve the part number, p-no, weight and color from the parts table
ordered by descending weight and by ascending color.
QUERY
RESULT
p-no weight color
P6 19 Red
P3 17 Blue
P2 17 Green
P4 14 Red
P5 12 Blue
P1 12 Red
95
SQL Notes
Objective
Query
Results
s-no avg qty
S2 350.00
S4 300.00
S1 216.67
S3 200.00
96
SQL Notes
97
SQL Notes
OBJECTIVE
QUERY
RESULTS
98
SQL Notes
QUERY
RESULTS
99
SQL Notes
Objective
Query
Result
• We multiply each p-no entry in the shipments table by its weight from
the parts table and by its quantity and then total the values for each
part number.
• The GROUP BY operator organizes the results by part number.
• In the WHERE clause we are performing a JOIN (see section 3.3.3) to
ensure we only use the weight values for those part numbers that are
in the shipments table.
• We qualify table names to prevent confusion during query execution.
100
SQL Notes
3. DATA MANIPULATION
101
SQL Notes
Notes:
1. The UNION operator is not the same as the UNION JOIN operator.
102
SQL Notes
UNION OPERATOR
The Union of two tables produces a table of all rows that appear in
either table.
Syntax
Alternatively:
103
SQL Notes
city
London
Paris
Paris
London
Athens
city
London
Paris
Rome
London
Paris
London
104
SQL Notes
We use the UNION operator to produce a list of all cities for suppliers
or parts.
Result:
city
Athens
London
Paris
Rome
city
London
Paris
Paris
London
Athens
London
Paris
Rome
London
Paris
London
Athens
Athens
105
SQL Notes
106
SQL Notes
DEFINITION
A "join" is a query in which data is retrieved from more than one table
and thus "joins" information from those tables.
NOTES
MSAccess only supports the INNER JOIN, LEFT JOIN, and RIGHT
JOIN.
107
SQL Notes
EQUI-JOIN QUERY
OBJECTIVE
Get all combinations of supplier and part information such that the
supplier and part in question are located in the same city.
QUERY
108
SQL Notes
EQUI-JOIN QUERY
(CONTINUED)
RESULT
109
SQL Notes
OBJECTIVE
QUERY
RESULT
110
SQL Notes
OBJECTIVE
Find the supplier's city and the part's city for supplier and part entries
in the shipments table.
Query
Result
suppliers.city parts.city
London London
London Paris
London Rome
Paris London
Paris Paris
111
SQL Notes
JOIN EXPRESSIONS
Note: MSAccess only supports the INNER JOIN, LEFT JOIN, and
RIGHT JOIN.
112
SQL Notes
JOIN
(NOT SUPPORTED BY MSACCESS)
SELECT *
FROM parts JOIN suppliers USING (city);
113
SQL Notes
CROSS JOIN
(NOT SUPPORTED BY MSACCESS)
The CROSS JOIN is the cartesion product or cross product of two
tables.
SELECT *
FROM suppliers CROSS JOIN parts;
RESULTS
114
SQL Notes
NATURAL JOIN
(NOT SUPPORTED BY MSACCESS)
SELECT *
FROM suppliers NATURAL JOIN parts;
115
SQL Notes
UNION JOIN
(NOT SUPPORTED BY MSACCESS)
The UNION JOIN makes no attempt to match a row from one table
with a row from another table. Instead, it creates the union of all the
columns in both tables, placing NULL values where no data values
exist.
SELECT *
FROM suppliers UNION JOIN parts;
would have all columns from table suppliers and all columns from
table parts. The rows would consist of all rows from table suppliers
followed by all rows from table parts. Within each row, the columns
which do not have values would have a NULL value inserted.
Note: The UNION JOIN is not the same as the UNION operator.
116
SQL Notes
OUTER JOIN
An OUTER JOIN preserves all rows from the resulting table that don't
have corresponding rows in both tables. Thus, an OUTER JOIN
preserves the unmatched rows. The OUTER JOIN operates on two or
more tables. Whichever table is on the left of the LEFT OUTER JOIN
command is considered the LEFT table and whatever table or result is
on the right of the command is known as the RIGHT table. Multiple
JOIN commands can be chained together in a single SELECT
statement. However, unlike a nested query, they are executed from
left to right.
The LEFT OUTER JOIN preserves all unmatched rows from the LEFT
table while discarding unmatched rows from the RIGHT table.
The RIGHT OUTER JOIN preserves all unmatched rows from the
RIGHT table while discarding unmatched rows from the LEFT table.
Combines the functions of the RIGHT and LEFT OUTER JOINS. The
FULL OUTER JOIN retains the unmatched rows from both the left and
right tables.
117
SQL Notes
Syntax
table1 and table2 are the names of the tables from which records are
to be combined.
column_i and column_j are the names of the columns that are joined.
They must be the same data type but don't have to have the same
column name.
operator is any relational operator such as "=", "<", ">", "<=", ">=",
"<>"
The LEFT JOIN creates a left outer join while the RIGHT JOIN creates
a right outer join.
118
SQL Notes
Result:
119
SQL Notes
Result:
120
SQL Notes
Result:
121
SQL Notes
INNER JOIN
An INNER JOIN discards all rows from the resulting table that do not
have corresponding rows in both source tables. This distinguishes it
from an OUTER JOIN that preserves unmatched rows.
Syntax
table1 and table2 are the names of the tables from which records are
to be combined.
column_i and column_j are the names of the columns that are joined.
They must be the same data type but don't have to have the same
column name.
operator is any relational operator -- "=", "<", ">", "<=", ">=", or "<>"
122
SQL Notes
Result:
123
SQL Notes
124
SQL Notes
125
SQL Notes
Syntax
SELECT …
WHERE …
Example
Get all unique pairs of part numbers that have the same quantity
shipped. Show the part number pairs, the supplier number and
quantity.
Note that we have created multiple aliases for the same table. This allows the
query engine to examine all possible combinations of the part number pairs. Note
also that we qualified [s-no] and qty. We had to do this to avoid confusion for the
query engine.
126
SQL Notes
Result:
127
SQL Notes
3. DATA MANIPULATION
128
SQL Notes
The functions are: COUNT, SUM, AVG, MAX, MIN, STDEV and
VAR, as well as STDEVP and VARP.
129
SQL Notes
130
SQL Notes
1. For SUM, AVG, STDEV and VAR the column must contain numeric
values.
5. Any null values in the column are not processed by the functions,
except in the case of COUNT(*).
131
SQL Notes
OBJECTIVE
QUERY
SELECT COUNT([s-no])
FROM suppliers ;
RESULT
5
132
SQL Notes
OBJECTIVE
QUERY
RESULT
4
133
SQL Notes
OBJECTIVE
QUERY
SELECT COUNT([s-no])
FROM shipments
WHERE [s-no]="S5";
RESULT
0
Note: In prior versions of Access the COUNT function returned a Null value when no
items existed in the table for it to count.
134
SQL Notes
OBJECTIVE
QUERY
RESULT
1000
135
SQL Notes
GROUP BY OPERATOR
DEFINITION
The GROUP BY operator logically rearranges the table represented by the FROM
clause into partitions or "groups." For each group, the MIN, MAX, AVG, SUM, and
COUNT can be computed.
So, GROUP BY s-no, p-no, qty would produce a result organized as follows:
s1 p1 quantity of p1 from s1
p2 quantity of p2 from s1
s2 p1 quantity of p1 from s2
p2 quantity of p2 from s2
s3 p1 quantity of p1 from s3
p2 quantity of p2 from s3
136
SQL Notes
OBJECTIVE
For each part supplied, get the part number and the total
shipment quantity for that part.
QUERY
RESULT
The quantities for each supplier are summed together and the results
organized into a table. The GROUP BY operator produces this
organization and grouping.
137
SQL Notes
Get the supplier number and the total quantity they are shipping.
QUERY
RESULT
The quantities for each supplier are summed together and the results
organized into a table. The GROUP BY operator produces this
organization and grouping.
138
SQL Notes
QUERY
RESULT
139
SQL Notes
HAVING CLAUSE
GENERAL SYNTAX
FROM table(s)
[ WHERE predicate ]
[ GROUP BY column-name(s)
[HAVING predicates ] ]
[ ORDER BY column-name(s) ] ;
140
SQL Notes
OBJECTIVE
For each part supplied, get the part number and the total
shipment quantity for that part. Group by part number
only those parts equal to P3 or P4.
QUERY
RESULT
p-no Totals
P3 400
P4 500
Compare this result with the result from the query without the HAVING
clause.
p-no Totals
P1 600
P2 1000
P3 400
P4 500
P5 500
P6 100
141
SQL Notes
3. DATA MANIPULATION
142
SQL Notes
DEFINITION
143
SQL Notes
IN AND NOT IN
NESTED QUERY OPERATORS
IN operator
NOT IN operator
144
SQL Notes
Find the part numbers of parts in the shipments table that originate in Paris.
RESULT
p-no
P1
P2
Find the part numbers of parts in the shipments table that do not originate in Paris.
In the example, rows are selected from the shipments table when the
s-no in the row is in or not in the list of suppliers.[s-no] returned by the
subquery.
145
SQL Notes
EXISTS operator
146
SQL Notes
Find the part numbers of parts in the shipments table if any supplier originates in
Paris.
RESULTS:
p-no
P1
P2
P3
P4
P5
P6
In this example we are asking "Is there any supplier whose city is
'Paris'?" Since in all cases the answer is "yes" we return a list of all
part numbers in shipments table.
147
SQL Notes
Find the part numbers of parts in the shipments table where the supplier
originates in Paris.
Result
p-no
P1
P2
shipments.[s-no]=suppliers.[s-no]
148
SQL Notes
QUERY
RESULT
In the example, rows are selected from the shipments table when the
nested subquery succeeds in any form. The system executes the
nested subquery for each [p-no] row in the shipments table. If the
nested subquery succeeds then for EXISTS operator, the row is kept.
If the nested subquery fails then for the NOT EXISTS operator, the
row is not kept.
Since a supplier whose city is "Paris" exists then in all instances the
NOT EXISTS fails so no values can satisfy the query.
149
SQL Notes
Example
Get supplier numbers for those suppliers that have a status that is
higher than the status of supplier S1.
SELECT suppliers.[s-no]
FROM suppliers
WHERE suppliers.status > (SELECT suppliers.status
FROM suppliers
WHERE suppliers.[s-no] = 'S1');
Result
s-no
S3
S5
150
SQL Notes
The ALL operator is a universal quantifier and the SOME and ANY
operators are existential quantifiers. The SOME and ANY operators
are synonymous and can be used interchangeably.
These operators are used to quantify the =, <, >, <=, >=, <> operators.
"< ALL" is interpreted to mean that the less than condition must satisfy
all values returned.
"< SOME" or "< ANY" is interpreted to mean that the less than
condition must satisfy at least one of the values returned.
Example
Get supplier numbers for those suppliers that have a status that is
higher than the status of supplier S1 or S2.
Result
s-no
S1
S3
S4
S5
151
SQL Notes
152
SQL Notes
NESTED QUERY
-- EXAMPLE 1 --
QUERY
SELECT suppliers.sname
FROM suppliers
WHERE suppliers.[s-no] IN ( SELECT shipments.[s-no]
FROM shipments
WHERE shipments.[p-no] = 'P2' );
SELECT suppliers.sname
FROM suppliers, shipments
WHERE suppliers.[s-no] = shipments.[s-no]
AND shipments.[p-no] = 'P2';
RESULT
sname
Smith
Jones
Blake
Clark
153
SQL Notes
NESTED QUERY
-- EXAMPLE 2 --
QUERY
SELECT suppliers.sname
FROM suppliers
WHERE suppliers.[s-no] IN (SELECT shipments.[s-no]
FROM shipments
WHERE shipments.[p-no] IN (SELECT parts.[p-no]
FROM parts
WHERE parts.color='RED'));
RESULT
sname
Smith
Jones
Clark
154
SQL Notes
CORRELATED SUBQUERIES
Example
SELECT [sname]
FROM suppliers
WHERE [s-no] NOT IN (SELECT [s-no]
FROM shipments
WHERE suppliers.[s-no] = shipments.[s-no]);
Result:
sname
Adams
155
SQL Notes
Syntax
SELECT …
WHERE …
SELECT x.sname
FROM suppliers AS x
WHERE x.[s-no] NOT IN (SELECT y.[s-no]
FROM shipments AS y
WHERE x.[s-no] = y.[s-no]);
Result:
sname
Adams
The alias "x" is created for table suppliers and the alias "y" is created
for shipments.
156
SQL Notes
Get the supplier number for the supplier who is first in the alphabetical
list of supplier names unless they have a pending shipment.
SELECT x.[s-no]
FROM suppliers AS x
WHERE x.sname = (SELECT MIN(y.sname)
FROM suppliers AS y)
AND x.[s-no] NOT IN (SELECT [s-no]
FROM shipments);
Result:
s-no
S5
157
SQL Notes
Example
Get all unique pairs of part numbers that have the same quantity
shipped. Show the part number pairs, the supplier number and
quantity.
Note that we have created multiple aliases for the same table. This allows the
query engine to examine all possible combinations of the part number pairs. Note
also that we qualified [s-no] and qty. We had to do this to avoid confusion for the
query engine.
Result:
158
SQL Notes
This problem arises from returning two columns with the part number
as the column heading (i.e., x.p-no and y.p-no ) because of your use of
two aliases for the same table. You get duplicate entries without
duplicate rows because the pair will appear twice in the output, once
as the ordered pair {x.[p-no], y.[p-no]} and once as the ordered pair
{y.[p-no], x.[p-no]}. In this way, the rows are not duplicated since the
positions of the part numbers are switched. However, the information
is duplicated. Using the not equal operator will not solve the problem
because it will retrieve redundant pairs (try it to see). Instead use the
less than inequality to eliminate redundant pairs (i.e., x.[p-no] < y.[p-
no]). It removes redundant pairs because it will not allow both pairs to
exist since either the ordered pair {x.[p-no], y.[p-no]} or the ordered pair
{y.[p-no], x.[p-no]} will violate the inequality.
159
SQL Notes
Result:
160
SQL Notes
The result is a table in which the first column lists the name of the
supplier that has a supplier number in the shipments table. Note also
that we gave the column a name using the AS command.
Query Result
Supplier s-no p-no qty
Smith S1 P1 300
Smith S1 P2 200
Smith S1 P3 400
Smith S1 P4 200
Smith S1 P5 100
Smith S1 P6 100
Jones S2 P1 300
Jones S2 P2 400
Blake S3 P2 200
Clark S4 P2 200
Clark S4 P4 300
Clark S4 P5 400
Note that this also could have been done using the following query.
161
SQL Notes
Query Result
162
SQL Notes
What supplier ships the maximum average quantity and what is that
quantity?
Query
Result
s-no Max of avg quantity
S2 350
produces the following table against which we run the outer query.
s-no avgqty
S1 216.666666666667
S2 350
S3 200
S4 300
163
SQL Notes
3. DATA MANIPULATION
164
SQL Notes
Example
Get the supplier name and the part name for suppliers and parts that
are in the shipments table, and the quantity being shipped. In
addition, combine the supplier name and the parts name into a new
name for the quantity.
QUERY
165
SQL Notes
QUERY RESULTS
Notice that the supplier name is combined with the part name to form
the “primary key value”.
166
SQL Notes
Note that the times are ordered in ascending order and that the
corresponding numbers are ordered in ascending order.
QUERY
SELECT SUM(DATEDIFF("n",b.[time],a.[time]))
FROM test AS A, test AS b
WHERE A.num=([B].[num]+1);
RESULT
795 minutes
167
SQL Notes
You can use an insert to copy the time values into a new table that
has a column with an autonumber data type. The new table is created
using the following INSERT command.
The time values are retrieved from the database table that holds them.
In the example this is database table timetable. The ORDER BY
clause ensures that the time values are inserted in the correct order.
As they are inserted into table test, the autonumber data type will
automatically create sequential numbers in the column num of table
test.
168
SQL Notes
3. DATA MANIPULATION
169
SQL Notes
DEFINITION
170
SQL Notes
UPDATE STATEMENT
DEFINITION
GENERAL SYNTAX
UPDATE table-name
SET column-name = expression
[, column-name = expression ] ...
[ WHERE predicate ] ;
NOTE: If the WHERE conditions are not met then the UPDATE
executes but no changes are made.
171
SQL Notes
2. If the WHERE conditions are not met then the UPDATE executes
but does not make any changes.
172
SQL Notes
Objective
SQL Statement
UPDATE parts
SET color = 'Yellow',
weight = weight + 5,
city = NULL
WHERE [p-no] = 'P2' ;
Result
173
SQL Notes
EXAMPLE 2
SEARCH AND REPLACEMENT OF NULL VALUES
Objective
SQL Statement
UPDATE parts
SET city = 0
Results
174
SQL Notes
OBJECTIVE
SQL STATEMENT
UPDATE parts
SET weight = weight*0.45;
RESULT
175
SQL Notes
DELETE STATEMENT
DEFINITION
GENERAL SYNTAX
176
SQL Notes
OBJECTIVE
Delete the row in the Parts table that contains part "p6"
SQL STATEMENT
RESULTS
The following row has been deleted from the parts table.
177
SQL Notes
DELETE STATEMENT
-- EXAMPLE 2 --
OBJECTIVE
SQL STATEMENT
This DELETE uses a nested query to identify the suppliers that have
"London" as their city. Their supplier number ([s-no] ) is set to the
supplier number in the shipments table through the condition
suppliers.[s-no] = shipments.[s-no]
178
SQL Notes
RESULT
179
SQL Notes
INSERT STATEMENT
DEFINITION
The INSERT statement can be used to insert specific
values into a row of a table, or it can be used with an
embedded SELECT statement that can result in multiple
rows being inserted into a table.
GENERAL SYNTAX
or
Note that you must explicitly specify the column names. You cannot
use a wild card specification of "*" as with a SELECT query.
180
SQL Notes
OBJECTIVE
SQL STATEMENT
You can only insert constants one row at a time so two statements are
needed.
P7 Athens 24
P8 Raleigh 28
181
SQL Notes
RESULT
Parts table
P-no PName Color Weight City
P1 Nut Red 12 London
P2 Bolt Green 17 Paris
P3 Screw Blue 17 Rome
P4 Screw Red 14 London
P5 Cam Blue 12 Paris
P6 Cog Red 19 London
P7 24 Athens Inserted Row
182
SQL Notes
OBJECTIVE
For each part supplied, get the part number and the total
quantity supplied of that part, and save the result in the
database in table TEMP.
SQL STATEMENTS
SQL Statement 1:
SQL Statement 2:
183
SQL Notes
OBJECTIVE
SQL Query
Results
The query:
184
SQL Notes
SQL NOTES
2 Data Definition
4 Miscellaneous Topics
185
SQL Notes
4. MISCELLANEOUS TOPICS
186
SQL Notes
DEFINITION
187
SQL Notes
188
SQL Notes
4.2 VIEWS
189
SQL Notes
VIEWS
(CONTINUED)
190
SQL Notes
191
SQL Notes
NOTES ON VIEWS
192
SQL Notes
VIEW STATEMENT
DEFINITION
GENERAL SYNTAX
193
SQL Notes
OBJECTIVE
SQL STATEMENT
RESULT
good_suppliers
S1 20 London
S3 30 Paris
S4 20 London
S5 30 Athens
194
SQL Notes
DEFINITION
GENERAL SYNTAX
195
SQL Notes
OBJECTIVE
SQL STATEMENT
RESULT
196
SQL Notes
OPERATIONS ON VIEWS
RETRIEVAL OPERATIONS
UPDATE OPERATIONS
197
SQL Notes
4.3 SECURITY
DEFINITION
198
SQL Notes
199
SQL Notes
GRANT STATEMENT
DEFINITION
GENERAL SYNTAX
GRANT statement-name
[, statement-name ] ...
ON TABLE table-name [, table-name ] ...
TO user-name [, user-name ] ... ;
200
SQL Notes
REVOKE STATEMENT
DEFINITION
GENERAL SYNTAX
REVOKE statement-name
[, statement-name ] ...
ON TABLE table-name [, table-name ] ...
TO user-name [, user-name ] ... ;
201
SQL Notes
EXAMPLE 1
OBJECTIVE
SQL STATEMENT
202
SQL Notes
EXAMPLE 2
OBJECTIVE
SQL STATEMENT
203
SQL Notes
EXAMPLE 3
OBJECTIVE
SQL STATEMENT
204
SQL Notes
4.4 RECOVERY
COMMIT Statement
ROLLBACK Statement
System Recovery
205
SQL Notes
DEFINITION OF A "TRANSACTION"
206
SQL Notes
207
SQL Notes
OBJECTIVE
SQL STATEMENT
UPDATE suppliers
SET [s-no] = 'S2'
WHERE [s-no] = 'S1' ;
UPDATE shipments
SET [s-no] = 'S2'
WHERE [s-no] = 'S1' ;
208
SQL Notes
QUESTION
ANSWER
209
SQL Notes
UPDATE suppliers
SET [s-no] = 'S2'
WHERE [s-no] = 'S1' ;
UPDATE shipments
SET [s-no] = 'S2'
WHERE [s-no] = 'S1' ;
210
SQL Notes
COMMIT STATEMENT
DEFINITION
211
SQL Notes
ROLLBACK STATEMENT
DEFINITION
212
SQL Notes
SYSTEM RECOVERY
213
SQL Notes
SYSTEM RECOVERY
(CONTINUED)
214
SQL Notes
SYSTEM RECOVERY
(CONTINUED)
215
SQL Notes
216
SQL Notes
217
SQL Notes
* PRIOR means that you are walking the tree from the root
downward so you will encounter each parent node "prior" to
its child.
218
SQL Notes
QUERY
219