0% found this document useful (0 votes)
2 views

SQLNotes

The document contains SQL notes by Robert E. Young, providing comprehensive information on relational databases and the SQL language, including data definition, manipulation, and various SQL commands. It features a Supplier-Parts database example to illustrate concepts and includes a detailed table of contents outlining the topics covered. The material is based on multiple sources, primarily 'An Introduction to Database Systems' by C. J. Date.

Uploaded by

Shafiul Alam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

SQLNotes

The document contains SQL notes by Robert E. Young, providing comprehensive information on relational databases and the SQL language, including data definition, manipulation, and various SQL commands. It features a Supplier-Parts database example to illustrate concepts and includes a detailed table of contents outlining the topics covered. The material is based on multiple sources, primarily 'An Introduction to Database Systems' by C. J. Date.

Uploaded by

Shafiul Alam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 223

ISE417 & ISE519

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

An Introduction to Database Systems by C. J. Date


Addison Wesley Longman Inc., publisher

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

Supplier-Parts Database .............................................................................................. iv


1. The Relational Data Model ....................................................................................... 2
1.1 Background .................................................................................................. 3
1.2 Example RDBMS ....................................................................................... 11
1.3 The SQL Language .................................................................................... 21
2. Data Definition .................................................................................................. 33
2.1 Base Tables ......................................................................................................... 34
CREATE TABLE Statement .............................................................................. 38
SQL Data Types ............................................................................................... 41
Data Types Within MS ACCESS ....................................................................... 42
ALTER TABLE Statement ................................................................................. 47
DROP TABLE Statement .................................................................................. 50
2.2 Indexes................................................................................................................ 52
CREATE INDEX Statement .............................................................................. 55
DROP INDEX Statement .................................................................................. 59
3. Data Manipulation .............................................................................................. 62
3.1 Simple Queries .................................................................................................... 64
SELECT Statement ........................................................................................... 65
Qualifying a Column Name with a Table Name ................................................. 67
"DISTINCT" and "DISTINCTROW" Keywords ................................................... 68
The "AS" keyword Renaming Columns that are Retrieved ................................ 72
Qualified Retrieval -- The WHERE Predicate -- ................................................. 74
Comparison Operators =, <>, >, >=, <, <= ....................................................... 75
Boolean Operators AND, OR, XOR, EQV, NOT............................................... 79
BETWEEN and NOT BETWEEN Operators ..................................................... 82
IN and NOT IN Operators ................................................................................. 84
LIKE and NOT LIKE Operators ......................................................................... 88
Wildcard Characters ...................................................................................... …89
ORDER BY Clause Retrieval with Ordering ...................................................... 93
Arithmetic Expressions in a Query Retrieval ..................................................... 97
Arithmetic Expressions and Functions in a Query Retrieval ............................ 100
3. Data Manipulation ............................................................................................ 101
3.2 Relational Operators -- UNION, INTERSECT and EXCEPT -- .......................... 102
UNION operator .............................................................................................. 103
3.3 Data Manipulation ........................................................................................... 106
3.3 Relational Operators -- JOINs -- ........................................................................ 107
Equi-join Query ............................................................................................... 108
Greater-Than Join Query ................................................................................ 110
Multi-Table Join Query .................................................................................... 111
JOIN Expressions ........................................................................................... 112
JOIN (not supported by MSAccess) ............................................................... 113
CROSS JOIN (not supported by MSAccess) ................................................... 114
NATURAL JOIN (not supported by MSAccess) ............................................... 115
UNION JOIN (not supported by MSAccess) .................................................... 116
OUTER JOIN .................................................................................................. 117
LEFT & RIGHT OUTER JOIN ......................................................................... 118
INNER JOIN.................................................................................................... 122
ON versus WHERE clauses in JOINS............................................................. 124

ii
SQL Notes

Maximum Number of Tables that can be Joined ............................................. 125


Aliases for Table Names in JOIN Queries ....................................................... 126
3.4 Built-in Functions or Aggregate Functions ......................................................... 129
Definition of the Functions ............................................................................... 130
GROUP BY Operator ...................................................................................... 136
Groups within Groups using the GROUP BY Operator ................................... 139
HAVING Clause .............................................................................................. 140
3.5 Nested Queries .................................................................................................. 143
IN and NOT IN Nested Query Operators......................................................... 144
EXISTS and NOT EXISTS Nested Query Operators ...................................... 146
Comparison Operators in Nested Queries =, <, >, <=, >=, <> ......................... 150
ANY, SOME and ALL Operators ..................................................................... 151
Notes on Nested Queries ................................................................................ 152
Correlated Subqueries .................................................................................... 155
Aliases for Table Names in NESTED Queries ................................................. 156
Multiple Aliases for the Same Table ................................................................ 158
Nested Queries in the SELECT and in the FROM ........................................... 161
3.6 Interesting Uses of Queries ................................................................................ 165
Computing Differences between row entries ................................................... 167
How do I get the sequential numbers? ............................................................ 168
3.7 Update Operations ............................................................................................ 170
UPDATE Statement ........................................................................................ 171
DELETE Statement ......................................................................................... 176
INSERT Statement ......................................................................................... 180
Example of a Single-Record INSERT .............................................................. 181
Example of a Multiple-Record INSERT ........................................................... 183
Example of a Conditional in an INSERT .......................................................... 184
4. Miscellaneous Topics ...................................................................................... 186
4.1 The System Catalog .......................................................................................... 187
4.2 Views................................................................................................................. 189
VIEW Statement ............................................................................................. 193
DROP VIEW Statement .................................................................................. 195
4.3 Security ............................................................................................................. 198
4.4 Recovery ........................................................................................................... 205
4.5 Bill-of-Materials problem .................................................................................... 216

iii
SQL Notes

SUPPLIER-PARTS DATABASE

from An Introduction to Database Systems by C. J. Date,


Addison Wesley Longman Inc, 2000.

Suppliers table s-no sname status city


S1 Smith 20 London
S2 Jones 10 Paris
S3 Blake 30 Paris
S4 Clark 20 London
S5 Adams 30 Athens

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

Shipments table s-no p-no qty


S1 P1 300
S1 P2 200
S1 P3 400
S1 P4 200
S1 P5 100
S1 P6 100
S2 P1 300
S2 P2 400
S3 P2 200
S4 P2 200
S4 P4 300
S4 P5 400

iv
SQL NOTES

1 The Relational Data Model

2 Data Definition

3 SQL Queries -- Data Manipulation

4 Miscellaneous Topics

 The System Catalog


 Views
 Security
 Recovery
 Bill-of-Materials Problem
SQL Notes

1. THE RELATIONAL DATA MODEL

1.1 Background

1.2 Example RDBMS

1.3 The SQL language

2
SQL Notes

1.1 BACKGROUND

A database is a collection of data stored in some organized way that


was traditionally kept on paper and is now stored on a computer. A
database management system (DBMS) is a computerized system that
allows users to define and manipulate the data in a database to
produce meaningful information. As on paper, the data is organized
within a database in a specific way so that it has meaning and can be
retrieved quickly as needed. The conceptual basis of the database
management system determines the structure around which data is
organized so that it can be efficiently manipulated and retrieved. A
relational database is currently the most widely used conceptual basis.

A relational database is organized into tables much like you would


organize information in a spreadsheet. Each table stores data that
has some connection when viewed together. An example would be a
table with you and your friend's name, address and phone number.
There can be many databases. Tables within a database have some
relationship among them that ensures the data within the database
and within the database tables is efficiently organized and stored. The
tables' structure and inter-table relationships provide a context that
transforms data into information. To understand how this works let's
first look at table structure and then at inter-table relationships.

1.1.1 TABLE STRUCTURE

Within a table data is arranged in a meaningful way using rows and


columns. The columns organize data into categories while the rows
contain specific values for the categories. Data within a row defines a
unique entry in the table. In database terminology, columns are
"fields" and rows are "records."

Column – a field in a database table.

Row – a record in a database table.

3
SQL Notes

To distinguish one row from another row we create a "unique


identifier" for each row. This is called the primary key.

Primary Key – one or more columns whose values taken together


uniquely identify a single row in a database table.

Within each table, no two primary key values can be identical ensuring
no two rows will be identical. This reduces redundancy.

Below is a database table containing information.

Each supplier has a:

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

Field Data value in a


Each Column in a field of a record
table is a field (row/column
intersection)

Record
Each row
in a table
is a record

Figure 1. Database table structure example.

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.

We organize data to give it meaning. Most often we use a table


structure to organize and hold the data and "column headings" to
provide context. Giving the table itself a name adds additional
context. Knowing that the database table in Figure 1 is the Suppliers
table allows you to identify S-no, Sname, Status and City as data
related to a supplier. These column names now have additional
context giving them more meaning.

1.1.2 RELATIONSHIPS AMONG DATABASE TABLES

Among database tables relationships provides additional context


increasing the database's information content. Figure 2 contains two
tables in addition to the Suppliers table. This is the Supplier-Parts
Database. Examining the table names and column names we see
that the Supplier table contains data about suppliers, the Parts table
contains data about parts, and the shipments table contains data
about shipments. The shipments table implies it contains data that
relates suppliers and parts. But does it?

Relationships among database tables explicitly specify the


relationships among tables and the nature of the relationship. The
nature of the relationship defines "how" the tables are related. As an
example, within the shipments table we see that multiple suppliers can
supply multiple parts since S1, S2 and S4 do so. We also see that
multiple parts can be supplied by multiple suppliers as P1, P2, P4 and
P5 are supplied by more than one supplier. Since the data within a
table can change, by looking at the table data we can't determine
whether or not S2, S3, S4 and S5 can supply all the parts, and
whether or not P3 can be supplied by more than one supplier.
However, explicitly defining the nature of the relationship gives us this

5
SQL Notes

information. Figure 3 is an example of explicitly defining the


relationships. It specifies that all suppliers can supply all parts and
that all parts can be supplied by all suppliers.

Figure 2. Supplier-Parts Database.

Suppliers Parts

S-no P-no

Sname Pname
Status Color
City Weight
SuppliersCol1 City
PartsCol1
Shipments

P-no (FK)
S-no (FK)

QTY
ShipmentsCol1

Figure 3. Relationships between database tables

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

"SQL" is an acronym for structured query language and is now a


world-wide standard for defining the database, putting data into the
database, and getting information from the database. This document
provides an in depth description with examples of the SQL language
and its application.

7
SQL Notes

WHERE DID THE NAME "RELATIONAL" DBMS COME


FROM?

* Called "relational" because the inventor, Dr. E. F. Codd, was


a mathematician and decided to use the term "relation" to
describe what we call a "table."

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

* Importance of the relational model is that it is the only DBMS


approach with a sound mathematical foundation.

8
SQL Notes

WHAT IS "SQL"?

* SQL is the language used by most relational DBMSs to


create databases, and to insert, retrieve, and manipulate
data.

* SQL first defined by IBM and initially implemented in a


prototype relational DBMS called "System R."

* This evolved into IBM's relational DBMSs, DB2 and SQL/DS.

* SQL standard is being developed by the American National


Standards Institute's Database Committee (ANSI/SPARC).

9
SQL Notes

SQL AS A STANDARD

* The SQL standards have been implemented by all companies


selling relational DBMSs.

* All relational DBMSs have products that run under Windows


95 and Windows NT that use SQL.

* Because of this activity and interest, SQL has become a


worldwide standard language for relational DBMSs.

Consequently, we will use only SQL to teach you about relational


DBMSs.

10
SQL Notes

1.2 EXAMPLE RDBMS

CONSISTS OF THREE TABLES

* suppliers table
* parts table
* shipments table

11
SQL Notes

SUPPLIERS TABLE

EACH SUPPLIER HAS A:

* unique supplier number - s-no


* Supplier name - sname
* Rating or status value - status
* Location - city

We assume that each supplier is located in exactly one city.

12
SQL Notes

SUPPLIERS TABLE

s-no sname status city


S1 Smith 20 London
S2 Jones 10 Paris
S3 Blake 30 Paris
S4 Clark 20 London
S5 Adams 30 Athens

13
SQL Notes

PARTS TABLE

EACH TYPE OF PART HAS A:

* Unique part number - p-no


* Part name - pname
* Color - color
* Weight - weight
* Location where parts of that
type are stored - city

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

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

15
SQL Notes

SHIPMENTS TABLE

EACH SHIPMENT HAS A:

* Supplier number - s-no


* Part number - p-no
* Quantity - qty

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

s-no p-no qty


S1 P1 300
S1 P2 200
S1 P3 400
S1 P4 200
S1 P5 100
S1 P6 100
S2 P1 300
S2 P2 400
S3 P2 200
S4 P2 200
S4 P4 300
S4 P5 400

17
SQL Notes

SHIPMENTS TABLE

The shipments table serves in a sense to connect the other two tables
together.

EXAMPLE

The first row of table shipments connects a


specific supplier (supplier S1) from table
supplier with a specific part (part P1) from table
parts to be shipped in a Specific quantity (300
parts).

18
SQL Notes

IMPORTANT POINTS ABOUT THE TABLES

1. All values are "atomic," there are no "repeating groups."

* At every row-and-column position in every table


there is always exactly one data value, never a set of
values.

2. The entire information content of the database is


represented as explicit data values.

* There is no physical link between tables that is


explicitly visible to the user as in non-relational
systems.

19
SQL Notes

EXAMPLE OF A REPEATING GROUP

ITEMS FROM THE SHIPMENTS TABLE

Shipments

s-no p-no qty

S1 P1 300
S1 P2 200
S1 P3 400
S2 P1 300
S2 P2 400

THE ITEMS AS REPEATING GROUPS

s-no p-no qty


S1 {P1, P2, P3} {300, 200, 400}
S2 {P1, P2} {300, 400}

Repeating Groups are NOT allowed in relational database tables.

20
SQL Notes

1.3 THE SQL LANGUAGE

CREATING THE SUPPLIERS-AND-PARTS DATABASE

* Use the SQL Data Definition Statement, CREATE TABLE,


to create each table.

* Each CREATE TABLE statement gives the:

 Name of the table to be created.


 Names of its columns.
 Data types of those columns.
 Specification of those columns that can't be null (i.e.,
"NOT NULL").
 Specification of those columns that uniquely identify a
row in the table (i.e., the "primary key").
 Conditions that data must meet to be acceptable as a
column entry in a row.

21
SQL Notes

THE SUPPLIERS-AND-PARTS DATABASE DEFINITION

CREATE TABLE Suppliers

( [s-no] CHAR(5) NOT NULL,


sname CHAR(20),
status SMALLINT,

city CHAR(15) ,
PRIMARY KEY ([s-no]) );

CREATE TABLE Parts


( [p-no] CHAR(6) NOT NULL,
pname CHAR(20),
color CHAR(6),
weight SMALLINT,
city CHAR(15) ,
PRIMARY KEY ([p-no]) );

CREATE TABLE Shipments


( [s-no] CHAR(5) NOT NULL,
[p-no] CHAR(6) NOT NULL,
qty INTEGER ,
PRIMARY KEY ([s-no], [p-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 SUPPLIERS-AND-PARTS DATABASE DEFINITION


USING ACCESS
 Under the File drop-down, select New Database …

 A screen will appear with a database icon called "blank database"


mouseclick on the "OK" button.

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

 A form now appears labed with your database name followed by


the identified "Database". If our database was named testdb then
the form would have the title "testdb: Database".

 Create the Suppliers table by selecting the "Tables" tab and


mouseclicking the "new" button. On the "New Table" form, select
"Design View" and mouseclick "OK".

 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".

 Create the other tables in a similar manner.

23
SQL Notes

PLACING VALUES INTO THE DATABASE

OBJECTIVE

Insert the row "P1, Nut, Red, 12, London" into the parts
table.

USING THE CLASSICAL SQL STATEMENT

INSERT INTO parts ([p-no], pname, city, weight, color )


VALUES ( 'P1', 'Nut', 'London', 12, 'Red' );

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

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.

24
SQL Notes

PLACING VALUES INTO THE DATABASE


USING ACCESS

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.

 Continue until all values are entered into the table.

 Insert objects into the other tables in a similar manner.

25
SQL Notes

RETRIEVING DATA FROM THE DATABASE


-- INTERACTIVELY --

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' ;

RESULT RETURNED BY THE QUERY:

city
London

Note: "s-no" is placed in brackets as [s-no] to indicate to Access that


this is a single name and not "s minus no". S4 is placed in quotes to
indicate to Access that it is a character string.

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.

26
SQL Notes

RETRIEVING DATA FROM THE DATABASE


USING ACCESS

THIS WILL VARY DEPENDING UPON THE VERSION OF


MSACCESS. THE BEST PLACE TO GET A SENSE OF HOW
TO OPEN AND EXECUTE A QUERY IS TO SEARCH YTUBE
OR THE MICROSOFT SITE (WWW.MICROSOFT.COM)

27
SQL Notes

SQL FUNCTIONS

DATA DEFINITION FUNCTIONS

* CREATE TABLE
* CREATE VIEW
* CREATE INDEX

* DROP TABLE
* DROP VIEW
* DROP INDEX

28
SQL Notes

SQL FUNCTIONS
(CONTINUED)

DATA MANIPULATION FUNCTIONS

 SELECT -- Retrieves information from the database but


does not delete the information. It is a QUERY
function because it doesn't change the state of
the database.

 UPDATE -- Changes information in a one row in a


database table.

 DELETE -- Removes one row of information from a


database table.

 INSERT -- Inserts one row of information in a database


table.

29
SQL Notes

OBSERVATIONS ON SQL

 It is a "set-level language."

It operates on entire sets of records instead of just on one


record at a time.

 It is "non-procedural."

Unlike most programming languages, in SQL users specify


what data they want without specifying a procedure for
getting it.

30
SQL Notes

EXAMPLE OF SQL OPERATION


ON A DATA SET

OBJECTIVE

Select from the table shipments the supplier numbers, s-no,


where the part number, p-no, is equal to P2.

QUERY

SELECT [s-no]
FROM shipments
WHERE [p-no] = 'P2' ;

RESULT

s-no
S1
S2
S3
S4

Note: "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". P2 is placed in quotes to indicate to Access that it is a character
string.

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

1 The Relational Data Model

2 Data Definition

3 SQL Queries -- Data Manipulation

4 Miscellaneous Topics

 The System Catalog


 Views
 Security
 Recovery
 Bill-of-Materials Problem

32
SQL Notes

2. DATA DEFINITION

2.1 Base Tables

2.2 Indexes

33
SQL Notes

2.1 BASE TABLES

* This section is concerned with the "Data Definition


Language" (DDL) statements of SQL.

* The principal Data Definition Language statements are:

- CREATE TABLE
- CREATE VIEW
- CREATE INDEX
- ALTER TABLE
- DROP TABLE
- DROP VIEW
- DROP INDEX

Note: CREATE and DROP VIEW will not be discussed until


section 3.4 on Views.

34
SQL Notes

2.1 BASE TABLES


CONTINUED…

Base Tables are a special case of the general concept "table."

DEFINITION OF A "TABLE"

A "table" in a relational system consists of a row of


"column headings," together with zero or more rows of
"data values."

* The column heading row specifies one or more columns.

* Each data row contains exactly one data value for each
of the columns.

* All the values in a given column are of the same data


type.

35
SQL Notes

IMPORTANT POINTS TO NOTE

1. There is no mention of "row ordering."

The rows of a relational table are considered to be


unordered; thus, we can insert rows in any order and it
has no affect on the retrieval time.

2. In most systems, the columns are considered to be ordered


left to right although this is not part of the underlying theory.

In practice there are very few situations in which the left-


to-right ordering is important.

36
SQL Notes

DEFINITION OF A BASE TABLE

A base table is an "autonomous," "named" table.

AUTONOMOUS

The table exists in its own right and is not derived from one
or more base tables as a "view" table is.

NAMED

The table is explicitly given a name via an appropriate SQL


CREATE statement or through the table create procedure of
Access.

This differs from a table resulting from a SELECT query that


does not have a name of its own and has only a temporary
existence.

37
SQL Notes

CREATE TABLE STATEMENT

GENERAL SYNTAX

CREATE TABLE base-table-name ( column-definition, [, column-definition] ... );

Where a "column-definition" takes the form:

column-name data-type [NOT NULL]

NOTE
In a syntax definition, the square brackets, "[" and "]",
indicate the material enclosed within them is optional.

38
SQL Notes

EXAMPLE OF CREATING A TABLE

CREATE TABLE Suppliers

( [s-no] CHAR(5) NOT NULL,


sname CHAR(20),
status SMALLINT,
city CHAR(15) );

RESULT

Suppliers table
s-no sname status city

There are no entries in the database table so it exists but is an empty


table.

NOTE: "S-NO" IS PLACED IN BRACKETS AS [S-NO] TO INDICATE TO ACCESS


THAT THIS IS A SINGLE NAME AND NOT "S 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.

39
SQL Notes

RESULT OF THE STATEMENT

* A new, empty base table called suppliers is created.

* Entries describing the table are automatically made in


the system catalog.

* The table has four columns called s-no, sname, status,


and city with the indicated data types.

* Data can now be entered into the table via the SQL
INSERT statement.

40
SQL Notes

SQL DATA TYPES

SQL SUPPORTS THE FOLLOWING DATA TYPES:

INTEGER Signed fullword binary integer


(31 bits precision).

SMALLINT Signed halfword binary integer


(15 bits precision).

DECIMAL(p [,q ]) Signed packed decimal number of "p" digits


precision, with assumed decimal point "q" digits
from the right ("q" is assumed to be zero if
omitted).

FLOAT Signed doubleword floating point number.

CHAR(n) Fixed length character string of length "n"


characters.

VARCHAR(n) Varying length character string of maximum length


"n" characters.

Other data types are also commonly supported. Examples include:


BINARY, LOGICAL, MONEY, DATE, TIME, etc.

41
SQL Notes

DATA TYPES WITHIN MS ACCESS

Text (Default) Text or combinations of text and numbers, as


well as numbers that don't require calculations, such as
phone numbers. Limited to 255 characters.
Memo Use the Memo data type if you need to store more than
255 characters. A Memo field can store up to 64,000
characters. If you want to store formatted text or long
documents, you should create an OLE field instead of a
Memo field. However, the LIKE function will not work on
an OLE field.
Number Numeric data used in mathematical calculations.
Date/Time Date and time values for the years 100 through 9999.
Currency Currency values and numeric data used in mathematical
calculations involving data with one to four decimal
places.
AutoNumber A unique sequential (incremented by 1) number or
random number assigned by Microsoft Access whenever
a new record is added to a table.
Yes/No Yes and No values and fields that contain only one of
two values (True/False, On/Off).
OLE Object An object (such as a Microsoft Excel spreadsheet, a
Microsoft Word document, graphics, sounds, or other
binary data) linked to or embedded in a Microsoft
Access table. In essence, an OLE object is a file and is
Microsoft's equivalent to a BLOB, a binary large object,
which is used to store large objects in most other
relational databases. These objects are usually stored
in files on disk and not within the database, although,
this is not necessarily the case.
Hyperlink Text or combinations of text and numbers stored as text
and used as a hyperlink address.
Lookup Wizard... Creates a field that allows you to choose a value
from another table or from a list of values using a combo
box.

42
SQL Notes

DATA TYPES WITHIN MS ACCESS


(CONTINUED)

Numeric Data

When number is selected as a data type various properties become


available for selection under "Field Size". These include:

Byte Stores numbers from 0 to 255 (no fractions).

Integer Stores numbers from –32,768 to 32,767 (no fractions).

Long Integer (Default) Stores numbers from –2,147,483,648 to


2,147,483,647 (no fractions).

Single Stores numbers from –3.402823E38 to –1.401298E–


45 for negative values and from 1.401298E–45 to
3.402823E38 for positive values.

Double Stores numbers from –1.79769313486231E308 to


–4.94065645841247E–324 for negative values and
from 1.79769313486231E308 to
4.94065645841247E–324 or positive values.

Replication ID Globally unique identifier (GUID).

43
SQL Notes

NULL VALUES

WHAT IS A NULL VALUE?

* Null is a special value used to represent "value unknown" or


"value inapplicable."

* It is not the same as blank or zero.

44
SQL Notes

SQL AND NULL VALUES

 SQL supports the concept of a "null data value."

 Any column can contain null values unless the definition of


that column in the CREATE TABLE statement explicitly
specifics "NOT NULL."

 Within Access, any column can contain null values or no


values unless it is defined as a primary key.

45
SQL Notes

CAUTIONS ABOUT USING NULL VALUES

* Arithmetic expressions in which one of the


operands is null always evaluate to null.

* Comparison expressions in which one of the


comparands is null always evaluate to the
"unknown" truth value.

46
SQL Notes

ALTER TABLE STATEMENT

DESCRIPTION

The ALTER TABLE statement is used to alter an existing


base table by adding a new column.

GENERAL SYNTAX

ALTER TABLE base-table-name


ADD column-name data-type;

ALTER TABLE base-table-name


DROP column-name;

Where you can either add a column (ADD) or remove a column


(DROP) from a table.

47
SQL Notes

ALTER TABLE STATEMENT


-- AN EXAMPLE --

OBJECTIVE

A new column, discount, is added to the suppliers table. All existing


suppliers records are expanded from four fields to five with the value
of the new fifth field automatically set to null in every case.

SQL STATEMENT

ALTER TABLE suppliers


ADD discount NUMBER;

Where discount is the column to add and number is the data-type.


added column
Result
Suppliers table
s-no sname status city discount

SQL STATEMENT

ALTER TABLE suppliers


DROP discount ;

RESULT

Suppliers table
s-no sname status city

Column discount is removed from table supplier.

48
SQL Notes

ADDING A COLUMN WITHIN MS ACCESS


-- ALTERNATIVE APPROACH --

 Open the database table in the "design" view.


 Add a new column definition to the database table
definition.

49
SQL Notes

DROP TABLE STATEMENT

DESCRIPTION

The DROP TABLE statement is used to destroy an


existing base table.

GENERAL SYNTAX

DROP TABLE base-table-name ;

RESULT

The specified base table is removed from the system. All


indexes and views defined on that table are automatically
dropped also.

50
SQL Notes

REMOVING A DATABASE TABLE COLUMN


WITHIN MS ACCESS

 Open the database table in the "design" view.

 Highlight the column definition of the column you wish to delete.

 Press the "delete" key.

Note: All data in that column will be lost.

51
SQL Notes

2.2 INDEXES

WHAT IS AN INDEX?

An index is a way of organizing the data in a table to speed


up accessing it.

EXAMPLE

1. Index all employee records by the CPR number of the


employee, ordered by lowest number first.

2. Index all pending orders by supplier name, ordered


alphabetically.

52
SQL Notes

ADVANTAGES OF INDEXING

INDEXING SPEEDS UP:

* Direct access based on a given value for the indexed


field or field combination.

This avoids a sequential scan of the data


looking for one value.

* Sequential access based on the indexed field of field


combination.

This avoids the necessity of sorting data.

53
SQL Notes

DISADVANTAGES OF INDEXING

* Indexes take up space on the disk.

The space taken up by indexes can easily


exceed that taken up by the data itself in a
heavily indexed database.

* Indexes slow down update operations.

Any INSERT or DELETE on the indexed file or


UPDATE on the indexed field or field
combination will require an accompanying
update on the index.

54
SQL Notes

CREATE INDEX STATEMENT

DESCRIPTION

The CREATE INDEX statement is used to create an index on


a base table using one or more columns.

GENERAL SYNTAX

CREATE [ UNIQUE ] INDEX index-name


ON base-table-name
( column-name [ order ]
[, column-name [ order ] ] ... )
[ CLUSTER ] ;

55
SQL Notes

NOTES ON THE CREATE INDEX STATEMENT

1. The left-to-right sequence of naming columns corresponds


to major-to-minor ordering in the index.

2. "order" can be either ASC (ascending) or DESC


(descending). If neither is specified, then ASC is assumed by
default.

3. "CLUSTER" is an optional command specifying a cluster


index. This tells the DBMS to try and store records that are
logically related physically together.

4. The "UNIQUE" option specifies that no two records in the


indexed base table will be allowed to take on the same value
for the indexed field or combination of indexed fields.

56
SQL Notes

CREATE INDEX STATEMENT


-- AN EXAMPLE --

OBJECTIVE

Create an index called part-weight on the combination of


columns (p-no, weight, pname) in the base table parts. Index
weight in descending order.

SQL STATEMENT

CREATE INDEX part-weight ON parts ( p-no, weight DESC, pname ) ;

RESULT

An index called part-weight is created for the parts base


table. Entries in the index are ordered by ascending pname-
value within descending weight-value within ascending p-no-
value.

57
SQL Notes

CREATING AN INDEX WITHIN MS ACCESS

 Open the database table in "design" view.

 In table Design view, in the upper portion of the window,


click the field for which you want to create an index.

 In the lower portion of the window, click the Indexed property


box, and then select Yes (Duplicates OK) or Yes (No
Duplicates).

 Select the Yes (No Duplicates) option if you want to ensure


that no two records have the same data in this field.

58
SQL Notes

DROP INDEX STATEMENT

DESCRIPTION

The DROP INDEX statement is used to destroy an existing


index.

GENERAL SYNTAX

DROP INDEX index-name

RESULT

The specified index is destroyed by removing its description


from the system catalog.

59
SQL Notes

DROPPING AN INDEX WITHIN MS ACCESS

 Open the database table in "design" view.

 In table Design view, in the upper portion of the window,


click the field for which you want to drop the index.

 In the lower portion of the window, click the Indexed property


box, and then select No.

60
SQL Notes

SQL NOTES

1 The Relational Data Model

2 Data Definition

3 SQL Queries -- Data Manipulation

4 Miscellaneous Topics

 The System Catalog


 Views
 Security
 Recovery
 Bill-of-Materials Problem

61
SQL Notes

3. DATA MANIPULATION

3.1 Simple Queries


3.2 Relational Operators - UNION, INTERSECT
and EXCEPT
3.3 Relational Operators – JOINs
3.4 Built-in Functions
3.5 Nested Queries
3.6 Interesting Uses of Queries
3.7 Update Operations

62
SQL Notes

INTRODUCTION

SQL provides four Data Manipulation Language statements: SELECT,


UPDATE, DELETE, and INSERT.

These statements together with a group of "built-in functions" allow us


to manipulate existing tables by:

* Retrieving information
* Updating information
* Deleting existing rows
* Inserting new rows

63
SQL Notes

3.1 SIMPLE QUERIES

DEFINITION

A "simple query" is a query that uses the basic form of


the SELECT statement and references only a single
table.

64
SQL Notes

SELECT STATEMENT

DESCRIPTION

The SELECT statement is the basic statement used in all


queries. It always returns another table.

GENERAL SYNTAX

SELECT [ DISTINCT ] column-name(s) [AS label for display]

FROM table(s)

[ WHERE predicate ]

[ GROUP BY column-name(s)
[HAVING predicates ] ]

[ ORDER BY column-name(s) ] ;

When used to define syntax, brackets indicate commands that are


optional. Consequently, the basic SELECT statement with no optional
commands looks like the following.

SELECT column-name(s)
FROM table(s)

The WHERE statement places conditions on data retrievals and thus


essentially filters the data.

Note: The GROUP BY clause is discussed in section 3.3.3, Built-in


Functions.

65
SQL Notes

EXAMPLE OF A SIMPLE QUERY

OBJECTIVE

From the suppliers table, get the supplier numbers and status for
suppliers in Paris.

QUERY

SELECT [s-no], status


FROM suppliers
WHERE city = 'Paris' ;

RESULT
s-no status
S2 10
S3 30

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. In this example, without the brackets the SQL
parser would interpret s-no as the variable "no" subtracted from the
variable "s".

66
SQL Notes

QUALIFYING A COLUMN NAME WITH A TABLE NAME

"Qualified column names" allow you to explicitly


associate a table name with the column name, and are
useful in complex queries where items from several
tables are retrieved together.

QUERY

Get the supplier numbers and the part numbers for suppliers and for
parts from Paris.

SELECT suppliers.[s-no], parts.[p-no]


FROM suppliers, parts
WHERE suppliers.city = 'Paris'
AND parts.city = 'Paris';

Note: The qualifier is the table name appended to the front


of the column name.

RESULT
s-no p-no
S2 P2
S3 P2
S2 P5
S3 P5

Qualified field names prevent the query processor from becoming


confused.

67
SQL Notes

"DISTINCT" AND "DISTINCTROW" KEYWORDS

The DISTINCT keyword eliminates duplicates from the result of a


SELECT statement.

Microsoft Access also includes the DISTINCTROW keyword.


DISTINCTROW applies only to queries that reference more than one
table and applies to duplicate records. DISTINCT applies to duplicate
fields. Recall that a record corresponds to a row in a database table
where as a field corresponds to a specific column in a row.

The DISTINCT keyword applies to all columns listed in the SELECT


statement. It is not possible to restrict it to any one column unless
there is only one column in the SELECT statement.

68
SQL Notes

DISTINCT VS DISTINCTROW EXAMPLE

Database table: names


lastname firstname major degree
Jones Bill IE BS
Jones Mary IE MS
Smith Robert MAE BS

SELECT DISTINCTROW lastname, major FROM names;


will return the following because there are no duplicate rows in the
original database tables. Thus, the DISTINCTROW is used with
queries over two or more tables when it is quite possible that the
tables contain duplicate rows. In the example, there are no duplicate
rows in the original database table name so the query returns the
results below:

lastname major
Jones IE
Jones IE
Smith MAE

SELECT DISTINCT lastname, major FROM names;


will return the following because it eliminates duplicate rows from the
result:

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

EXAMPLE QUERY USING THE "DISTINCT" KEYWORD

QUERY

SELECT DISTINCT [p-no]


FROM shipments ;

RESULT

p-no
P1
P2
P3
P4
P5
P6

71
SQL Notes

THE "AS" KEYWORD


RENAMING COLUMNS THAT ARE RETRIEVED

The "AS" keyword is used with column names in the SELECT


statement to specify an alternative label for the results.

Query

SELECT [p-no] AS [part number], [s-no] AS [supplier no]


FROM Shipments;

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

ALSO SEE the section 3.3.5, Interesting Uses of Nested Queries.

72
SQL Notes

COMBINING RETRIEVED RESULTS INTO A SINGLE OUTPUT

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

The WHERE predicate is used to specify a row selection criteria. It


may include:

 The comparison operators =, <>, >, >=, <, and <=.


The symbol "<>" represents "not equal to" (i.e.,  )

 The Boolean operators AND, OR, XOR, EQV, and NOT.

 Ranges BETWEEN and NOT BETWEEN.

 IN and NOT IN operators.

 LIKE and NOT LIKE operators.

 Parentheses to indicate a desired order of evaluation.

Note: Often the symbols "~", "¬" or "!" are used to


represent negation and used in conjunction with =
to form ~=, which is read as not equal. The symbol
that is used depends upon the database vendor.

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

SELECT [s-no], [p-no], qty


FROM shipments
WHERE qty = 200;

RESULT

s-no p-no qty


S1 P2 200
S1 P4 200
S3 P2 200
S4 P2 200

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

SELECT [s-no], [p-no], qty


FROM shipments
WHERE qty <> 200;

RESULT

s-no p-no qty


S1 P1 300
S1 P3 400
S1 P5 100
S1 P6 100
S2 P1 300
S2 P2 400
S4 P4 300
S4 P5 400

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

SELECT [s-no], [p-no], qty


FROM shipments
WHERE qty > 200;

RESULT

s-no p-no qty


S1 P1 300
S1 P3 400
S2 P1 300
S2 P2 400
S4 P4 300
S4 P5 400

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

SELECT [s-no], [p-no], qty


FROM shipments
WHERE qty >= 200;

RESULT

s-no p-no qty


S1 P1 300
S1 P2 200
S1 P3 400
S1 P4 200
S2 P1 300
S2 P2 400
S3 P2 200
S4 P2 200
S4 P4 300
S4 P5 400

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

SELECT [s-no], [p-no], qty


FROM shipments
WHERE qty <= 200
AND ([p-no]="P2" OR [p-no]="P5");

In this query, we must use parentheses to group the various


conditions. From the objective we need a qualifier for quantity (qty)
AND we also need those parts whose numbers are either P2 or P5.
This means the resulting part numbers must be either P2 or P5 and
their quantity must be less than or equal to 200.

RESULT

s-no p-no qty


S1 P2 200
S1 P5 100
S3 P2 200
S4 P2 200

80
SQL Notes

BOOLEAN OPERATORS
AND, OR, XOR, EQV, NOT

Continuing the example, let us group the qualifiers differently. Instead


of
qty <= 200 AND ([p-no]="P2" OR [p-no]="P5")

let us group the qualifier as

(qty <= 200 AND [p-no]="P2") OR [p-no]="P5"

Note that the parentheses create a different grouping. So our query


now is

SELECT [s-no], [p-no], qty


FROM shipments
WHERE (qty <= 200 AND [p-no]="P2") OR [p-no]="P5";

RESULT

s-no p-no qty


S1 P2 200
S1 P5 100
S3 P2 200
S4 P2 200
S4 P5 400

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

BETWEEN AND NOT BETWEEN OPERATORS

These operators specify a range within which to search for values.


The range is inclusive.

SELECT [s-no], [p-no]


FROM shipments
WHERE qty BETWEEN 200 AND 300;

This query is identical to

SELECT [s-no], [p-no]


FROM shipments
WHERE qty >= 200 AND qty <= 300;

Result:

s-no p-no
S1 P1
S1 P2
S1 P4
S2 P1
S3 P2
S4 P2
S4 P4

Note that the range is inclusive.

82
SQL Notes

BETWEEN AND NOT BETWEEN OPERATORS

NOT BETWEEN EXAMPLES

In this example we retrieve the entries from the shipments table with a
quantity that is not between 200 and 300.

SELECT [s-no], [p-no], qty


FROM shipments
WHERE qty NOT BETWEEN 200 AND 300;

An alternative query that produces identical results is:

SELECT [s-no], [p-no], qty


FROM shipments
WHERE NOT (qty >= 200 AND qty <= 300);

RESULTS FROM BOTH QUERIES

s-no p-no qty


S1 P3 400
S1 P5 100
S1 P6 100
S2 P2 400
S4 P5 400

83
SQL Notes

IN AND NOT IN OPERATORS

The IN and NOT IN Operators allow the comparison of a single value


to a list of values.

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.

The query using the OR Boolean operator would be

SELECT [s-no], [p-no], qty


FROM shipments
WHERE [p-no]="P1" OR [p-no]="P2" OR [p-no]="P6";

The query using the IN operator would be

SELECT [s-no], [p-no], qty


FROM shipments
WHERE [p-no] IN ("P1", "P2", "P6");

84
SQL Notes

INCORRECT USE OF THE IN OPERATOR

Incorrect Query

SELECT sname
FROM suppliers
WHERE city, sname IN (“London”, “Smith, “Athens”, “Adams”);

This example is incorrect because it violates the requirement that a


single value be compared to a list of values. To work it needs to be
restated as follows.

Correct Query

SELECT sname
FROM suppliers
WHERE city IN (“London”, “Athens”)
AND sname IN (“Smith, “Adams”);

85
SQL Notes

IN AND NOT IN OPERATORS


EXAMPLES
1. Example using a logical operator

SELECT sname
FROM suppliers
WHERE city = "London" OR city = "Athens";

Result

sname
Smith
Clark
Adams

2. Example using the IN operator

SELECT sname
FROM suppliers
WHERE city IN ("London", "Athens");

Result
sname
Smith
Clark
Adams

86
SQL Notes

IN AND NOT IN OPERATORS


MORE EXAMPLES

3. Example of incorrect queries using more than a single value.

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”);

These two examples are incorrect because they violate the


requirement that a single value be compared to a list of values. To
work these need to be restated as follows.

SELECT sname
FROM suppliers
WHERE city IN (“London”, “Athens”)
AND sname IN (“Jones”, “Adams”);

Result:
sname
Adams

Be careful not to write the query as follows.

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

LIKE AND NOT LIKE OPERATORS


The LIKE and NOT LIKE Operators allow the comparison of two
character strings for a partial match. Partial matches are valuable if
you know a piece of the string you want to find but not its whole form.
They can be used to retrieve a table of items that have a partial string
match in one column.

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

MSAccess makes uses the wildcard characters from Visual Basic.

Character Usage Example


Matches any number of "wh*" finds what, white, and why
characters. It can be used
* as the first or last character
in the character string.
Matches any single "B?ll" finds ball, bell, and bill
? alphabetic character.
Matches any single "B[ae]ll" finds ball and bell but not
character within the bill
[] brackets.
Matches any character not "b[!ae]ll" finds bill and bull but not
! in the brackets. bell
Matches any one of a range "b[a-c]d" finds bad, bbd, and bcd
of characters. You must
- specify the range in
ascending order (A to Z, not
Z to A).
Matches any single numeric "1#3" finds 103, 113, 123
# character.

89
SQL Notes

LIKE AND NOT LIKE OPERATORS


-- EXAMPLES --

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

Get the names of suppliers that contain an "a".

SELECT sname
FROM suppliers
WHERE sname LIKE "*a*"; Note the use of the wildcard character * .

Results:
sname
Blake
Clark
Adams

Get the list of suppliers that do not contain an "a".

SELECT sname
FROM suppliers
WHERE sname NOT LIKE "*a*"; Note the use of the wildcard character *.

Results:
sname
Smith
Jones

90
SQL Notes

LIKE VERSUS = (I.E., EQUALITY)

The LIKE operators are intended for PARTIAL matches while


equality (i.e., = ) is used for exact matches.

• In general, they are NOT interchangeable.

• Wildcard characters don't work with equality (=) because the


SQL engine interprets the characters within parentheses as a
character string whereas LIKE recognizes the wildcard
characters.

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

LIKE VERSUS = (I.E., EQUALITY)


-- EXAMPLES --

Get the names of parts from the Parts table that begin with "c".

Using the LIKE operator

SELECT pname
FROM parts
WHERE pname LIKE "c*"; Note the use of the wildcard character * .

Results: pname
Cam
Cog

Using equality (=) operator

SELECT pname
FROM parts
WHERE pname = "c*";

pname

The equality operator couldn't locate any entries


because it didn't recognize the wildcard character
"*". Instead, it interpreted "c*" as a character
string of two characters, a "c" and a "*".

92
SQL Notes

ORDER BY CLAUSE
RETRIEVAL WITH ORDERING

DESCRIPTION

The ORDER BY clause is placed after the WHERE condition to


specify the way results are to be organized before being displayed. If
there is no WHERE condition then the ORDER BY clause is placed at
the end of the SELECT statement.

GENERAL SYNTAX

ORDER BY column-name [ ASC or DESC ]


[, column-name [ASC or DESC ] ] ...

The column-names must also be specified as one of the column-


names to be retrieved by the SELECT statement. The results will be
organized in a nested fashion in the order listed in the ORDER BY
clause but will be presented left to right in the sequence the columns
are listed in the SELECT part of the query statement.

Note: ASC (ascending) or DESC (descending) can be


specified. If neither is specified, then ASC is
assumed by default.

93
SQL Notes

RETRIEVAL WITH ORDERING


-- EXAMPLE 1--

OBJECTIVE

Retrieve the part number (p-no) and quantity (qty) from the shipments
table ordered by ascending quantity (qty).

QUERY

SELECT [p-no], qty


FROM shipments
WHERE [s-no] = "s1"
ORDER BY qty ASC;

RESULT

p-no qty

P6 100

P5 100

P4 200

P2 200

P1 300

P3 400

Notice the result is organized by ascending quantity (qty) as specified


by the ORDER BY clause.

94
SQL Notes

RETRIEVAL WITH NESTED ORDERING


-- EXAMPLE 2 --

OBJECTIVE

Retrieve the part number, p-no, weight and color from the parts table
ordered by descending weight and by ascending color.

QUERY

SELECT [p-no], weight, color


FROM parts
ORDER BY weight DESC, color ASC ;

Since there is not a WHERE condition the ORDER BY clause is


placed immediately after the FROM table specification.

RESULT
p-no weight color
P6 19 Red
P3 17 Blue
P2 17 Green
P4 14 Red
P5 12 Blue
P1 12 Red

Notice the result is organized by descending weight and then within


each weight group, by ascending color. Since the returned colors are
alphabetic characters, ascending order is alphabetical order.
Consequently, the ORDER BY clause creates a nested ordering.

95
SQL Notes

RETRIEVAL WITH ORDERING OF DATA PRODUCED BY


BUILT-IN FUNCTIONS (AGGREGATE FUNCTIONS)
-- EXAMPLE 3 –

Objective

Determine the average quantity shipped by suppliers organized in


descending order. Here the average quantity is computed using a
Built-in Function also called an Aggregate Function.

Query

SELECT [s-no], avg(qty) AS [avg qty]


FROM shipments
GROUP BY [s-no]
ORDER BY avg(qty) DESC;

Note that avg(qty) is used and NOT [avg qty].


Using a new column name produces an error, you must use the aggregate operator.
Aggregate operators are Built-in Functions and are discussed in Section 3.3.4

Since there is not a WHERE condition the ORDER BY clause is


placed immediately after the GROUP BY operator specification.

The GROUP BY operator is discussed in Section 3.3.4.

Results
s-no avg qty
S2 350.00
S4 300.00
S1 216.67
S3 200.00

96
SQL Notes

ARITHMETIC EXPRESSIONS IN A QUERY RETRIEVAL

In general, the items in the SELECT clause can be arbitrary


expressions, involving column names and/or constants and/or
functions combined together by means of the usual arithmetic
operators ( +, -, *, /, ^ ), with optional parentheses to indicate a desired
order of evaluation.

 Column names – The name of any column in the database


tables.

 Constants – Any numerical value that is an integer or a real


number.

 Functions – Any function as defined in Section 3.3.4, Built-in


Functions.

Note: +, -, *, /, ^ are addition (+), subtraction (-), multiplication (*),


division (/), and exponentiation (^).

97
SQL Notes

ARITHMETIC EXPRESSIONS IN A QUERY RETRIEVAL


-- EXAMPLE USING A CONSTANT --

OBJECTIVE

Retrieve the part number, p-no, and the weight of the


part in kilograms (part weights are given in pounds in
table parts).

QUERY

SELECT [p-no], 'Weight in Kilograms = ', weight * .454


FROM parts ;

RESULTS

p-no Expr1001 Expr1002


P1 Weight in Kilograms = 5.448
P2 Weight in Kilograms = 7.718
P3 Weight in Kilograms = 7.718
P4 Weight in Kilograms = 6.356
P5 Weight in Kilograms = 5.448
P6 Weight in Kilograms = 8.626

Note that the column names "Expr1001" and "Expr1002" are


generated by MSAccess because we didn't provide column names
using the AS operator.

98
SQL Notes

ARITHMETIC EXPRESSIONS IN A QUERY RETRIEVAL


-- EXAMPLE (CONTINUED) --

QUERY

SELECT [p-no], weight * .454 AS [Weight in Kilograms]


FROM parts ;

RESULTS

p-no Weight in Kilograms


P1 5.448
P2 7.718
P3 7.718
P4 6.356
P5 5.448
P6 8.626

99
SQL Notes

ARITHMETIC EXPRESSIONS AND FUNCTIONS IN A QUERY


RETRIEVAL

Objective

Determine the total weight shipped of each part number in the


supplier-Parts database.

Query

SELECT shipments.[p-no], SUM(parts.weight * shipments.qty) AS [total qty shipped]


FROM shipments, parts
WHERE shipments.[p-no]=parts.[p-no]
GROUP BY shipments.[p-no];

Result

p-no total qty shipped


P1 7200
P2 17000
P3 6800
P4 7000
P5 6000
P6 1900

• 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

3.1 Simple Queries

3.2 Relational Operators - UNION, INTERSECT and EXCEPT

3.3 Relational Operators – JOINs

3.4 Built-in Functions

3.5 Nested Queries

3.6 Interesting Uses of Queries

3.7 Update Operations

101
SQL Notes

3.2 RELATIONAL OPERATORS


-- UNION, INTERSECT AND EXCEPT --

The UNION, INTERSECT and EXCEPT operators combine data from


more than one table. The UNION and INTERSECT operators perform
identically to the union and intersect operators in set operations. They
only operate on two source tables. The UNION operator produces the
cross product of two tables, producing all rows that exist in either
table. The INTERSECT operator produces a table of rows that exist in
both tables, eliminating rows that exist in one or the other table but not
in both. The EXCEPT operator is essentially the first table minus the
intersection of the two tables in that it produces a table of rows from
the first table that do not appear in the second table.

Notes:

1. The UNION operator is not the same as the UNION JOIN operator.

2. The INTERSECT and EXCEPT operators are not supported by


MSAccess.

3. INTERSECT operator results can be achieved using NESTED


queries (Section 3.3.5).

102
SQL Notes

UNION OPERATOR

 The tables to be included in a UNION operator must have the same


number of columns and the corresponding columns must have
identical data types and lengths.

 Most often these tables are created by SELECT queries.

 The Union of two tables produces a table of all rows that appear in
either table.

Syntax

table1 UNION [CORRESPONDING (column1, column2, …) | ALL]


table2

Alternatively:

(SELECT … ) UNION [CORRESPONDING (column1, column2,


…) | ALL] (SELECT … )

The CORRESPONDING and ALL keywords are optional.

The column names come from the FIRST query or table

Duplicate elimination problem

By default, duplicate rows are eliminated from the resulting table. If


you use ALL, duplicates are retained in the resulting table. If you use
CORRESPONDING and its list of columns, only the columns listed are
considered in the UNION operation. Consequently, these columns
must exist in both tables and have matching data types and lengths.

Note: The CORRESPONDING keyword is not available in MSAccess.

103
SQL Notes

UNION OPERATOR -- EXAMPLES

Produce a list of all cities for suppliers or parts.

Cities from the Suppliers table -- SELECT suppliers.city FROM suppliers

city
London
Paris
Paris
London
Athens

Cities from the Parts table -- SELECT parts.city FROM parts

city
London
Paris
Rome
London
Paris
London

Note the duplicates in each table.

104
SQL Notes

We use the UNION operator to produce a list of all cities for suppliers
or parts.

(SELECT suppliers.city FROM suppliers)


UNION
(SELECT parts.city FROM parts);

Result:
city
Athens
London
Paris
Rome

NOTE THAT ALL DUPLICATES ARE REMOVED!!

To include all duplicates we use the ALL keyword.

(SELECT suppliers.city FROM suppliers)


UNION ALL
(SELECT parts.city FROM parts);

city
London
Paris
Paris
London
Athens
London
Paris
Rome
London
Paris
London
Athens
Athens

105
SQL Notes

3.3 DATA MANIPULATION

3.1 Simple Queries

3.2 Relational Operators - UNION, INTERSECT and EXCEPT

3.3 Relational Operators – JOINs

3.4 Built-in Functions

3.5 Nested Queries

3.6 Interesting Uses of Queries

3.7 Update Operations

106
SQL Notes

3.3 RELATIONAL OPERATORS


-- JOINS --

DEFINITION

A "join" is a query in which data is retrieved from more than one table
and thus "joins" information from those tables.

NOTES

The ability to "join" together two or more tables to produce a single


result table is one of the most powerful features of relational systems,
and the single most important thing that distinguishes them from
non-relational systems.

MSAccess only supports the INNER JOIN, LEFT JOIN, and RIGHT
JOIN.

107
SQL Notes

EQUI-JOIN QUERY

An equi-join query is a basic join with a WHERE clause containing a


condition specifying that the value in one column in the first table must
be equal to the value of a corresponding column in the second table.

OBJECTIVE

Get all combinations of supplier and part information such that the
supplier and part in question are located in the same city.

QUERY

SELECT suppliers.*, parts.*


FROM suppliers, parts
WHERE suppliers.city = parts.city ;

Note: The star or asterisk, *, is shorthand for a list of all


field names in the table(s) named in the FROM
clause, in the order in which those fields are defined
in the CREATE TABLE statement.

108
SQL Notes

EQUI-JOIN QUERY
(CONTINUED)

RESULT

S-no Sname Status suppliers.City P-no PName Color Weight parts.City

S1 Smith 20 London P6 Cog Red 19 London

S1 Smith 20 London P4 Screw Red 14 London

S1 Smith 20 London P1 Nut Red 12 London

S2 Jones 10 Paris P5 Cam Blue 12 Paris

S2 Jones 10 Paris P2 Bolt Green 17 Paris

S3 Blake 30 Paris P5 Cam Blue 12 Paris

S3 Blake 30 Paris P2 Bolt Green 17 Paris

S4 Clark 20 London P6 Cog Red 19 London

S4 Clark 20 London P4 Screw Red 14 London

S4 Clark 20 London P1 Nut Red 12 London

109
SQL Notes

GREATER-THAN JOIN QUERY

Similar to an equi-join except the equality comparison operator is


replaced by an inequality operator (i.e., "<", ">", "<=", ">=" )

OBJECTIVE

Get all supplier-number / part-number / weight combinations of


supplier information and part information where the supplier and part
concerned are located in the same city, but where the part weight is
greater than 14.

QUERY

SELECT suppliers.[s-no], parts.[p-no], parts.weight


FROM suppliers, parts
WHERE suppliers.city = parts.city
AND parts.weight > 14 ;

RESULT

s-no p-no weight


S3 P2 17
S2 P2 17
S4 P6 19
S1 P6 19

110
SQL Notes

MULTI-TABLE JOIN QUERY

OBJECTIVE

Find the supplier's city and the part's city for supplier and part entries
in the shipments table.

Query

SELECT DISTINCT suppliers.city, parts.city


FROM suppliers, shipments, parts
WHERE suppliers.[s-no] = shipments.[s-no]
AND shipments.[p-no] = parts.[p-no] ;

Result

suppliers.city parts.city
London London
London Paris
London Rome
Paris London
Paris Paris

111
SQL Notes

JOIN EXPRESSIONS

Within a JOIN expression, the WHERE clause is replaced with one of


the following JOIN expressions:

JOIN (not supported by MSAccess)


CROSS JOIN (not supported by MSAccess)
NATURAL JOIN (not supported by MSAccess)
UNION JOIN (not supported by MSAccess)
INNER JOIN -- left, right or full
OUTER JOIN -- left, right or full

In general the JOIN expressions have equivalent expressions in


standard SQL.

Note: MSAccess only supports the INNER JOIN, LEFT JOIN, and
RIGHT JOIN.

112
SQL Notes

JOIN
(NOT SUPPORTED BY MSACCESS)

This operation is identical to the equi-join discussed earlier but uses a


JOIN expression syntax.

SELECT *
FROM parts JOIN suppliers USING (city);

This is identical to the previous syntax for an equi-join:

SELECT suppliers.*, parts.*


FROM parts, suppliers
WHERE suppliers.city=parts.city;

and returns the same results.

Unfortunately, this operator is not available in MSAccess.

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;

Unfortunately, this operator is not available in MSAccess.

Alternatively, using standard SQL we can achieve the same results

SELECT * FROM parts, suppliers;

RESULTS

p-no pname color weight parts.city s-no sname status suppliers.city


P1 Nut Red 12 London S1 Smith 20 London
P1 Nut Red 12 London S2 Jones 10 Paris
P1 Nut Red 12 London S3 Blake 30 Paris
P1 Nut Red 12 London S4 Clark 20 London
P1 Nut Red 12 London S5 Adams 30 Athens
P2 Bolt green 17 Paris S1 Smith 20 London
P2 Bolt green 17 Paris S2 Jones 10 Paris
P2 Bolt green 17 Paris S3 Blake 30 Paris
P2 Bolt green 17 Paris S4 Clark 20 London
P2 Bolt green 17 Paris S5 Adams 30 Athens
P3 Screw Blue 17 Rome S1 Smith 20 London
P3 Screw Blue 17 Rome S2 Jones 10 Paris
P3 Screw Blue 17 Rome S3 Blake 30 Paris
P3 Screw Blue 17 Rome S4 Clark 20 London
P3 Screw Blue 17 Rome S5 Adams 30 Athens
P4 Screw Red 14 London S1 Smith 20 London
P4 Screw Red 14 London S2 Jones 10 Paris
P4 Screw Red 14 London S3 Blake 30 Paris
P4 Screw Red 14 London S4 Clark 20 London
P4 Screw Red 14 London S5 Adams 30 Athens
P5 Cam Blue 12 Paris S1 Smith 20 London
P5 Cam Blue 12 Paris S2 Jones 10 Paris
P5 Cam Blue 12 Paris S3 Blake 30 Paris
P5 Cam Blue 12 Paris S4 Clark 20 London
P5 Cam Blue 12 Paris S5 Adams 30 Athens
P6 Cog Red 19 London S1 Smith 20 London
P6 Cog Red 19 London S2 Jones 10 Paris
P6 Cog Red 19 London S3 Blake 30 Paris
P6 Cog Red 19 London S4 Clark 20 London
P6 Cog Red 19 London S5 Adams 30 Athens

114
SQL Notes

NATURAL JOIN
(NOT SUPPORTED BY MSACCESS)

The NATURAL JOIN is a special case of an equi-join. In the previous


example of an equi-join, within the WHERE clause a column from one
table is compared with a column from another table using equality.
However, in the equi-join the columns must be of the same data type
and contain the same number of rows. The NATURAL JOIN has the
same requirement but also requires that the columns have the same
name.

SELECT *
FROM suppliers NATURAL JOIN parts;

This returns the same results as the equi-join example.

Unfortunately, this operator is not available in MSAccess.

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.

Unfortunately, this operator is not available in MSAccess.

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.

LEFT OUTER JOIN

The LEFT OUTER JOIN preserves all unmatched rows from the LEFT
table while discarding unmatched rows from the RIGHT table.

RIGHT OUTER JOIN

The RIGHT OUTER JOIN preserves all unmatched rows from the
RIGHT table while discarding unmatched rows from the LEFT table.

FULL OUTER JOIN (not supported by MSAccess)

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

LEFT & RIGHT OUTER JOIN

Syntax

SELECT [list of columns]

FROM table1 [ LEFT | RIGHT ] JOIN table 2

ON table1.column_i operator table2.column_j

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

LEFT OUTER JOIN EXAMPLE

SELECT suppliers.*, parts.*


FROM parts LEFT JOIN suppliers ON parts.city = suppliers.city;

Result:

s-no sname status suppliers.city p-no pname color weight parts.city


S4 Clark 20 London P1 Nut Red 12 London
S1 Smith 20 London P1 Nut Red 12 London
S3 Blake 30 Paris P2 Bolt green 17 Paris
S2 Jones 10 Paris P2 Bolt green 17 Paris
P3 Screw Blue 17 Rome
S4 Clark 20 London P4 Screw Red 14 London
S1 Smith 20 London P4 Screw Red 14 London
S3 Blake 30 Paris P5 Cam Blue 12 Paris
S2 Jones 10 Paris P5 Cam Blue 12 Paris
S4 Clark 20 London P6 Cog Red 19 London
S1 Smith 20 London P6 Cog Red 19 London

119
SQL Notes

LEFT OUTER JOIN EXAMPLE


(CONTINUED)

To order the results by S-no, we add the ORDER BY clause.

SELECT suppliers.*, parts.*


FROM parts LEFT JOIN suppliers ON parts.city = suppliers.city
ORDER BY [s-no];

Result:

s-no sname status suppliers.city p-no pname color weight parts.city

P3 Screw Blue 17 Rome


S1 Smith 20 London P6 Cog Red 19 London

S1 Smith 20 London P4 Screw Red 14 London

S1 Smith 20 London P1 Nut Red 12 London


S2 Jones 10 Paris P5 Cam Blue 12 Paris
S2 Jones 10 Paris P2 Bolt green 17 Paris

S3 Blake 30 Paris P5 Cam Blue 12 Paris


S3 Blake 30 Paris P2 Bolt green 17 Paris

S4 Clark 20 London P6 Cog Red 19 London

S4 Clark 20 London P4 Screw Red 14 London


S4 Clark 20 London P1 Nut Red 12 London

120
SQL Notes

RIGHT OUTER JOIN EXAMPLE

SELECT suppliers.*, parts.*


FROM parts RIGHT JOIN suppliers ON parts.city = suppliers.city;

Result:

s-no sname status suppliers.city p-no pname color weight parts.city


S1 Smith 20 London P6 Cog Red 19 London
S1 Smith 20 London P4 Screw Red 14 London
S1 Smith 20 London P1 Nut Red 12 London
S2 Jones 10 Paris P5 Cam Blue 12 Paris
S2 Jones 10 Paris P2 Bolt gree 17 Paris
n
S3 Blake 30 Paris P5 Cam Blue 12 Paris
S3 Blake 30 Paris P2 Bolt gree 17 Paris
n
S4 Clark 20 London P6 Cog Red 19 London
S4 Clark 20 London P4 Screw Red 14 London
S4 Clark 20 London P1 Nut Red 12 London
S5 Adams 30 Athens

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

SELECT [list of columns]

FROM table1 INNER JOIN table 2

ON table1.column_i operator table2.column_j

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

INNER JOIN EXAMPLE

SELECT suppliers.*, parts.*


FROM parts INNER JOIN suppliers ON parts.city = suppliers.city;

Result:

s-no sname status suppliers.city p-no pname color weight parts.city

S1 Smith 20 London P6 Cog Red 19 London


S1 Smith 20 London P4 Screw Red 14 London

S1 Smith 20 London P1 Nut Red 12 London

S2 Jones 10 Paris P5 Cam Blue 12 Paris


S2 Jones 10 Paris P2 Bolt green 17 Paris
S3 Blake 30 Paris P5 Cam Blue 12 Paris
S3 Blake 30 Paris P2 Bolt green 17 Paris

S4 Clark 20 London P6 Cog Red 19 London

S4 Clark 20 London P4 Screw Red 14 London

S4 Clark 20 London P1 Nut Red 12 London

123
SQL Notes

ON VERSUS WHERE CLAUSES IN JOINS

 The ON clause is part of the INNER, LEFT and RIGHT JOINS.

 The ON clause in an INNER JOIN is logically equivalent to a


WHERE clause. The same condition could be specified using
either an ON or a WHERE clause.

 The ON clause in either a LEFT or a RIGHT JOIN is different from


the WHERE clause. The ON clause first filters the rows of a cross
product between the tables being joined and then includes the
rejected rows extended with null values. The WHERE clause filters
the rows that are returned by the FROM clause. The rejected rows
are not included in the resulting table.

124
SQL Notes

MAXIMUM NUMBER OF TABLES


THAT CAN BE JOINED

Although theoretically there is no limit on the number of tables that can


be joined together, in practice each implementation is limited by the
resources available to process the join. Consequently, check before
making very large joins to ensure the system's limits are not
exceeded.

125
SQL Notes

ALIASES FOR TABLE NAMES IN JOIN QUERIES

In complex queries involving multiple tables or correlated subqueries,


it can be confusing to use the long table names. Aliases allow us to
rename tables for use within a query.

Syntax

SELECT …

FROM table1 AS alias for table1, table2 AS alias for table2, …

WHERE …

Example

Write a query to determine the supplier numbers for suppliers shipping


at least one part using with quantity equal to 200.

SELECT t1.[s-no], t1.[p-no], t1.[qty]


FROM shipment AS t1, shipments AS t1
WHERE t1.[p-no]=t2.[p-no]
AND t2.[qty]>200;

Get all unique pairs of part numbers that have the same quantity
shipped. Show the part number pairs, the supplier number and
quantity.

SELECT x.[p-no], y.[p-no], x.[s-no], x.qty


FROM shipments AS x, shipments AS y
WHERE x.[p-no] <>y.[p-no] AND x.qty = y.qty;

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:

x.p-no y.p-no s-no qty


P4 P1 S4 300
P4 P2 S1 200
P5 P3 S4 400
P2 P3 S2 400
P2 P4 S3 200
P2 P4 S4 200
P2 P4 S1 200
P6 P5 S1 100
P5 P6 S1 100
P4 P1 S4 300
P5 P2 S4 400
P3 P2 S1 400
P4 P2 S1 200
P1 P4 S2 300
P1 P4 S1 300
P4 P2 S1 200
P2 P5 S2 400
P3 P5 S1 400

127
SQL Notes

3. DATA MANIPULATION

3.1 Simple Queries

3.2 Relational Operators - UNION, INTERSECT and EXCEPT

3.3 Relational Operators – JOINs

3.4 Built-in Functions

3.5 Nested Queries

3.6 Interesting Uses of Queries

3.7 Update Operations

128
SQL Notes

3.4 BUILT-IN FUNCTIONS OR AGGREGATE FUNCTIONS

 SQL provides a number of special "built-in functions" or


"aggregate functions" to enhance its basic retrieval power.

 The functions are: COUNT, SUM, AVG, MAX, MIN, STDEV and
VAR, as well as STDEVP and VARP.

 The functions operate on the collection of values returned by


the query to produce a single value as a result.

 The collection of values may be organized into subgroups by


the GROUP BY operator in which case the functions operate
on the collection of values in each subgroup.

129
SQL Notes

DEFINITION OF THE FUNCTIONS

COUNT - The number of entries in the column.

SUM - The sum of the values in the column.

AVG - The Average of the values in the column.

MAX - The largest value in the column.

MIN - The smallest value in the column.

STDEV - The standard deviation of the sample. This is


the adjusted standard deviation to produce an
unbiased estimator.

STDEVP - The standard deviation of the population.

VAR - The variance of the sample. This is


the adjusted variance to produce an
unbiased estimator.

VARP - The variance of the population.

130
SQL Notes

NOTES ABOUT FUNCTIONS

1. For SUM, AVG, STDEV and VAR the column must contain numeric
values.

2. The argument of the function may optionally be preceded by the


keyword DISTINCT except in MS Access where this is not allowed.

3. For COUNT, DISTINCT should not be specified because it is not


processed.

4. To count all rows in a column, including duplicates and null values,


COUNT(*) -- DISTINCT not allowed here -- is provided. However, a
null value is different than something which does not exist so be
careful when using COUNT in a multi-table query.

However, it is possible to work around this by first using the


UPDATE SQL statement to change the null value to something else
such as zero. See the UPDATE SQL statement examples in
Section 3.3.7.

5. Any null values in the column are not processed by the functions,
except in the case of COUNT(*).

6. The STDEV, STDEVP, VAR, VARP functions produce a NULL


value if the result from the underlying query contains fewer than two
records.

131
SQL Notes

FUNCTIONS IN THE SELECT STATEMENT


-- EXAMPLE 1 --

OBJECTIVE

Get the total number of suppliers.

QUERY

SELECT COUNT([s-no])
FROM suppliers ;

RESULT
5

132
SQL Notes

FUNCTIONS IN THE SELECT STATEMENT


-- EXAMPLE 2 --

OBJECTIVE

Get the total number of unique suppliers currently


supplying parts.

QUERY

SELECT COUNT (DISTINCT[s-no])


FROM shipments ;

RESULT
4

Note: This statement will not execute in MS Access. Writing an


equivalent SQL statement in MS Access is not possible.

However, in Access2000 or AccessXP the following NESTED query


will produce the same result

SELECT COUNT( [s-no])


FROM (SELECT DISTINCT [s-no] FROM shipments);

This query works because a query always returns a database table


that can be operated on using another query. The nested query
returns a table of the distinct items in the shipments table. The outer
query counts the distinct items in the table returned by the nested
query.

133
SQL Notes

FUNCTIONS IN THE SELECT STATEMENT


-- EXAMPLE 3 --

OBJECTIVE

Get the number of shipments for supplier S5.

QUERY

SELECT COUNT([s-no])
FROM shipments
WHERE [s-no]="S5";

RESULT
0

Since there are no shipments for supplier S5 the COUNT function


returns a zero value.

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

FUNCTIONS IN THE SELECT STATEMENT


-- EXAMPLE 4 --

OBJECTIVE

Get the total quantity of part P2 supplied.

QUERY

SELECT SUM (qty)


FROM shipments
WHERE [p-no] = 'P2' ;

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.

Groups within Groups

Organizing results by grouping within groups is possible using the GROUP BY


operator. This is accomplished by listing several columns separated by a comma.
The left to right column order determines the major to minor organization of the
grouping within groups.

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
 

Note: GROUP BY doesn't imply ORDER BY. If a result is


needed in a specific order then the ORDER BY
clause should be added.

136
SQL Notes

EXAMPLE OF THE GROUP BY OPERATOR

OBJECTIVE

For each part supplied, get the part number and the total
shipment quantity for that part.

QUERY

SELECT [p-no], SUM(qty) AS [total quantity]


FROM shipments
GROUP BY [p-no] ;

RESULT

p-no total quantity


P1 600
P2 1000
P3 400
P4 500
P5 500
P6 100

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

EXAMPLE OF THE GROUP BY OPERATOR


-- (CONTINUED) --

Get the supplier number and the total quantity they are shipping.

QUERY

SELECT [s-no], SUM(qty) AS [total quantity]


FROM shipments
GROUP BY [s-no];

RESULT

s-no total quantity


S1 1300
S2 700
S3 200
S4 900

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

GROUPS WITHIN GROUPS


USING THE GROUP BY OPERATOR

In this example, we will generate a nested list organized by one major


grouping and then organized within each item in the major grouping.

We want to get the part numbers and quantities shipped by each


supplier. The suppliers will be the major grouping and within each
supplier the parts will be grouped with their quantities.

QUERY

SELECT [s-no], [p-no], qty


FROM shipments
GROUP BY [s-no], [p-no], qty;

RESULT

s-no p-no qty


S1 P1 300
S1 P2 200
S1 P3 400
S1 P4 200
S1 P5 100
S1 P6 100
S2 P1 300
S2 P2 400
S3 P2 200
S4 P2 200
S4 P4 300
S4 P5 400

139
SQL Notes

HAVING CLAUSE

The HAVING clause is used only with the GROUP BY operator.

GENERAL SYNTAX

SELECT [ DISTINCT ] column-name(s) [AS label for display]

FROM table(s)

[ WHERE predicate ]

[ GROUP BY column-name(s)
[HAVING predicates ] ]

[ ORDER BY column-name(s) ] ;

The HAVING clause is a filter that places a further restriction on the


table a GROUP BY clause creates. Just as a WHERE clause
removes unwanted individual rows in a query by operating on the raw
data within the tables specified, a HAVING clause removes unwanted
groups. As such, the HAVING clause operates on the results of the
query deleting groups that do not meet the conditions.

140
SQL Notes

EXAMPLE OF THE HAVING CLAUSE WITH THE GROUP


BY OPERATOR

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

SELECT [p-no], SUM(qty) AS Totals


FROM shipments
GROUP BY [p-no]
HAVING [p-no] = 'P3' OR [p-no] = 'P4';

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

3.1 Simple Queries

3.2 Relational Operators - UNION, INTERSECT and EXCEPT

3.3 Relational Operators – JOINs

3.4 Built-in Functions

3.5 Nested Queries

3.6 Interesting Uses of Queries

3.7 Update Operations

142
SQL Notes

3.5 NESTED QUERIES

DEFINITION

A nested query is a SELECT - FROM - WHERE


expression that is "nested" or embedded inside another
such expression.

A nested query is a subquery that is located within the


WHERE clause of a SELECT statement. The subquery
sets the conditions for the WHERE clause. The
conditions are defined by various operators.

IN, NOT IN -- non-correlated subquerie


EXISTS, NOT EXISTS -- correlated subqueries
=, <, >, <=, >=, <> -- non-correlated subquerie
ANY, SOME, ALL -- non-correlated subqueries

Note: non-correlated subqueries can be made correlated by using an


explicit reference in the subquery to a table that exists within the outer
query.

143
SQL Notes

IN AND NOT IN
NESTED QUERY OPERATORS

IN operator

The IN operator is used to compare a single value to a list returned by


a subquery. If the single value is in the list returned by the subquery,
then the WHERE clause returns a true value and the specified
columns from the table's row that is being processed are added to the
result table.

NOT IN operator

The NOT IN operator is the negation of the IN operator. It too


compares a single value to a list returned by a subquery. If the single
value is not in the list returned by the subquery, then the WHERE
clause returns a true value and the specified columns from the table's
row that is being processed are added to the result table

Note: The subquery may reference the same table as referenced by


the outer query, or it may reference a difference table.

144
SQL Notes

IN AND NOT IN EXAMPLE

Find the part numbers of parts in the shipments table that originate in Paris.

SELECT DISTINCT shipments.[p-no]


FROM shipments
WHERE shipments.[s-no] IN ( SELECT suppliers.[s-no]
FROM suppliers
WHERE suppliers.city = 'Paris');

RESULT
p-no
P1
P2

Find the part numbers of parts in the shipments table that do not originate in Paris.

SELECT DISTINCT shipments.[p-no]


FROM shipments
WHERE [s-no] NOT IN ( SELECT suppliers.[s-no]
FROM suppliers
WHERE suppliers.city = 'Paris');
Result
p-no
P1
P2
P3
P4
P5
P6

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 AND NOT EXISTS


NESTED QUERY OPERATORS

These operators are existence tests on the nested subquery. They


are correlated subqueries because the outer query executes first and
locates a row it specifies. This is then followed by execution of the
nested subquery. The success or failure of the nested subquery
determines whether or not to keep the row returned by the outer
query.

EXISTS operator

The EXISTS operator is used to compare a single value to the


success of a nested subquery. If the nested subquery succeeds in
returning at least one row then the EXISTS predicate succeeds. The
success of the EXISTS predicate causes the WHERE clause to return
a true value and the specified columns from the row being processed
in the outer query are added to the result table.

NOT EXISTS operator

The NOT EXISTS operator is used to compare a single value to the


failure of a nested subquery. If the nested subquery fails to return at
least one row then the NOT EXISTS predicate succeeds. The
success of the NOT EXISTS predicate causes the WHERE clause to
return a true value and the specified columns from the row being
processed in the outer query are added to the result table.

Note: The nested subquery may reference the same table as


referenced by the outer query, or it may reference a difference table.

146
SQL Notes

EXISTS AND NOT EXISTS EXAMPLE

Find the part numbers of parts in the shipments table if any supplier originates in
Paris.

SELECT DISTINCT shipments.[p-no]


FROM shipments
WHERE EXISTS ( SELECT suppliers.[s-no]
FROM suppliers
WHERE suppliers.city = '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

EXISTS AND NOT EXISTS EXAMPLE


-- CONTINUED … --

Find the part numbers of parts in the shipments table where the supplier
originates in Paris.

Notice this is a slightly different question than the previous example.

SELECT DISTINCT shipments.[p-no]


FROM shipments
WHERE EXISTS ( SELECT suppliers.[s-no]
FROM suppliers
WHERE shipments.[s-no]=suppliers.[s-no]
AND suppliers.city = 'Paris');

Result
p-no
P1
P2

This returns a different result than the previous EXISTS example


because now we explicitly correlate the nested query with the outer
query by adding the condition

shipments.[s-no]=suppliers.[s-no]

We are requiring existence of a supplier's city being "Paris" and that


the supplier also exists in the shipments table.

148
SQL Notes

EXISTS AND NOT EXISTS EXAMPLE


-- CONTINUED … --
Find the part numbers of parts in the shipments table if no supplier
originates in Paris.

Notice the condition for retrieval is whether or not any supplier


originates in Paris.

QUERY

SELECT DISTINCT shipments.[p-no]


FROM shipments
WHERE NOT EXISTS ( SELECT suppliers.[s-no]
FROM suppliers
WHERE suppliers.city = 'Paris');

RESULT

No values are returned.

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

COMPARISON OPERATORS IN NESTED QUERIES


=, <, >, <=, >=, <>

The comparison operators compare a single value to a single value.


Consequently, the subquery must return a single value. This value is
then treated the same as any other value we have used in
constructing a WHERE clause. Multiple subqueries can be compared
to one another using the comparison operators as long as each
subquery returns a single value.

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

ANY, SOME AND ALL OPERATORS

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.

SELECT suppliers.[s-no], suppliers.status


FROM suppliers
WHERE suppliers.status > ANY (SELECT suppliers.status
FROM suppliers
WHERE suppliers.[s-no] IN ('S1', 'S2'));

Result

s-no
S1
S3
S4
S5

151
SQL Notes

NOTES ON NESTED QUERIES

1. The DBMS evaluates the overall query by evaluating the


inner-most nested query first, then the next inner-most
nested query, etc.

2. The exception to the evaluation procedure is for an EXISTS


or NOT EXISTS operator. In this case, the outer query is
evaluated first and compared to the results of the subquery
to determine whether the results from the outer query exist in
the results from the subquery.

3. Knowing the order of evaluation allows us to construct


complex nested queries by constructing them from the inside
to the outside, subquery by subquery.

152
SQL Notes

NESTED QUERY
-- EXAMPLE 1 --

Get supplier names for suppliers who supply part P2.

QUERY

SELECT suppliers.sname
FROM suppliers
WHERE suppliers.[s-no] IN ( SELECT shipments.[s-no]
FROM shipments
WHERE shipments.[p-no] = 'P2' );

ALTERNATIVE USING AN EQUI-JOIN

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

Get supplier names for suppliers who have shipments in


the shipments table and who supply at least one red
part.

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

Notice that this query is a three-level nesting.

154
SQL Notes

CORRELATED SUBQUERIES

Correlated subqueries can be created by referencing a column from


the outer query within the subquery.

Example

Get the names of suppliers that do not have shipments pending.

SELECT [sname]
FROM suppliers
WHERE [s-no] NOT IN (SELECT [s-no]
FROM shipments
WHERE suppliers.[s-no] = shipments.[s-no]);

Result:
sname
Adams

The supplier number ( s-no) in both tables is correlated between the


outer query and the subquery.

155
SQL Notes

ALIASES FOR TABLE NAMES IN NESTED QUERIES

In complex queries involving multiple tables or correlated subqueries,


it can be confusing to use the long table names. Aliases allow us to
rename tables for use within a query.

Syntax

SELECT …

FROM table1 AS alias for table1, table2 AS alias for table2, …

WHERE …

Example -- this is the same example as the Correlated Query example

Get the names of suppliers that do not have shipments pending.

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

COMPLEX NESTED QUERY EXAMPLE


(ALIASES EXAMPLE)
Example

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

There are several things happening in this query. First, we use


MIN(sname) to locate the first supplier in the alphabetical list. This
works because the names are converted to an internal representation
in which numerically the alphabet is in ascending order from a to z.
Second, we generate list of supplier numbers in which the supplier
number for supplier name (sname) is also in the shipments table. If it
is in the shipments table then we reject the supplier name. The query
compares the supplier number from the suppliers table with the
supplier number from the shipments table. The aliases allow us to
more easily understand what goes where.

157
SQL Notes

MULTIPLE ALIASES FOR THE SAME TABLE

Example

Get all unique pairs of part numbers that have the same quantity
shipped. Show the part number pairs, the supplier number and
quantity.

SELECT x.[p-no], y.[p-no], x.[s-no], x.qty


FROM shipments AS x, shipments AS y
WHERE x.[p-no] <>y.[p-no] AND x.qty = y.qty;

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:

x.p-no y.p-no s-no qty


P4 P1 S4 300
P4 P2 S1 200
P5 P3 S4 400
P2 P3 S2 400
P2 P4 S3 200
P2 P4 S4 200
P2 P4 S1 200
P6 P5 S1 100
P5 P6 S1 100
P4 P1 S4 300
P5 P2 S4 400
P3 P2 S1 400
P4 P2 S1 200
P1 P4 S2 300
P1 P4 S1 300
P4 P2 S1 200
P2 P5 S2 400
P3 P5 S1 400

158
SQL Notes

MULTIPLE ALIASES FOR THE SAME TABLE


CONTINUED …
The query result contains many duplicates. These exist because the
system examines all possible combinations by fixing one value for x.[p-
no] and then iterating through all possible values for y.[p-no] for the
condition
x.[p-no] =y.[p-no]. When the second condition x.qty = y.qty is met the
part number pair is saved as a solution. Thus, we have two types of
duplicates – duplicate rows and duplicate information. Duplicate rows
are the same row appearing more than once. This can be eliminated
using the DISTINCT operator. Duplicate information exists because
you will still have duplicate entries that are not duplicate rows.

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

MULTIPLE ALIASES FOR THE SAME TABLE


CONTINUED …

To eliminate the duplicate values we use the DISTINCT function and


the inequality operator in the query.

SELECT DISTINCT x.[p-no], y.[p-no], x.[s-no], x.qty


FROM shipments AS x, shipments AS y
WHERE x.[p-no] <y.[p-no] AND x.qty = y.qty;

Result:

x.p-no y.p-no s-no qty


P1 P4 S1 300
P1 P4 S2 300
P2 P3 S2 400
P2 P4 S1 200
P2 P4 S3 200
P2 P4 S4 200
P2 P5 S2 400
P3 P5 S1 400
P5 P6 S1 100

160
SQL Notes

NESTED QUERIES IN THE SELECT AND IN THE FROM

Nested Queries in the SELECT Part of a Query

Using a nested query to determine the supplier name for a shipment.

SELECT (SELECT sname FROM suppliers WHERE suppliers.[s-no] = shipments.[s-no])


AS Supplier, qty, [s-no], [p-no]
FROM shipments;

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.

SELECT suppliers.sname AS Supplier, shipments.qty,shipments.[s-no],shipments.[p-no]


FROM shipments, suppliers
WHERE suppliers.[s-no]=shipments.[s-no];

161
SQL Notes

NESTED QUERIES IN THE SELECT AND IN THE FROM


CONTINUED…

Nested Queries in the FROM Part of a Query

Using a nested query in Access2000 or AccessXP to determine the


DISTINCT COUNT of items in a database.

SELECT COUNT( [s-no] )


FROM (SELECT DISTINCT [s-no] FROM shipments);

The overall query works because a query always returns a database


table that can be operated on using another query. Thus, the nested
query returns a table of the distinct items in the shipments table and
the outer query counts the distinct items in the table returned by the
nested query.

Query Result

162
SQL Notes

NESTED QUERIES IN THE SELECT AND IN THE FROM


CONTINUED…
Objective

What supplier ships the maximum average quantity and what is that
quantity?

Query

SELECT [s-no], avgqty AS [Max of avg quantity]


FROM (SELECT [s-no], AVG(qty) AS avgqty FROM shipments GROUP BY [s-no] )
WHERE avgqty=(SELECT MAX(avgqty) FROM (SELECT [s-no], AVG(qty) AS avgqty
FROM shipments GROUP BY [s-no] ));

Result
s-no Max of avg quantity
S2 350

Two different things are happening in this query. In the WHERE


clause we use a nested query to locate the maximum value of the
average quantity shipped by suppliers. We then select from the table
of supplier numbers and their average quantity shipped the supplier
number (i.e., s-no) and average quantity (i.e., avgqty) with that
maximum value.

The nested query

SELECT [s-no], AVG(qty) AS avgqty FROM shipments GROUP BY [s-no];

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

3.1 Simple Queries

3.2 Relational Operators - UNION, INTERSECT and EXCEPT

3.3 Relational Operators – JOINs

3.4 Built-in Functions

3.5 Nested Queries

3.6 Interesting Uses of Queries

3.7 Update Operations

164
SQL Notes

3.6 INTERESTING USES OF QUERIES

In addition to the WHERE clause of the previous examples, nested


queries can be placed elsewhere. In the example below two nested
queries are used to retrieve the name of the part (sname) associated
with each supplier number (s-no) and the name of the part (pname)
associated with each part number
(p-no). The results from these queries are combined using the “&” to
create a character string labeled as the “primary key value”.

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

SELECT (SELECT suppliers.sname


FROM suppliers
WHERE suppliers.[s-no]= shipments.[s-no])
& " and " &
(SELECT parts.pname
FROM parts
WHERE parts.[p-no]=shipments.[p-no])
AS [primary key value], qty
FROM shipments, parts, suppliers
WHERE parts.[p-no]=shipments.[p-no]
AND suppliers.[s-no]= shipments.[s-no];

165
SQL Notes

INTERESTING USES OF QUERIES


CONTINUED …

QUERY RESULTS

primary key value qty


Smith and Nut 300
Smith and Bolt 200
Smith and Screw 400
Smith and Screw 200
Smith and Cam 100
Smith and Cog 100
Jones and Nut 300
Jones and Bolt 400
Clark and Bolt 200
Clark and Screw 300
Blake and Bolt 200
Clark and Cam 400

Notice that the supplier name is combined with the part name to form
the “primary key value”.

166
SQL Notes

COMPUTING DIFFERENCES BETWEEN ROW ENTRIES

Occasionally, it is necessary to compute differences between


successive row entries in a database table. An example is time-
stamped data in which it is necessary to compute the time interval
between successive events.

EXAMPLE DATABASE TABLE TEST


num time
1 2/3/2001 5:00:00 AM
2 2/3/2001 3:00:00 PM
3 2/3/2001 4:30:00 PM
4 2/3/2001 5:00:00 PM
5 2/3/2001 5:15:00 PM
6 2/3/2001 5:30:00 PM
7 2/3/2001 5:45:00 PM
8 2/3/2001 6:15:00 PM

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

Note: The function DATEDIFF is an MSAccess function that computes


the time difference between two dates. "n" specifies that the time
difference will be in minutes.

167
SQL Notes

HOW DO I GET THE SEQUENTIAL NUMBERS?

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.

INSERT INTO test ( time )


SELECT [time value]
FROM timetable
ORDER BY [time value];

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

3.1 Simple Queries

3.2 Relational Operators - UNION, INTERSECT and EXCEPT

3.3 Relational Operators – JOINs

3.4 Built-in Functions

3.5 Nested Queries

3.6 Interesting Uses of Queries

3.7 Update Operations

169
SQL Notes

3.7 UPDATE OPERATIONS

DEFINITION

The SQL data manipulation language includes three


update statements that allow you to change or modify,
delete, and insert information in a database. These are :

* UPDATE (i.e., change or modify)


* DELETE
* INSERT

170
SQL Notes

UPDATE STATEMENT

DEFINITION

When an UPDATE statement is executed, all rows in the


specified table that satisfy the WHERE predicate are
modified in accordance with the SET clause.

GENERAL SYNTAX

UPDATE table-name
SET column-name = expression
[, column-name = expression ] ...
[ WHERE predicate ] ;

In a syntax definition, those items in square brackets are optional.

NOTE: If the WHERE conditions are not met then the UPDATE
executes but no changes are made.

171
SQL Notes

NOTES ON THE UPDATE STATEMENT

1. It is not possible to update more than one table in a single


statement. Consequently, an UPDATE statement must specify
exactly one table.

2. If the WHERE conditions are not met then the UPDATE executes
but does not make any changes.

172
SQL Notes

EXAMPLE 1 OF AN UPDATE STATEMENT

Objective

In the parts table, change the color of part P2 to yellow,


increase its weight by 5, and set its city to "unknown"
(i.e., NULL).

SQL Statement

UPDATE parts
SET color = 'Yellow',
weight = weight + 5,
city = NULL
WHERE [p-no] = 'P2' ;

Result

P-no PName Color Weight City


P1 Nut Red 12 London
P2 Bolt Yellow 22 modified row
P3 Screw Blue 17 Rome
P4 Screw Red 14 London
P5 Cam Blue 12 Paris
P6 Cog Red 19 London

173
SQL Notes

EXAMPLE 2
SEARCH AND REPLACEMENT OF NULL VALUES

Objective

Find the null value of example 1 and replace it with zero.

SQL Statement

UPDATE parts

SET city = 0

WHERE city Is Null;

Results

P-no PName Color Weight City


P1 Nut Red 12 London
P2 Bolt yellow 22 0 modified row

P3 Screw Blue 17 Rome


P4 Screw Red 14 London
P5 Cam Blue 12 Paris
P6 Cog Red 19 London

Note We use the comparison


operator "Is" with the Null value and
not the "=" operator when testing.

When setting a record value to NULL


use use “=” as in example 1.

174
SQL Notes

EXAMPLE 3 OF AN UPDATE STATEMENT

OBJECTIVE

In the parts table, convert the weight from pounds to


kilograms.

SQL STATEMENT

UPDATE parts
SET weight = weight*0.45;

RESULT

p-no pname color weight city


P1 Nut Red 5.4 London
P2 Bolt green 7.65 Paris
P3 Screw Blue 7.65 Rome
P4 Screw Red 6.3 London
P5 Cam Blue 5.4 Paris
P6 Cog Red 8.55 London

175
SQL Notes

DELETE STATEMENT

DEFINITION

All rows in the specified table that satisfy the WHERE


predicate are deleted.

GENERAL SYNTAX

DELETE FROM table-name


[ WHERE predicate ] ;

In a syntax definition, those items in square brackets are optional.

176
SQL Notes

EXAMPLE 1 DELETE STATEMENT


-- EXAMPLE 1 --

OBJECTIVE

Delete the row in the Parts table that contains part "p6"

SQL STATEMENT

DELETE FROM parts


WHERE [p-no] = "p6";

RESULTS

The following row has been deleted from the parts table.

p-no pname color weight city


P6 Cog Red 8.55 London

177
SQL Notes

DELETE STATEMENT
-- EXAMPLE 2 --

OBJECTIVE

Delete all shipments for suppliers in London from the


shipments table.

SQL STATEMENT

DELETE FROM shipments


WHERE 'London' = ( SELECT suppliers.city
FROM suppliers
WHERE suppliers.[s-no] = shipments.[s-no] ) ;

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]

Note: This statement will only work in MS Access if "referential


integrity is turned off for all relationships among the database tables.

178
SQL Notes

EXAMPLE OF A DELETE STATEMENT


(CONTINUED)

RESULT

Before the DELETE statement is executed.

S-no P-no QTY


S1 P1 300
S1 P2 200
S1 P3 400
S1 P4 200
S1 P5 100
S1 P6 100
S2 P1 300
S2 P2 400
S3 P2 200
S4 P2 200
S4 P4 300
S4 P5 400

After the DELETE statement is executed.

S-no P-no QTY


S2 P1 300
S2 P2 400
S3 P2 200

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

INSERT INTO table-name (column-name Inserts


[, column-name] ...) constants into
VALUES ( constant [, constant] ...) ] ; a database
table.

or

INSERT INTO table-name (column-name Uses a query


[, column-name] ...) to specify the
SELECT ... FROM ... WHERE ... ; values that will
be inserted
into the
database table.

Note that you must explicitly specify the column names. You cannot
use a wild card specification of "*" as with a SELECT query.

In the syntax definition, those items in square brackets are optional.

180
SQL Notes

EXAMPLE OF A SINGLE-RECORD INSERT

OBJECTIVE

Add part P7 (city - Athens, weight - 24, name and color -


unknown) and part P8 (city – Raleigh, weight – 28, name
and color -- unknown) to table parts.

SQL STATEMENT

You can only insert constants one row at a time so two statements are
needed.

INSERT INTO parts ([p-no], city, weight)


VALUES ( 'P7', 'Athens', 24 ) ;

INSERT INTO parts ([p-no], city, weight)


VALUES ( 'P8', 'Raleigh', 28 ) ;

Note that there is a correspondence between the column and the


value to be inserted into it. This correspondence is determined by the
sequence of appearance. So, P7 will be inserted into column p-no
because they both are the first item in the corresponding lists. Below
we see the assignments based upon the corresponding sequences of
appearance.

p-no city weight

  

P7 Athens 24

P8 Raleigh 28

181
SQL Notes

EXAMPLE OF A SINGLE-RECORD INSERT


(CONTINUED)

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

P8 28 Raleigh Inserted Row

Note: In MS Access, if the contents of the parts table is open and


displayed, in order to see the inserted record you must close and
reopen the display of the parts table.

182
SQL Notes

EXAMPLE OF A MULTIPLE-RECORD INSERT

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:

CREATE TABLE temp ( [p-no] TEXT, tot_qty NUMBER) ;

SQL Statement 2:

INSERT INTO temp ( [p-no], tot_qty )


SELECT [p-no], SUM(qty)
FROM shipments
GROUP BY [p-no] ;

Statement1 creates the table temp and Statement 2 inserts the


information into table temp.

Result temp table


p-no tot_qty
P1 600
P2 1000
P3 400
P4 500
P5 500
P6 100

183
SQL Notes

EXAMPLE OF A CONDITIONAL IN AN INSERT

OBJECTIVE

Insert into the Suppliers table s-no = "s8", sname = "Robert",


status = 15, city = "Raleigh" only if "s8" is not in the Suppliers table.

SQL Query

INSERT INTO suppliers ([s-no], sname, status, city)


SELECT DISTINCT "S8", "Robert", 15, "Raleigh"
FROM suppliers
WHERE NOT EXISTS (SELECT [s-no]
FROM suppliers
WHERE [s-no]="s5");

Results

The query:

SELECT DISTINCT "S8", "Robert", 15 "Raleigh"


FROM suppliers
WHERE NOT EXISTS (SELECT [s-no]
FROM suppliers
WHERE [s-no]="s5")

will fail because of the NOT EXISTS condition since "s5" is


currently in the database table. Since this query fails the INSERT
will also fail and nothing will be inserted into the database.

This is useful when trying to insert information from a from that


may already exist in a database table. It eliminates the need to
write a script to search for the value in the database table.

See Section 3.3.5 for more details on NESTED queries.

184
SQL Notes

SQL NOTES

1 The Relational Data Model

2 Data Definition

3 SQL Queries -- Data Manipulation

4 Miscellaneous Topics

 The System Catalog


 Views
 Security
 Recovery
 Bill-of-Materials Problem

185
SQL Notes

4. MISCELLANEOUS TOPICS

4.1 The System Catalog


4.2 Views
4.3 Security
4.4 Recovery
4.5 Bill-of-Materials Problem

186
SQL Notes

4.1 THE SYSTEM CATALOG

DEFINITION

The system catalog is the DBMS's database that


contains information concerning things that are of
interest to the system itself. This includes information
on base tables, views, indexes, users, application plans,
access privileges, etc.

Note: The system catalog is not accessible via SQL by a user in MS


Access.

187
SQL Notes

NOTES ON THE SYSTEM CATALOG

1. When a CREATE statement is executed, an entry is made in


the system catalog and remains there until it is removed
through a DROP statement.

2. The catalog itself consists of tables just like a user database.


Consequently, it can be queried using SELECT statements to
get information about your own database.

188
SQL Notes

4.2 VIEWS

* Views provide a means for creating "virtual tables" that are


based on a selection of columns from one or more other
tables.

* They allow access to the results of an SQL query as if it were


a table without actually incurring the overhead (and possible
inconsistencies) of storing redundant data.

* Views can be based on one or more tables.

189
SQL Notes

VIEWS
(CONTINUED)

 Data in a view can be accessed by a user or application with


SQL statements as though it were in a real table.

 Views can be used to limit access to restricted portions of a


table.

 Views based on single tables can be updated.

 Views as an SQL-based entity are not supported by MS


Access.
A similar result is possible using forms.

190
SQL Notes

WHY DO WE NEED "VIEWS"?

* At the external level the database is perceived as an


external view, defined by an external schema.

* Different users and applications have different external


views.

* An external view can include base tables defined by the


conceptual schema as well as derived tables or views.

* Each external schema defines the derived tables or


views, and their relationships among one-another and
with the base tables defined in the conceptual schema.

191
SQL Notes

NOTES ON VIEWS

1. Views are not supported by their own, physically separate,


distinguishable stored data.

2. Their definition, in terms of other tables, is stored in the


DBMS catalog.

3. A view is in effect a window into the real tables of the DBMS


that is dynamic.

4. Any change to the other tables will automatically and


instantaneously be reflected in the view.

5. Any change to the view will also be automatically and


instantaneously reflected in the other tables.

192
SQL Notes

VIEW STATEMENT

Not supported in MSAccess. Must use a "temporary" table


qualifier in a Create Table statement (see next few pages)

DEFINITION

A "view" is a "virtual table" -- that is, a table that does


not exist in its own right but appears to the user or an
application as if it did exist.

GENERAL SYNTAX

CREATE VIEW view-name [ ( column-name [, column-name ] ...) ]


AS subquery ;

Note: Subqueries can reference other views. Thus, a view


can be defined in terms of other views.
Also, remember VIEWs are not supported by MS
Access.

193
SQL Notes

EXAMPLE OF A VIEW STATEMENT

OBJECTIVE

Create a view called good_suppliers from the table


suppliers that contains the supplier number, s-no, the
status, and the city. A "good supplier" is a supplier with
a status greater than 15.

SQL STATEMENT

CREATE VIEW good_suppliers


AS SELECT [s-no], status, city
FROM suppliers
WHERE status > 15 ;

Note: Remember VIEWs are not supported by MS Access.

RESULT

good_suppliers

s-no status city

S1 20 London
S3 30 Paris
S4 20 London
S5 30 Athens

194
SQL Notes

DROP VIEW STATEMENT

DEFINITION

The DROP VIEW statement deletes the definition of a


view from the DBMS catalog. Any views defined in terms
of other views are also automatically dropped.

GENERAL SYNTAX

DROP VIEW view-name ;

Notes: If a base table is dropped through a DROP TABLE


statement, all views defined from that base table (or
on views of that base table, etc.) are automatically
dropped too.

195
SQL Notes

EXAMPLE OF A DROP VIEW STATEMENT

OBJECTIVE

Drop the view good_suppliers.

SQL STATEMENT

DROP VIEW good_suppliers ;

RESULT

The view good_supplier is removed from the DBMS


catalog and no longer exists.

Note: Remember VIEWs are not supported by MS Access.

196
SQL Notes

OPERATIONS ON VIEWS

RETRIEVAL OPERATIONS

* The VIEW statement is converted by the DBMS into


equivalent operations on the underlying base tables and
executed.

* Generally, a view can be used just like a table in any type


of retrieval operation.

UPDATE OPERATIONS

* Only views based on a single base table can be updated.

197
SQL Notes

4.3 SECURITY

DEFINITION

Security in a database management system is the


protection of data against unauthorized disclosure,
alteration, or destruction.

Note: Within MS Access a database is made secure through


password protection. Consequently, the concept of a system
administrator does not exist in MS Access.

198
SQL Notes

SQL SECURITY FEATURES

* The view mechanism can be used to hide sensitive data


from unauthorized users

* The authorization subsystem which allows specific


rights to be selectively and dynamically granted and
revoked to users.

199
SQL Notes

GRANT STATEMENT

DEFINITION

The GRANT statement specifies what operations by a


user may be executed against which parts of the
database.

GENERAL SYNTAX

GRANT statement-name
[, statement-name ] ...
ON TABLE table-name [, table-name ] ...
TO user-name [, user-name ] ... ;

200
SQL Notes

REVOKE STATEMENT

DEFINITION

The REVOKE statement removes granted privileges.

GENERAL SYNTAX

REVOKE statement-name
[, statement-name ] ...
ON TABLE table-name [, table-name ] ...
TO user-name [, user-name ] ... ;

201
SQL Notes

EXAMPLE 1

OBJECTIVE

Grant all privileges to Ellen for the parts and shipments


tables.

SQL STATEMENT

GRANT ALL ON TABLE parts, shipments TO Ellen;

202
SQL Notes

EXAMPLE 2

OBJECTIVE

Grant SELECT privileges to everyone for all tables.

SQL STATEMENT

GRANT SELECT ON ALL TO ALL ;

203
SQL Notes

EXAMPLE 3

OBJECTIVE

Revoke update privileges from Young.

SQL STATEMENT

REVOKE UPDATE ON ALL FROM Young;

204
SQL Notes

4.4 RECOVERY

 A Transaction Processing System

 COMMIT Statement

 ROLLBACK Statement

 System Recovery

205
SQL Notes

A TRANSACTION PROCESSING SYSTEM

DEFINITION OF A "TRANSACTION"

A "transaction" is a logical unit of work that transforms a


consistent state of the database into another consistent
state, without necessarily preserving consistency at all
intermediate points. A transaction may require a
sequence of several database operations.

206
SQL Notes

A TRANSACTION PROCESSING SYSTEM


(CONTINUED)

DEFINITION OF A "TRANSACTION PROCESSING SYSTEM"

A "transaction processing" system is a system that


supports the processing of transactions by guarantying
that if a transaction has not completed all its database
operations when a failure occurs, then those operations
will be undone.

Thus, the transaction either executes in its entirety or is


totally canceled (i.e., made as if it never executed at all).

207
SQL Notes

TRANSACTION PROCESSING EXAMPLE

OBJECTIVE

Change the supplier number of supplier S1 from S1 to


S3.

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

COMMENTS ON THE EXAMPLE

QUESTION

If we are on a system where multiple users are


simultaneously trying to access the suppliers table and
the shipments table, how can we ensure that both
changes will be made before anyone else has a query
processed?

ANSWER

We can't with the queries written as in the example.

209
SQL Notes

EXAMPLE CORRECTED TO BE A "TRANSACTION PROCESS"

CORRECTED SQL QUERY

COMMIT /Used here to signify the start of a new transaction./

UPDATE suppliers
SET [s-no] = 'S2'
WHERE [s-no] = 'S1' ;

UPDATE shipments
SET [s-no] = 'S2'
WHERE [s-no] = 'S1' ;

COMMIT /Used here to signify the end of the transaction and


commits the database changes made by it./

210
SQL Notes

COMMIT STATEMENT

DEFINITION

The COMMIT statement terminates a transaction or a


logical unit of work and commits database changes
made by it. It also signifies the start of a new
transaction. The COMMIT statement applies to all SQL
statements and should be used in all embedded SQL
statements.

211
SQL Notes

ROLLBACK STATEMENT

DEFINITION

The ROLLBACK statement terminates the current


transaction or logical unit of work. It causes the current
transaction to be aborted. This restores the database to
the state it was in at the last COMMIT or ROLLBACK. It
also signifies the start of a new transaction. The
ROLLBACK statement applies to all SQL statements and
should be used in all embedded SQL statements.

212
SQL Notes

SYSTEM RECOVERY

HOW IS IT POSSIBLE TO UNDO AN UPDATE?

* The system maintains a "log" or "journal" on disk in


which details of all update operations are recorded.

* If it becomes necessary to undo an update, the DBMS


uses the corresponding log entry to restore the item to
its previous value.

213
SQL Notes

SYSTEM RECOVERY
(CONTINUED)

HOW DO WE RECOVERY FROM A HARDWARE FAILURE?

* A "roll forward journal file" can be maintained that has a


record of all SQL statements that were executed.

214
SQL Notes

SYSTEM RECOVERY
(CONTINUED)

ROLL FORWARD JOURNAL FILE

* This file lets you restore the database since it has a


record of all SQL statements that were executed and
modified the database.

* It should be kept on a different physical device than that


of the database (i.e., a different physical disk drive).

* The roll forward journal file is used in conjunction with a


restart procedure to recreate all transactions lost to a
failure.

215
SQL Notes

4.5 BILL-OF-MATERIALS PROBLEM

Also known as the Parts Explosion Problem


1. We need to "explode" the part to "n" levels.

2. We therefore need a way of holding "n" distinct positions in


the database (corresponding to "n" distinct levels in the tree)
simultaneously.

3. The object that is used in SQL to hold a position in the


database is the "cursor," and so we need "n" cursors.

4. Since the value of "n" is unknown at the time of writing the


query, those "n" cursors can't be declared. We need a way
of "recursively" calling cursors.

5. The current SQL standard doesn't support recursive cursors.

216
SQL Notes

ORACLE SOLUTION TO THE


BILL-OF-MATERIALS PROBLEM

* The relationship that connects nodes in the tree can be


expressed by the following "logical expression":

parents node's MAJOR_p-no = child node's MINOR_p-no

* The CONNECT BY clause can be used in the SELECT


statement:

CONNECT BY PRIOR MAJOR_p-no = MINOR_p-no

* The CONNECT BY clause says that "if one node's MAJOR_p-


no equals a second node's MINOR_p-no, then the first node
is the parent of the second."

217
SQL Notes

ORACLE SOLUTION TO THE


BILL-OF-MATERIALS PROBLEM
(CONTINUED)

* PRIOR means that you are walking the tree from the root
downward so you will encounter each parent node "prior" to
its child.

* The root is identified with the START WITH clause:

START WITH MAJOR_p-no = 'P1'

* The CONNECT BY and START WITH clauses follow the


FROM clause (and the WHERE clause, if present).

218
SQL Notes

ORACLE SOLUTION TO THE


BILL-OF-MATERIALS PROBLEM
(CONTINUED)

QUERY

SELECT [MAJOR_p-no], [MINOR_p-no]


FROM parts_OF_parts
CONNECT BY PRIOR [MAJOR_p-no] = [MINOR_p-no]
START WITH [MAJOR_p-no = 'P1'] ;

Note: For MS Access this problem would be solved by writing a


program in the Access BASIC programming language.

219

You might also like