SQL: Lessons: Machine A PDF Writer That Produces Quality PDF Files With Ease!

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

SQL: Lessons

Lesson 1: Tables and Schema definition ...............................................................................5


The Relational Database Model.........................................................................................5
Schema Definition .............................................................................................................6
Conventions Used ..............................................................................................................7
Lesson 2: The SELECT clause and the FROM clause ..........................................................7
The SELECT and FROM clause........................................................................................7
Example 2.1 ...................................................................................................................7
Example 2.2 ...................................................................................................................7
Example 2.3 ...................................................................................................................8
Example 2.4 ...................................................................................................................8
Example 2.5 ...................................................................................................................8
Column Alias .....................................................................................................................8
Example 2.6 ...................................................................................................................8
Example 2.7 ...................................................................................................................9
Order By.............................................................................................................................9
Example 2.8: Ascending Sort ........................................................................................9
Results 2.8......................................................................................................................9
Example 2.9: Descending Sort.......................................................................................9
Results 2.9......................................................................................................................9
ALL, DISTINCT, TOP ....................................................................................................10
Example 2.10: Distinct.................................................................................................10
Results 2.10..................................................................................................................10
Example 2.11: TOP......................................................................................................10
Results 2.11..................................................................................................................10
Lesson 3: The WHERE clause.............................................................................................11
Lesson 3.1: Comparison Operators......................................................................................11
Example 3.1 .................................................................................................................11
Results 3.1....................................................................................................................11
Comparison Operators .....................................................................................................11
Lesson 3.2: Pattern Matches ................................................................................................12
Example 3.2 .................................................................................................................12
Results 3.2....................................................................................................................12
Wildcards .....................................................................................................................12
Lesson 3.3: Range Checks ...................................................................................................13
BETWEEN ..................................................................................................................13
Example 3.3 .................................................................................................................13
Example 3.4 .................................................................................................................13
Results 3.3 and 3.4 .......................................................................................................13
Example 3.5 .................................................................................................................13
Example 3.6 .................................................................................................................13
Results 3.5 and 3.6 .......................................................................................................13
Lesson 3.4: IN......................................................................................................................14
Example 3.7 .................................................................................................................14
Example 3.8 .................................................................................................................14
Results 3.7 and 3.8 .......................................................................................................14
Example 3.9 and 3.10...................................................................................................14
Results 3.9 and 3.10 .....................................................................................................15
pdfMachine
A pdf writer that produces quality PDF files with ease!
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Example 3.11 ...............................................................................................................15
Example 3.12 ...............................................................................................................15
Results 3.11 and 3.12 ...................................................................................................15
Example 3.13 ...............................................................................................................15
Results 3.13..................................................................................................................15
Example 3.14 ...............................................................................................................16
Results 3.14..................................................................................................................16
Lesson 3.5: NULL ...............................................................................................................16
Example 3.15 ISNULL ................................................................................................16
Results 3.15..................................................................................................................16
Lesson 4: Old Style/ANSI Style Joins .................................................................................17
Introduction......................................................................................................................17
Lesson 4.1: CROSS JOIN....................................................................................................17
When to use Cross Joins ..................................................................................................17
Example 4.1 Cross Join (Cartesian product)................................................................18
Results 4.1....................................................................................................................18
Lesson 4.2: INNER JOINS ..................................................................................................20
When to use Inner Joins...................................................................................................20
Example 4.2 Inner Join ................................................................................................20
Results 4.2....................................................................................................................20
Lesson 4.3: LEFT OUTER JOINS ......................................................................................21
When to use Left Outer Joins...........................................................................................21
Example 4.3 Left Join ..................................................................................................21
Results 4.3....................................................................................................................21
Example: Left Join Three Tables .................................................................................22
Lesson 4.4: RIGHT OUTER JOINS....................................................................................22
When to use Right Outer Joins ........................................................................................22
Example 4.4 Right Join................................................................................................22
Results 4.4....................................................................................................................22
Example: Right Join Three Tables...............................................................................23
Lesson 4.5: FULL OUTER JOINS......................................................................................24
When to use Full Joins.....................................................................................................24
Example 4.5 Full Join ..................................................................................................24
Results 4.5....................................................................................................................24
Lesson 4.6: Joining Multiple tables .....................................................................................24
Example 4.6 .................................................................................................................25
Lesson 5: Aggregation functions .........................................................................................26
Introduction......................................................................................................................26
Lesson 5.1: COUNT ........................................................................................................26
Example 5.1 COUNT(*)..............................................................................................26
Results 5.1....................................................................................................................26
Example 5.2 COUNT(vend_id) ...................................................................................26
Results 5.2....................................................................................................................26
Example 5.3 COUNT(*)..............................................................................................26
Lesson 5.2: SUM .................................................................................................................27
Example 5.4 SUM(prod_price)....................................................................................27
Results 5.4....................................................................................................................27
Example 5.5 SUM(P.prod_price) ................................................................................27
Results 5.5....................................................................................................................27

pdfMachine
A pdf writer that produces quality PDF files with ease!
1
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 5.3: AVG .................................................................................................................27
Example 5.6 AVG(P.prod_price) ................................................................................28
Results 5.6....................................................................................................................28
Lesson 5.4: MIN ..................................................................................................................28
Example 5.7 MIN(P.prod_price) .................................................................................28
Results 5.7....................................................................................................................29
Lesson 5.5: MAX.................................................................................................................29
Example 5.8 MAX(P.prod_price)................................................................................29
Results 5.8....................................................................................................................29
Lesson 5.6: MIN, MAX and Strings....................................................................................30
Results 5.9....................................................................................................................30
Example 5.10 MIN(P.prod_name) and MAX(P.prod_name)......................................30
Results 5.10..................................................................................................................31
Lesson 5.7: Sub-queries .......................................................................................................32
Example 5.11 Sub-query..............................................................................................32
Results 5.11..................................................................................................................32
Lesson 5.8: GROUP BY ......................................................................................................33
Example 5.12 GROUP BY C.Cust_Name, P.prod_price ............................................33
Results 5.12..................................................................................................................33
Example 5.13 GROUP BY OI.order_num ..................................................................33
Results 5.13..................................................................................................................34
Lesson 5.9: HAVING ..........................................................................................................34
Example 5.14 GROUP BY.... HAVING .....................................................................34
Results 5.14..................................................................................................................34
Example 5.15 ...............................................................................................................35
Results 5.15..................................................................................................................35
Lesson 6: CASE/DECODE..................................................................................................35
Example 6.1 CASE vend_name...................................................................................35
Results 6.1....................................................................................................................36
Example 6.2 CASE ......................................................................................................36
Results 6.2....................................................................................................................36
Lesson 7: UNION ................................................................................................................36
Example 7.1 UNION ...................................................................................................37
Results 7.1....................................................................................................................37
Example 7.2 .................................................................................................................37
Results 7.2....................................................................................................................38
Example 7.3 Place Holders ..........................................................................................38
Results 7.3....................................................................................................................38
Lesson 8: Data Type Conversions .......................................................................................39
SQL Server.......................................................................................................................39
Example 8.1 Query without data conversions .............................................................39
Results 8.1....................................................................................................................39
Example 8.2 CAST ......................................................................................................39
Results 8.2....................................................................................................................39
Example 8.3 CONVERT .............................................................................................40
Results 8.3....................................................................................................................40
Oracle...............................................................................................................................40
Example 8.4 Query without data conversions .............................................................41
Results 8.4....................................................................................................................41

pdfMachine
A pdf writer that produces quality PDF files with ease!
2
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Example 8.5 TO_CHAR, TO_NUMBER, TO_DATE ...............................................41
Results 8.5....................................................................................................................42
Lesson 9: VIEWS ................................................................................................................43
Example 9.1 View Creation.........................................................................................43
Example 9.2 Querying Views ......................................................................................43
Results 9.2....................................................................................................................43
Lesson 10: CREATE TABLE, ALTER TABLE.................................................................44
CREATE TABLE ............................................................................................................44
Example 10.1 The Orders Table ..................................................................................44
Data Types .......................................................................................................................44
Constraints .......................................................................................................................45
ALTER TABLE...............................................................................................................45
Lesson 11: INSERT .............................................................................................................46
Method One: ................................................................................................................46
Method Two.................................................................................................................46
Constraints .......................................................................................................................46
Example 11.1 Adding a Customer ...............................................................................47
Results 11.1..................................................................................................................47
Lesson 12: UPDATE ...........................................................................................................47
UPDATE..........................................................................................................................47
Example 12.1 The Current Values...............................................................................48
Results 12.1..................................................................................................................48
Example 12.2 UPDATE...............................................................................................48
Results 12.2..................................................................................................................48
SQL Exercises...................................................................... Error! Bookmark not defined.
Lesson 1: ......................................................................................................................50
Lesson 2: ......................................................................................................................50
Lesson 3.1: ...................................................................................................................50
Lesson 3.2: ...................................................................................................................51
Lesson 3.3: ...................................................................................................................51
Lesson 3.4: ...................................................................................................................51
Lesson 4.1 ....................................................................................................................51
Lesson 4.2 ....................................................................................................................51
Lesson 4.3 ....................................................................................................................52
Lesson 4.4 ....................................................................................................................52
Lesson 4.5 ....................................................................................................................52
Lesson 5.1 ....................................................................................................................52
Lesson 5.2 ....................................................................................................................52
Lesson 5.3 ....................................................................................................................52
Lesson 5.4 ....................................................................................................................52
Lesson 5.5 ....................................................................................................................52
Lesson 5.6 ....................................................................................................................53
Lesson 5.7 ....................................................................................................................53
Lesson 5.8 ....................................................................................................................53
Lesson 6: ......................................................................................................................54
Lesson 7: ......................................................................................................................55
Lesson 8: ......................................................................................................................55
Lesson 9: ......................................................................................................................56
Lesson 10: ....................................................................................................................56

pdfMachine
A pdf writer that produces quality PDF files with ease!
3
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 11: ....................................................................................................................56
Lesson 12 .....................................................................................................................57

pdfMachine
A pdf writer that produces quality PDF files with ease!
4
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 1: Tables and Schema definition

The Relational Database Model

Database Relation: A relational database management system (RDBMS) organizes information in two-
dimensional tables, called relations.

A table in a relational database consists of rows and columns. The intersection of a row and a column is known
as a field, and each field contains only one value. Empty fields are called NULL fields. Figure 1.1 gives an
example of a table (relation).

Columns

Vend_id vend_name vend_address vend_city vend_state vend_zip

BRS01 Bears R Us 123 Main Street Bear Town MI 4444

BRE02 Bear Emporium 500 Park Street Anytown OH 44333

Rows DLL01 Doll House Inc. 555 High Street Dollsville CA 99999

FRB01 Furball Inc. 1000 5th Avenue New York NY 11111

EX011 Some Name NULL NULL VA 22222

Figure 1.1: Vendors Table

In Figure 1.1 the column headings are vend_id, vend_name, vend_address, vend_city, vend_state and
vend_zip. The value BRS01 under vend_id is a field with the value of BRS01. The NULL values under
vend_address and vend_city indicate that these values were not assigned or are unknown.

The vend_id for the Vendors table is the Primary Key. A Primary Key a column, or set of columns, that
uniquely identifies each row in a table. Primary Keys cannot take a NULL value.

pdfMachine
A pdf writer that produces quality PDF files with ease!
5
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Schema Definition

A Schema is a collection of tables that are related to each other. Figure 1.2 is an example of a database schema.

Figure 1.2: Database Schema

In the above schema there are five tables. Each table relates to the others through a foreign key.

A foreign key is used to maintain referential integrity. For example if the Vendors table is the parent and the
Products table is the child then the Products table cannot refer to a vendor that does not exist in the Vendors
table. In other words, the child table is dependent on the parent table and cannot contain information about
something the parent does not know about.

pdfMachine
A pdf writer that produces quality PDF files with ease!
6
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Conventions Used

The following conventions will be used thought all lessons:

 Table names will start with a capital letter and the remaining letters will be lower case.
 Column names are all lower case.
 Key words will be capitalized.
 Table aliases are capitalized.
 Column aliases have the first letter capitalized.
 Numeric fields are right justified.
 Character fields are left justified.
 View names will start with a lower case "v".
 ANSI (American National Standards Institute) style queries may not work on all relation database
systems.

Lesson 2: The SELECT clause and the FROM clause

The SELECT and FROM clause

The SELECT clause is the starting point of any query. A simple select statement would look like Example 2.1:

Example 2.1
SELECT *
FROM Customers;

The above statement is in effect saying: "Go to the Customers table and return all columns and all rows".
The SELECT determines which columns are to be returned. The FROM clause determines from which table(s)
the data is to be retrieved. The semicolon (;) at the end of the statement indicates that the statement is complete.
Some systems do not require the semicolon (SQL-Server) while others do (Oracle).
The * indicates that all columns are to be return. Since no filtering was stated (the WHERE clause is missing)
all rows are returned.

To select specific columns from a single table, those columns need to be listed.

Example 2.2
SELECT cust_name, cust_email
FROM Customers;

In Example 2.2 only the customer name and email are selected from the table. Note that the column names are
separated by a comma (,). A comma should appear after each column name except for the last column selected.

pdfMachine
A pdf writer that produces quality PDF files with ease!
7
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
If we were going to select from multiple tables then we will need to provide a table/column combination,
especially in the case where both tables have columns of the same name.

Example 2.3

SELECT Customers.cust_id, Customers.cust_name, Orders.cust_id, Orders.order_date


FROM Customers, Orders;

In Example 2.3 we are selecting the customer id and name from the Customers table, and the customer id and
order date from the Orders table. The syntax <table name>.<column name> is used to specify which table the
column is to be retrieved from. Note that the table names in the FROM clause are separated by a comma (,). A
comma should appear after each table name except for the last table selected.

In order to avoid retyping the table name over and over again a table alias can be used.

Example 2.4

SELECT C.cust_id, C.cust_name, O.cust_id, O.order_date


FROM Customers C, Orders O;

The statement in Example 2.4 returns the same result as the statement in Example 2.3. The only difference is
that the letter "C" is used to refer to the Customers table and the letter "O" is used to refer to the Orders table.

To select everything from one table and only a few columns from another, table alias and the * can be used
together.

Example 2.5

SELECT C.*, O.cust_id, O.order_date


FROM Customers C, Orders O;

The statement in Example 2.5 returns everything from the Customers table and returns the customer id and the
order date from the Orders table.

Column Alias

You can also rename columns in the SELECT clause. This renaming does not change the column name in the
database; it only affects the result set.

Example 2.6

SELECT LTRIM(RTRIM(C.cust_name)) AS customer_name


FROM Customers C;

The expression LTRIM and RTRIM as applied to the column cust_name to remove any spaces that pad the left
and right of the customer name. The column would appear in the results set as LTRIM(RTRIM(C.cust_name)).

pdfMachine
A pdf writer that produces quality PDF files with ease!
8
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
The use of the "AS" keyword changes the way the column name will appear in the results set. In Example 2.6
the column would appear as customer_name.

You can also concatenate results. Suppose you want to return the customers address as a single string and not as
separate columns.

Example 2.7

SELECT RTRIM(cust_address) + ', ' + RTRIM( cust_city) + ', ' + RTRIM(cust_zip) AS Customer_Address
FROM Customers;

The concatenation operator in SQL Server is the "+". Example 2.7 is assuming the use of a SQL Server
database.
If you are using an Oracle (Not supported by SQL-Tutor) database the concatenation operator is the "||" and
Example 2.7 would look like this:

SELECT RTRIM(cust_address) || ', ' || RTRIM( cust_city) || ', ' || RTRIM(cust_zip) AS Customer_Address
FROM Customers;

Order By

The ORDER BY clause sorts the results of a query.

Example 2.8: Ascending Sort

SELECT cust_name
FROM Customers
ORDER BY cust_name ASC

Results 2.8
cust_name
Fun4All
Fun4All
Kids Place
The Toy Store
Village Toys

Example 2.9: Descending Sort

SELECT cust_name
FROM Customers
ORDER BY cust_name Desc

Results 2.9
cust_name

pdfMachine
A pdf writer that produces quality PDF files with ease!
9
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Village Toys
The Toy Store
Kids Place
Fun4All
Fun4All

ALL, DISTINCT, TOP

ALL

The keyword ALL in a query is used to obtain all records in the result set. This is the default setting. Examples
2.8 and 2.9 both return all records.

To eliminate duplicate records the key word DISTINCT is used.

DISTINCT

Example 2.10: Distinct

SELECT DISTINCT cust_name


FROM Customers
ORDER BY cust_name ASC

Results 2.10
cust_name
Fun4All
Kids Place
The Toy Store
Village Toys

The duplicate value for "Fun4All" was not displayed.

TOP

The keyword TOP is used to limit the number of rows returned in the result set.

Example 2.11: TOP

SELECT TOP 2 cust_name


FROM Customers
ORDER BY cust_name DESC

Results 2.11
cust_name

pdfMachine
A pdf writer that produces quality PDF files with ease!
10
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Village Toys
The Toy Store

Lesson 3: The WHERE clause


The WHERE clause is used to filter the result set of query. If a WHERE clause is not added to the SELECT
statement all rows are returned. Lesson 3 will cover the following WHERE clause topics:

 Comparison Operators
 Pattern Matches
 Range Checks
 IN
 Null Values

Lesson 3.1: Comparison Operators


The WHERE clause is used to filter the result set. If a WHERE clause is not added to the SELECT statement
all rows are returned.

Example 3.1

SELECT *
FROM Products
WHERE prod_price = 5.99

Results 3.1
prod_id vend_id prod_name prod_price prod_desc
8 inch teddy bear,
BR01 BRS01 8 inch teddy bear $5.99 comes with cap and
jacket

As the results table shows, Example 3.1 will display all columns in the Products table and will return rows for
which the products price is $5.99. The "=" comparison operator is just one of many employed by the WHERE
clause. Table 3.1 contains a list of comparison operators, their purpose, and an example of their use.

Comparison Operators
Operator Purpose Example
= Equal: Checks if two values are the same. prod_price = 5.99
<> Not Equal: Checks if two values are not the same. prod_price <> 3.49
!= Not Equal: Checks if two values are not the same. prod_price != 3.49
> Greater Than: Checks if the value on the right is higher than the value on the left. prod_price > 3.49
Greater Than or Equal To: Checks if the value on the right is higher than, or the same as,
>= prod_price >= 4.99
the value on the left.

pdfMachine
A pdf writer that produces quality PDF files with ease!
11
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
< Less Than: Checks if the value on the right is lower than the value on the left. prod_price < 8.99
Less Than or Equal To: Checks if the value on the right is lower than, or the same as, the
<= prod_price <= 8.99
value on the left.
!< Not Less Than: Checks if the value on the right is not lower than the value on the left. prod_price !< 5.99
!> Not Greater Than: Checks if the value on the right is not higher than the value on the left. prod_price !> 5.99

Lesson 3.2: Pattern Matches


The LIKE operator is use to find patterns in strings. It is useful for those times when you do not know, or are
not searching for, an exact value. The LIKE operator allows you to provide the values you know, or are
searching for, and use wildcards to fill in the rest.

Example 3.2

SELECT prod_name
FROM Products
WHERE prod_name LIKE '%bean%'

Results 3.2
prod_name
Fish bean bag toy
Bird bean bag toy
Rabbit bean bag toy

As the results table shows, Example 3.2 will return all product names that contain the "bean" string. If you are
using a SQL Server database case is not important; "bean", "Bean", and "BEAN" will all produce the same
results. In an Oracle database this is not true.

The following table lists some of the wildcards that can be used with the LIKE operator.

Wildcards
Wildcard Purpose Example Results
Returns any product name that contains the "bean"
% Zero or more characters. prod_name LIKE '%bean%'
string .
Any single character
prod_name LIKE Returns any products name that has a single
_ followed by the rest in a
'_ish bean b_g t_y' characters in the "_" location.
string.
Returns all product names that start with an "F" or an
Look for ranges inside the
[] prod_name LIKE '[FR]%' "R". If the "%" is not used the query will search for
brackets [A-D].
names that are one character long.
Returns all product names that do not start with an
Look for anything NOT in
[^] prod_name LIKE '[^FR]%' "F" or an "R". If the "%" is not used the query will
the range.
search for names that are one character long.
Looks for anything that is
prod_name NOT Returns all product names that do not contain the
NOT not returned by the LIKE
LIKE '%bean%' "bean" string .
operator.

pdfMachine
A pdf writer that produces quality PDF files with ease!
12
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 3.3: Range Checks
BETWEEN
There are two ways to search for objects in a inclusive range. The first method is to use greater than or equal
to and less than or equal to. The second method is to use BETWEEN.

Example 3.3

SELECT prod_name, prod_price


FROM Products
WHERE prod_price >= 5.99 AND prod_price <= 11.99

Example 3.4

SELECT prod_name, prod_price


FROM Products
WHERE prod_price BETWEEN 5.99 AND 11.99

Examples 3.3 and 3.4 are equivalent and produce the following results:

Results 3.3 and 3.4


prod_name prod_price
8 inch teddy bear 5.99
12 inch teddy bear 8.99
18 inch teddy bear 11.99
King doll 9.49
Queen doll 9.49

Example 3.5

SELECT prod_name, prod_price


FROM Products
WHERE NOT (prod_price >= 5.99 AND prod_price <= 11.99)

Example 3.6

SELECT prod_name, prod_price


FROM Products
WHERE prod_price NOT BETWEEN 5.99 AND 11.99

Examples 3.5 and 3.6 are equivalent and produce the following results:

Results 3.5 and 3.6


pdfMachine
A pdf writer that produces quality PDF files with ease!
13
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
prod_name prod_price
Fish bean bag toy 3.49
Bird bean bag toy 3.49
Rabbit bean bag toy 3.49
Raggedy Ann 4.99

Using BETWEEN makes the SQL more readable and easier to negate.

Lesson 3.4: IN
IN searches a list of values and returns tuples (rows) that match those values. The same results can be attained
with a series of ORs in the WHERE clause.

Example 3.7

SELECT prod_name
FROM Products
WHERE prod_price IN ( 5.99, 4.99, 8.99)

Example 3.8

SELECT prod_name, prod_price


FROM Products
WHERE prod_price = 5.99 OR
prod_price = 4.99 OR
prod_price = 8.99

The results from Example 3.7 and 3.8 are identical.

Results 3.7 and 3.8


prod_name prod_price
8 inch teddy bear 5.9900
12 inch teddy bear 8.9900
Raggedy Ann 4.9900

The NOT operator also applies to the IN rage check. In Examples 3.9 and 3.10 we are selecting all products
that have prices that are equal to $5.99, $4.99, or $8.99.

Example 3.9 and 3.10

SELECT prod_name, prod_price


FROM Products
WHERE prod_price NOT IN ( 5.99, 4.99, 8.99)

SELECT prod_name, prod_price


pdfMachine
A pdf writer that produces quality PDF files with ease!
14
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
FROM Products
WHERE NOT (prod_price = 5.99 OR
prod_price = 4.99 OR
prod_price = 8.99)

Results 3.9 and 3.10


prod_name prod_price
18 inch teddy bear 11.99
Fish bean bag toy 3.49
Bird bean bag toy 3.49
Rabbit bean bag toy 3.49
King doll 9.49
Queen doll 9.49

Providing only one value for IN is equivalent to using "=" in the WHERE clause.

Example 3.11

SELECT prod_name, prod_price


FROM Products
WHERE prod_price IN ( 5.99 )

Example 3.12

SELECT prod_name, prod_price


FROM Products
WHERE prod_price = 5.99

Results 3.11 and 3.12


prod_name prod_price
8 inch teddy bear 5.9900

If you do not know the exact values that are to be used in the IN range check then you can make use of a sub-
query. Suppose you want to get a listing of all products and their prices from vendors with a name that contains
the word "Inc." A sub-query that returns the vendor IDs of such vendors could be used to return those values.

Example 3.13

SELECT prod_name, prod_price


FROM Products
WHERE vend_id IN (SELECT vend_id FROM Vendors WHERE vend_name LIKE '%Inc.%')

Results 3.13
prod_name prod_price
Fish bean bag toy 3.4900

pdfMachine
A pdf writer that produces quality PDF files with ease!
15
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Bird bean bag toy 3.4900
Rabbit bean bag toy 3.4900
Raggedy Ann 4.9900

You can also use sub-queries to exclude rows from the result set.

Example 3.14

SELECT prod_name, prod_price


FROM Products
WHERE vend_id NOT IN (SELECT vend_id FROM Vendors WHERE vend_name LIKE '%Inc.%')

Results 3.14
prod_name prod_price
8 inch teddy bear 5.99
12 inch teddy bear 8.99
18 inch teddy bear 11.99
King doll 9.49
Queen doll 9.49

More on sub-queries in Lesson 5.6

Lesson 3.5: NULL


NULLs cannot be treated like known values. You cannot perform arithmetic with NULL values. Any
arithmetic operation performed on a NULL will produce a NULL. You can't use comparison operators ("=",
LIKE, IN, BETWEEN, >, <, >=, <=) on NULL either. IS NULL and IS NOT NULL are used to determine if a
value is NULL.

Another useful function is ISNULL. In Oracle the NVL function performs the same task.

ISNULL(expression, new value), or in Oracle, NVL(expression, new value) checks if the expression is a
NULL value. If the expression is in fact NULL, then new value is returned in the results set.

Example 3.15 ISNULL


SELECT IsNull(cust_email, 'N/A')
FROM Customers

Results 3.15
Email
[email protected]
N/A
[email protected]
[email protected]

pdfMachine
A pdf writer that produces quality PDF files with ease!
16
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
N/A

Lesson 4: Old Style/ANSI Style Joins

Introduction

When related data is stored in two or more relations (tables) extracting the data requires a join. For example, if
we want to list all product names and the names of their vendors we would need to join the Vendor table to the
Products table. Table 4.1 shows the syntax for this query using the old style join and the ANSI style join:

Old Style ANSI Style


SELECT P.prod_name, SELECT P.prod_name,
V.vend_name V.vend_name
FROM Vendors V, FROM Vendors V
Products P JOIN Products P ON V.vend_id = P.vend_id
WHERE V.vend_id = P.vend_id

Table 4.1

Old style joins are performed in the WHERE clause while ANSI style joins are performed in the FROM clause.
ANSI style joins use the WHERE clause to filter the result set as do old style joins. The join condition
determines which columns must match. In Table 4.1 the join condition is that the vendor id in the Vendors
table match the vendor id in the Products table. The query is basically saying "Give me the product name and
the name of the vendor of the given product." Join conditions involve columns that are present in both tables.

There are five different types of joins that can be perform using old style and ANSI style joins:

1. Cross Join: Returns the cross product (Cartesian product) of two tables.
2. Inner Join: Only returns records from each table that match. If the records do not match they are not
included in the result set. If a join type is not specified then this is the default.
3. Left Join: Returns all records on the left side of the join regardless of a match.
4. Right Join: Returns all records on the right side of the join regardless of a match.
5. Full Join: Returns all records from both sides of the join regardless of a match.

Lesson 4.1: CROSS JOIN


When to use Cross Joins
Cross join are used to return a Cartesian product. The resulting number of rows is the number of rows in the
first table multiplied by the number of rows in the second table.

pdfMachine
A pdf writer that produces quality PDF files with ease!
17
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Example 4.1 Cross Join (Cartesian product)
Old Style ANSI Style
SELECT P.prod_name, SELECT P.prod_name,
V.vend_name V.vend_name
FROM Vendors V, FROM Vendors V
Products P CROSS JOIN Products P

Results 4.1
prod_name vend_name
8 inch teddy bear Bears R Us
12 inch teddy bear Bears R Us
18 inch teddy bear Bears R Us
Fish bean bag toy Bears R Us
Bird bean bag toy Bears R Us
Rabbit bean bag toy Bears R Us
Raggedy Ann Bears R Us
Raggedy Andy Bears R Us
8 inch teddy bear Bear Emporium
12 inch teddy bear Bear Emporium
18 inch teddy bear Bear Emporium
Fish bean bag toy Bear Emporium
Bird bean bag toy Bear Emporium
Rabbit bean bag toy Bear Emporium
Raggedy Ann Bear Emporium
Raggedy Andy Bear Emporium
8 inch teddy bear Doll House Inc.
12 inch teddy bear Doll House Inc.
18 inch teddy bear Doll House Inc.
Fish bean bag toy Doll House Inc.
Bird bean bag toy Doll House Inc.
Rabbit bean bag toy Doll House Inc.
Raggedy Ann Doll House Inc.
Raggedy Andy Doll House Inc.
8 inch teddy bear Furball Inc.
12 inch teddy bear Furball Inc.
18 inch teddy bear Furball Inc.
Fish bean bag toy Furball Inc.
Bird bean bag toy Furball Inc.
Rabbit bean bag toy Furball Inc.
Raggedy Ann Furball Inc.
Raggedy Andy Furball Inc.
8 inch teddy bear Dolls R Us
12 inch teddy bear Dolls R Us

pdfMachine
A pdf writer that produces quality PDF files with ease!
18
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
18 inch teddy bear Dolls R Us
Fish bean bag toy Dolls R Us
Bird bean bag toy Dolls R Us
Rabbit bean bag toy Dolls R Us
Raggedy Ann Dolls R Us
Raggedy Andy Dolls R Us

As can be seen from the result set, the cross join can return a potentially huge set with every row from table A is
returned with every rows from table B. This is useful for viewing all possible combinations of data from table
A with data from table B. The cross join is not used very often.

pdfMachine
A pdf writer that produces quality PDF files with ease!
19
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 4.2: INNER JOINS

When to use Inner Joins


Use an inner join to obtain only the records that match the join condition in both tables. Rows with null values will
not appear in the result set.

Example 4.2 Inner Join


Old Style ANSI Style
SELECT P.prod_name, SELECT P.prod_name,
V.vend_name V.vend_name
FROM Vendors V, FROM Vendors V
Products P INNER JOIN Products P ON V.vend_id = P.vend_id
WHERE V.vend_id = P.vend_id

In the above example the keyword INNER is optional since inner join are the default type of join.

Results 4.2
prod_name vend_name
8 inch teddy bear Bears R Us
12 inch teddy bear Bears R Us
18 inch teddy bear Bears R Us
Fish bean bag toy Doll House Inc.
Bird bean bag toy Doll House Inc.
Rabbit bean bag toy Doll House Inc.
Raggedy Ann Doll House Inc.
King doll Fun and Games
Queen doll Fun and Games

The results set for an inner join is the smallest result set that can be returned from a query with a join. The result set
consists of records where both items in the join condition match.

pdfMachine
A pdf writer that produces quality PDF files with ease!
20
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 4.3: LEFT OUTER JOINS

When to use Left Outer Joins


Use a left join when all rows from the table on the left side of the join are required in the results set, as well as
rows that match the join condition.

Example 4.3 Left Join


Old Style ANSI Style
SELECT V.vend_name, SELECT V.vend_name,
P.prod_name P.prod_name
FROM Vendors V, FROM Vendors V
Products P LEFT OUTER JOIN Products P ON V.vend_id = P.vend_id
WHERE V.vend_id *= P.vend_id

In the above example the keyword OUTER is optional. The keyword LEFT refers to the order in which the
tables appear. The Vendors table appears first (to the left of Products) in the FROM clause, so a left join will
return all rows in the Vendors table regardless of the existence of a match in the Products table.

The join condition,


V.vend_id = P.vend_id,
has the Vendors table to the left of the join condition (=).

If the condition where changed to


P.vend_id = V.vend_id
the results would be the same since the Vendors table still appears first in the FROM clause.

Results 4.3
vend_name prod_name
Bears R Us 8 inch teddy bear
Bears R Us 12 inch teddy bear
Bears R Us 18 inch teddy bear
Bear Emporium NULL
Doll House Inc. Fish bean bag toy
Doll House Inc. Bird bean bag toy
Doll House Inc. Rabbit bean bag toy
Doll House Inc. Raggedy Ann
Furball Inc. NULL
Jouets et ours NULL
Fun and Games King doll
Fun and Games Queen doll

The results set for a left join is all rows in the table on the left side of the join regardless of a match and all rows

pdfMachine
A pdf writer that produces quality PDF files with ease!
21
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
not exist. The vendors "Bear Emporium", "Furball Inc.", and "Dolls R Us" do not have any entries in the
Products table and those missing values have been replaced by null values.

Example: Left Join Three Tables


ANSI Style
SELECT *
FROM OrderItems oi
left outer join products p on p.prod_id = oi.prod_id
left outer join vendors v on v.vend_id = p.vend_id

Lesson 4.4: RIGHT OUTER JOINS


When to use Right Outer Joins
Use a right join when all rows from the table on the right side of the join are required in the results set, as well
as rows that match the join condition.

Example 4.4 Right Join


Old Style ANSI Style
SELECT P.prod_name, SELECT P.prod_name,
V.vend_name V.vend_name
FROM Vendors V, FROM Vendors V
Products P RIGHT OUTER JOIN Products P ON V.vend_id = P.vend_id
WHERE V.vend_id =* P.vend_id

In the above example the keyword OUTER is optional. The keyword RIGHT refers to the order in which the tables appe
The Products table appears second (to the right of Vendors) in the FROM clause, so a right join will return all rows in the
Products table regardless of the existence of a match in the Vendors table.

The join condition,


V.vend_id = P.vend_id,
has the Products table to the right of the join condition (=).

If the condition where changed to


P.vend_id = V.vend_id
the results would be the same since the Products table still appears second in the FROM clause.

Results 4.4
vend_name prod_name
Bears R Us 8 inch teddy bear
Bears R Us 12 inch teddy bear
Bears R Us 18 inch teddy bear
Doll House Inc. Fish bean bag toy

pdfMachine
A pdf writer that produces quality PDF files with ease!
22
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Doll House Inc. Bird bean bag toy
Doll House Inc. Rabbit bean bag toy
Doll House Inc. Raggedy Ann
Fun and Games King doll
Fun and Games Queen doll

The results set for a right join is that it returns all rows in the table on the right side of the join regardless of a match. In th
above result set, null values were used where a match did not exist. The product "Raggedy Andy" does not have a
corresponding entry in the Vendors table and that missing value has been replaced by a null value in the results set.

Example: Right Join Three Tables


ANSI Style
SELECT *
FROM OrderItems oi
right outer join products p on p.prod_id = oi.prod_id
right outer join vendors v on v.vend_id = p.vend_id

pdfMachine
A pdf writer that produces quality PDF files with ease!
23
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 4.5: FULL OUTER JOINS

When to use Full Joins


Use a full join when all rows from the table on the left and

right sides of the join are required in the results set, as well as all rows that match the join condition. A full
join is a combination of a left and right join

Example 4.5 Full Join


Old Style ANSI Style
Not supported SELECT P.prod_name,
V.vend_name
FROM Vendors V
FULL JOIN Products P ON V.vend_id = P.vend_id

Results 4.5
prod_name vend_name
8 inch teddy bear Bears R Us
12 inch teddy bear Bears R Us
18 inch teddy bear Bears R Us
Fish bean bag toy Doll House Inc.
Bird bean bag toy Doll House Inc.
Rabbit bean bag toy Doll House Inc.
Raggedy Ann Doll House Inc.
NULL Bear Emporium
NULL Furball Inc.
NULL Jouets et ours
King doll Fun and Games
Queen doll Fun and Games

The results set for a full join returns all rows in the table on the left side of the join and the right side of a join
regardless of a match. If you compare Results 4.5 with Results 4.3 and 4.4 you will see that the FULL join
returned everything the left join returned and everything the right join returned. The null values indicate that
the Product "Raggedy Andy" does not have a corresponding entry in the Vendors table and thus the vendor of
the "Raggedy Andy" product is not known. The Products table does not contain any products sold by the
"Bear Emporium", "Furball Inc.", and "Dolls R Us" vendors, so nulls were returned in their place.

Lesson 4.6: Joining Multiple tables

pdfMachine
A pdf writer that produces quality PDF files with ease!
24
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Example 4.6 shows a query that joins every table in the schema. Each join condition is based on columns that
are present in both tables involved in the join. An individual join condition involves two tables; all join
conditions taken together can involve more than two tables.

Example 4.6
Old Style ANSI Style
SELECT P.prod_name, SELECT P.prod_name,
V.vend_name, V.vend_name,
OI.quantity, OI.quantity,
O.order_date, O.order_date,
C.cust_name C.cust_name
FROM Vendors V, FROM Vendors V
Products P, JOIN Products P ON V.vend_id = P.vend_id
OrderItems OI, JOIN OrderItems OI ON OI.prod_id = P.prod_id
Orders O, JOIN Orders O ON O.order_num = OI.order_num
Customers C JOIN Customers C ON C.cust_id = O.cust_Id
WHERE V.vend_id = P.vend_id
AND P.prod_id = OI.prod_id
AND OI.order_num = O.order_num
AND O.cust_id = C.cust_Id

Try running the above query yourself to view the result set. Since there are fourteen (14) records in the
OrderItems table, you should get eighteen rows in the results set. The Orders table has the most matching
records of all the tables joined, that is why the Orders table determines how many rows are in the result set.

pdfMachine
A pdf writer that produces quality PDF files with ease!
25
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 5: Aggregation functions

Introduction

Aggregation functions are used to summarize data. These functions are used when the details of the data are not
required. With aggregation functions you can count the number of records that match a given criteria, get the
sum of all values in a column, get the average of all values in a column, or determine what the minimum and
maximum values are for a column.

Lesson 5.1: COUNT


Used to determine the number of rows in a table or the number of values for a specific column.

Example 5.1 COUNT(*)

SELECT COUNT(*) AS Prod_Count


FROM Products;

Results 5.1
Prod_Count
10

Since there are ten (10) rows in the Products table a count of ten (10) is returned.

Example 5.2 COUNT(vend_id)

SELECT COUNT(vend_id) AS Prod_Count


FROM Products;

Results 5.2
Prod_Count
9

There are ten (10) rows in the table but only nine (9) have a vend_id that is not null. Example 5.2 is equivalent
to Example 5.3.

Example 5.3 COUNT(*)

SELECT COUNT(*) AS Prod_Count


FROM Products
WHERE vend_id IS NOT NULL;

Both Examples 5.2 and 5.3 return a count of seven (7).

pdfMachine
A pdf writer that produces quality PDF files with ease!
26
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 5.2: SUM
Returns the sum of all values in a given column. Example 5.4 returns the sum of all prices in the products table.

Example 5.4 SUM(prod_price)

SELECT SUM(prod_price) AS Sum_Price


FROM Products;

Results 5.4
Sum_Price
61.41

To get the total cost of all items ordered by a given customer Example 5.5 expands on Example 5.6 with the
addition of joins and a where clause.

Example 5.5 SUM(P.prod_price)


Old Style ANSI Style
SELECT SUM(P.prod_price) as Sum_Price SELECT SUM(P.prod_price) as Sum_Price
FROM Products P, FROM Products P
OrderItems OI, JOIN OrderItems OI ON OI.prod_id = P.prod_id
Orders O, JOIN Orders O ON O.order_num = OI.order_num
Customers C JOIN Customers C ON C.cust_id = O.cust_id
WHERE OI.prod_id = P.prod_id WHERE C.cust_id = 1000000001
AND O.order_num = OI.order_num
AND C.cust_id = O.cust_id
AND C.cust_id = 1000000001

The aggregation function MIN is used with the customer name, MIN(C.cust_name), because when an
aggregation function is used for one column, all columns must be aggregated. The correct customer name is
returned only because the customer id is unique. If the product name where included in the query the correct
name would NOT be returned because there is more than one product associated with the given customer.
More on that when we get to MIN and MAX and how they work on character strings.

Results 5.5
Sum_Price
28.45

Results 5.5 shows that the total cost to the customer is $28.45.

Lesson 5.3: AVG


Returns the average value of a column. Example 5.6 shows the average price of the products ordered by the
"Village Toys" customer.

pdfMachine
A pdf writer that produces quality PDF files with ease!
27
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Example 5.6 AVG(P.prod_price)
Old Style ANSI Style
SELECT AVG(P.prod_price) as Avg_Price SELECT Avg(P.prod_price) as Avg_Price
FROM Products P, FROM Products P
OrderItems OI, JOIN OrderItems OI ON OI.prod_id = P.prod_id
Orders O, JOIN Orders O ON O.order_num = OI.order_num
Customers C JOIN Customers C ON C.cust_id = O.cust_id
WHERE OI.prod_id = P.prod_id WHERE C.cust_id = 1000000001
AND O.order_num = OI.order_num
AND C.cust_id = O.cust_id
AND C.cust_id = 1000000001

Results 5.6
Avg_Price
5.69

Results 5.6 shows that the average price of an item purchased by the "Village Toys" customer is $5.69.

Lesson 5.4: MIN


Returns the minimum value in a column. MIN and MAX work on string types (char, varchar) as well as
numeric types.

Example 5.7 MIN(P.prod_price)


Old Style ANSI Style
SELECT MIN(P.prod_price) AS Min_Price SELECT MIN(P.prod_price) AS Min_Price
FROM Products P, FROM Products P
OrderItems OI, JOIN OrderItems OI ON OI.prod_id = P.prod_id
Orders O, JOIN Orders O ON O.order_num = OI.order_num
Customers C JOIN Customers C ON C.cust_id = O.cust_id
WHERE OI.prod_id = P.prod_id WHERE C.cust_id = 1000000001
AND O.order_num = OI.order_num
AND C.cust_id = O.cust_id
AND C.cust_id = 1000000001

pdfMachine
A pdf writer that produces quality PDF files with ease!
28
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Results 5.7
Min_Price
3.49

Lesson 5.5: MAX


Returns the minimum value in a column. MAX and MIN work on string types (char, varchar) as well as
numeric types.

Example 5.8 MAX(P.prod_price)


Old Style ANSI Style
SELECT MAX(P.prod_price) AS Max_Price SELECT Max(P.prod_price) AS Max_Price
FROM Products P, FROM Products P
OrderItems OI, JOIN OrderItems OI ON OI.prod_id = P.prod_id
Orders O, JOIN Orders O ON O.order_num = OI.order_num
Customers C JOIN Customers C ON C.cust_id = O.cust_id
WHERE OI.prod_id = P.prod_id WHERE C.cust_id = 1000000001
AND O.order_num = OI.order_num
AND C.cust_id = O.cust_id
AND C.cust_id = 1000000001

Results 5.8
Max_Price
11.99

pdfMachine
A pdf writer that produces quality PDF files with ease!
29
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 5.6: MIN, MAX and Strings
In Examples 5.6 and 5.7 we obtained the minimum and maximum prices for items
purchased for the "Village Toys" customer. Suppose we wanted to get the name of the
lowest price product along with the price, how would this be accomplished?

Example 5.9 is a query that returns all products purchased by the "Village Toys" customer.

Old Style ANSI Style


SELECT P.prod_price, SELECT P.prod_price,
P.prod_name, P.prod_name,
C.cust_name C.cust_name
FROM Products P, FROM Products P
OrderItems OI, JOIN OrderItems OI ON
Orders O, OI.prod_id = P.prod_id
Customers C JOIN Orders O ON
WHERE OI.prod_id = P.prod_id O.order_num = OI.order_num
AND O.order_num = OI.order_num JOIN Customers C ON
AND C.cust_id = O.cust_id C.cust_id = O.cust_id
AND C.cust_id = 1000000001 WHERE C.cust_id = 1000000001

Results 5.9
prod_price prod_name cust_name
5.99 8 inch teddy bear Village Toys
11.99 18 inch teddy bear Village Toys
3.49 Fish bean bag toy Village Toys
3.49 Bird bean bag toy Village Toys
3.49 Rabbit bean bag toy Village Toys

Results 5.9 shows that the customer name for all products is the same, due to the
condition in the WHERE clause, so using MIN or MAX on the customer name would
not have any effect. However, if we want to get a product name that matches the MIN
or MAX value we can use MIN(P.prod_name) or MAX(P.prod_name).

Example 5.10 MIN(P.prod_name) and MAX(P.prod_name)


Old Style ANSI Style
SELECT MAX(P.prod_price) AS Max_Price, SELECT MAX(P.prod_price) AS Max_Price,
MIN(P.prod_price) AS Min_Price, MIN(P.prod_price) AS Min_Price,
MAX(P.prod_name) AS Max_Prod_Name, MAX(P.prod_name) AS Max_Prod_Name,

pdfMachine
A pdf writer that produces quality PDF files with ease!
30
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
MIN(P.prod_name) AS Min_Prod_Name, MIN(P.prod_name) AS Min_Prod_Name,
MAX(C.cust_name) AS Cust_Name_Max, MAX(C.cust_name) AS Cust_Name_Max,
MIN(C.cust_name) AS Cust_Name_Min MIN(C.cust_name) AS Cust_Name_Min
FROM Products P, FROM Products P
OrderItems OI, JOIN OrderItems OI ON
Orders O, OI.prod_id = P.prod_id
Customers C JOIN Orders O ON
WHERE OI.prod_id = P.prod_id O.order_num = OI.order_num
AND O.order_num = OI.order_num JOIN Customers C ON
AND C.cust_id = O.cust_id C.cust_id = O.cust_id
AND C.cust_id = 1000000001 WHERE C.cust_id = 1000000001

Results 5.10
Max_Price Min_Price Max_Prod_Name Min_Prod_Name Cust_Name_Max Cust_Name_Min

11.99 3.49 Rabbit bean bag toy 18 inch teddy bear Village Toys Village Toys

The maximum price and the minimum price are return as are the maximum and minimum product names and
customer names. Note that the maximum product name does NOT correspond to the maximum price and the
minimum product name does NOT correspond to the minimum price. How do we get the name of the
cheapest and/or most expensive product? We can use a sub-query.

pdfMachine
A pdf writer that produces quality PDF files with ease!
31
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 5.7: Sub-queries
Sub-queries are used in conjunction with a main query. Sub-queries are used when a specific condition
needs to be met and filtering the main query to meet this condition would not produce the desired
results. Sub-queries are exactly like main queries and can be used alone. The only difference is that
sub-queries are often designed to return a single column value in order for that value to be compared to a
value in the main query.

In Example 5.11, the query is going to return product information for products that were ordered by
"Village Toys" and "Fun4All" (cust_id = 1000000003).

Example 5.11 Sub-query


Old Style ANSI Style
SELECT MAX(P.prod_price) AS Max_Price, SELECT MAX(P.prod_price) AS Max_Price,
MIN(P.Prod_Name) AS Prod_Name, MIN(P.prod_name) AS Prod_Name,
MAX(C.cust_name) AS Cust_Name MIN(C.cust_name) AS Cust_Name_Min
FROM Products P, FROM Products P
OrderItems OI, JOIN OrderItems OI ON OI.prod_id = P.prod_id
Orders O, JOIN Orders O ON O.order_num = OI.order_num
Customers C JOIN Customers C ON C.cust_id = O.cust_id
WHERE OI.prod_id = P.prod_id WHERE C.cust_id = 1000000001
AND O.order_num = OI.order_num AND P.prod_id IN
AND C.cust_id = O.cust_id (SELECT P.prod_id
AND C.cust_id = 1000000001 FROM Products P
AND P.prod_id IN JOIN OrderItems OI ON OI.prod_id = P.prod_id
(SELECT P.prod_id JOIN Orders O ON O.order_num = OI.order_num
FROM Products P, JOIN Customers C ON C.cust_id = O.cust_id
OrderItems OI, WHERE C.cust_id = 1000000003)
Orders O,
Customers C
WHERE OI.prod_id = P.prod_id
AND O.order_num = OI.order_num
AND C.cust_id = O.cust_id
AND C.cust_id = 1000000003 )

Results 5.11
Max_Price Prod_Name Cust_Name
11.99 18 inch teddy bear Village Toys

The sub-query in Example 5.11 is going to return the value "11.99" which is the same result returned in
Example 5.8. The difference here is that the sub-query only returns a single column whereas Example
5.8 returns the maximum price and the customer name. Sub-queries can be used any place a regular
column value would be used provided that the sub-query returns a single column value. If the query in
Example 5.8 were used in this example, the main query would not have known which column to use
(Max_Price or Cust_Name) in the WHERE clause.

pdfMachine
A pdf writer that produces quality PDF files with ease!
32
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 5.8: GROUP BY
Used to combine records with identical values in the specified field list into a single record. If aggregate
functions are included, the result is a summary value created for each record. In Example 5.9 three records are
returned with the value of 3.49. Example 5.11 shows the use of GROUP BY on a query identical to Example
5.9.

Example 5.12 GROUP BY C.Cust_Name, P.prod_price


Old Style ANSI Style
SELECT SUM(P.prod_price) Prod_price, SELECT SUM(P.prod_price) Prod_price,
C.cust_name C.cust_name
FROM Products P, FROM Products P
OrderItems OI, JOIN OrderItems OI ON OI.prod_id = P.prod_id
Orders O, JOIN Orders O ON O.order_num = OI.order_num
Customers C JOIN Customers C ON C.cust_id = O.cust_id
WHERE OI.prod_id = P.prod_id GROUP BY C.Cust_Name
AND O.order_num = OI.order_num
AND C.cust_id = O.cust_id
GROUP BY C.Cust_Name

Results 5.12
prod_price cust_name
54.42 Fun4All
28.45 Village Toys
27.45 The Toy Store

The columns in the GROUP BY clause determine how the summery data will be organized. Every column that
is in the SELECT clause must be present in the GROUP BY clause. GROUP BY clauses appear after the
WHERE clause, or after the FROM clause if the query does not have a WHERE clause, and before ORDER BY
as can be seen in Example 5.12.

Example 5.13 GROUP BY OI.order_num


Old Style ANSI Style
SELECT O.cust_id, SELECT O.cust_id,
COUNT(*) AS Order_Count COUNT(*) AS Order_Count
FROM Orders O, FROM Orders O
OrderItems OI JOIN OrderItems OI ON OI.order_num = O.order_num
WHERE OI.order_num = O.order_num GROUP BY O.cust_id
GROUP BY O.cust_id ORDER BY Order_Count
ORDER BY Order_Count

pdfMachine
A pdf writer that produces quality PDF files with ease!
33
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Results 5.13
cust_id Order_Count
1000000003 3
1000000001 5
1000000004 5
1000000005 5

The query in Example 5.12 gets the number of orders per customer.

Lesson 5.9: HAVING


Similar to the WHERE clause but used with the GROUP BY clause. HAVING is used to filter the results of a
GROUP BY. Suppose we want to know which customers have ordered five or more items. We can do this by
adding HAVING after GROUP BY.

Example 5.14 GROUP BY.... HAVING


Old Style ANSI Style
SELECT O.cust_id, SELECT O.cust_id,
COUNT(*) AS Order_Count COUNT(*) AS Order_Count
FROM Orders O, FROM Orders O
OrderItems OI JOIN OrderItems OI ON OI.order_num = O.order_num
WHERE OI.order_num = O.order_num GROUP BY O.cust_id
GROUP BY O.cust_id HAVING COUNT(*) >= 5
HAVING COUNT(*) >= 5

Results 5.14
cust_id Order_Count
1000000001 5
1000000004 5
1000000005 5

The results return all customers that purchased five or more items. Just like the WHERE clause HAVING can
be used to filter the results on multiple conditions. In Example 5.14 HAVING is used in conjunction with
BETWEEN.

pdfMachine
A pdf writer that produces quality PDF files with ease!
34
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Example 5.15
Old Style ANSI Style
SELECT O.cust_id, SELECT O.cust_id,
SUM(P.prod_price) AS Sum_Price, SUM(P.prod_price) AS Sum_Price,
MAX(P.prod_price) AS Max_Price MAX(P.prod_price) AS Max_Price
FROM Orders O, FROM Orders O
OrderItems OI, JOIN OrderItems OI ON OI.order_num = O.order_num
Products P JOIN Products P ON P.prod_id = OI.prod_id
WHERE OI.order_num = O.order_num GROUP BY O.cust_id
AND P.prod_id = OI.prod_id HAVING SUM(P.prod_price) BETWEEN 28 AND 30
GROUP BY O.cust_id AND MAX(P.prod_price) > 11
HAVING SUM(P.prod_price) BETWEEN 28 AND 30
AND MAX(P.prod_price) > 11

Results 5.15
Cust_id Sum_Price Max_Price
1000000001 28.45 11.99

As can be seen from Results 5.14 the HAVING clause returns the customer that has ordered a product with a
maximum price that is greater than eleven (11) and that same customer has ordered items with a total cost
between twenty-eight (28) and thirty (30).

Lesson 6: CASE/DECODE
The CASE function in Transact-SQL (SQL-Server database) allows alternative values to be displayed depending
on a column's values. If you are using an Oracle database the DECODE function would be a counterpart to the
CASE function.

Example 6.1 CASE vend_name


Transact-SQL Oracle (Not supported by SQL-Tutor)
SELECT vend_name, SELECT vend_name,
CASE vend_state DECODE(vend_state,
WHEN 'CA' THEN 'California' 'CA', 'California',
WHEN 'MI' THEN 'Michigan' 'MI', 'Michigan',
WHEN 'NY' THEN 'New York' 'NY', 'New York',
WHEN 'OH' THEN 'Ohio' 'OH', 'Ohio',
WHEN 'WA' THEN 'Washington' 'WA',
ELSE 'Unknown' 'Washington',
END AS vend_state 'Unknown') AS
FROM vendors vend_state
FROM vendors

The CASE function takes a column as input, in Example 6.1 the column is vend_state. The WHEN clause
states that if the value of vend_state is "CA" then display "California", if the value of vend_state is "MI"
then display "Michigan" and so on. If a value for vend_state is not one of the comparison values listed in
the case statement, "CA", "MI", "NY", "OH", or "WA", then the CASE function will return "Unknown".
The DECODE function in Oracle operates in a similar manner.

Once the CASE function finds a condition, it returns the results and does not test the remaining conditions.
You should therefore place conditions that are LEAST likely to be met first.

pdfMachine
A pdf writer that produces quality PDF files with ease!
35
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Results 6.1
vend_name vend_state
Bears R Us Michigan
Bear Emporium Ohio
Doll House Inc. California
Furball Inc. New York
Dolls R Us Washington
Jouets et ours Unknown

The comparison conditions in Example 6.1 is equality: If vend_state = CA' Then 'California'. To use another
comparison condition (>, <, <>, >=, <=) the statement would need to be written differently.

Example 6.2 CASE


Transact-SQL Oracle (Not supported by SQL-Tutor)
SELECT COUNT(OI.order_item) AS Order_Count, SELECT COUNT(OI.order_item) AS Order_Count,
CASE DECODE(COUNT(OI.order_item),
WHEN COUNT(OI.order_item) = 0 0, 'Zero purchases',
THEN 'Zero purchases' 1, 'First time customer',
WHEN COUNT(OI.order_item) = 1 2, 'Returning customer',
THEN 'First time customer' 'Preferred customer') AS Customer_Status
WHEN COUNT(OI.order_item) = 2 FROM OrderItems OI,
THEN 'Returning customer' Products P,
WHEN COUNT(OI.order_item) >= 3 Orders O,
THEN 'Preferred customer' Customers C
END AS Customer_Status WHERE P.prod_id = OI.prod_id
FROM OrderItems OI AND OI.order_num = O.order_num
JOIN Products P ON P.prod_id = OI.prod_id AND C.cust_id = O.cust_id
JOIN Orders O ON OI.order_num = GROUP BY OI.order_item
O.order_num
JOIN Customers C ON C.cust_id = O.cust_id
GROUP BY OI.order_item

Results 6.2
Order_Count Customer_Status
5 Preferred customer
5 Preferred customer
4 Preferred customer
2 Returning customer
2 Returning customer

Oracle's DECODE function does not allow for any comparisons other than equal. The ELSE part of the CASE
function is optional. For DECODE, the last entry is not optional and needs to be provided.

Lesson 7: UNION

pdfMachine
A pdf writer that produces quality PDF files with ease!
36
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
UNION combines two, or more, queries to produce a single results set. In order to combine
these queries certain conditions need to be met:

1. Column names in both queries must match.


2. The order in which the columns appear in both queries must mach.
3. The data type of each column must match.

Example 7.1 UNION


Old Style ANSI Style
SELECT C.cust_name, SELECT C.cust_name,
P.prod_price P.prod_price
FROM OrderItems OI, FROM OrderItems OI
Products P, JOIN Products P ON P.prod_id = OI.prod_id
Orders O, JOIN Orders O ON OI.order_num = O.order_num
Customers C JOIN Customers C ON C.cust_id = O.cust_id
WHERE P.prod_id = OI.prod_id WHERE C.cust_id = 1000000001
AND OI.order_num = O.order_num AND P.prod_id = 'BR03'
AND C.cust_id = O.cust_id UNION
AND C.cust_id = 1000000001 SELECT C.cust_name AS Cust_Name,
AND P.prod_id = 'BR03' P.prod_price
UNION FROM OrderItems OI
SELECT C.cust_name AS Cust_Name, JOIN Products P ON P.prod_id = OI.prod_id
P.prod_price JOIN Orders O ON OI.order_num = O.order_num
FROM OrderItems OI, JOIN Customers C ON C.cust_id = O.cust_id
Products P, WHERE C.cust_id = 1000000004
Orders O, AND P.prod_id = 'BNBG01'
Customers C
WHERE P.prod_id = OI.prod_id
AND OI.order_num = O.order_num
AND C.cust_id = O.cust_id
AND C.cust_id = 1000000004
AND P.prod_id = 'BNBG01'

Results 7.1
Cust_Name prod_price
Fun4All 3.49
Village Toys 11.99

In Example 7.1 we are combining two queries in order to obtain specific results. In Example 7.2 a union is
not used. As you can see, the results are not the same as in Example 7.1.

Example 7.2
Old Style ANSI Style
SELECT DISTINCT C.cust_name, SELECT DISTINCT C.cust_name,
P.prod_price P.prod_price
FROM OrderItems OI, FROM OrderItems OI
Products P, JOIN Products P ON P.prod_id = OI.prod_id
Orders O, JOIN Orders O ON OI.order_num = O.order_num
Customers C JOIN Customers C ON C.cust_id = O.cust_id
WHERE P.prod_id = OI.prod_id WHERE C.cust_id IN ( 1000000001, 1000000004)
AND OI.order_num = O.order_num AND P.prod_id IN ( 'BNBG01', 'BR03' )
AND C.cust_id = O.cust_id
AND C.cust_id IN ( 1000000001, 1000000004)
AND P.prod_id IN ( 'BNBG01', 'BR03' )

pdfMachine
A pdf writer that produces quality PDF files with ease!
37
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Results 7.2

The price for product 'BNBG01' is returned for "Fun4All" as well as "Village Toys".

Cust_Name prod_price
Fun4All 3.49
Fun4All 11.99
Village Toys 11.99

Example 7.3 Place Holders


Old Style ANSI Style
SELECT C.cust_name AS Customer_1, SELECT C.cust_name AS Customer_1,
P.prod_price AS Price_1, P.prod_price AS Price_1,
'' AS Customer_2, '' AS Customer_2,
0 AS Price_2 0 AS Price_2
FROM OrderItems OI, FROM OrderItems OI
Products P, JOIN Products P ON
Orders O, P.prod_id = OI.prod_id
Customers C JOIN Orders O ON
WHERE P.prod_id = OI.prod_id OI.order_num = O.order_num
AND OI.order_num = O.order_num JOIN Customers C ON
AND C.cust_id = O.cust_id C.cust_id = O.cust_id
AND C.cust_id = 1000000001 WHERE C.cust_id = 1000000001
AND P.prod_id = 'BR03' AND P.prod_id = 'BR03'
UNION UNION
SELECT '' AS Customer_1 , SELECT '' AS Customer_1 ,
0 AS Price_1, 0 AS Price_1,
C.cust_name AS Customer_2, C.cust_name AS Customer_2,
P.prod_price AS Price_2 P.prod_price AS Price_2
FROM OrderItems OI, FROM OrderItems OI
Products P, JOIN Products P ON
Orders O, P.prod_id = OI.prod_id
Customers C JOIN Orders O ON
WHERE P.prod_id = OI.prod_id OI.order_num = O.order_num
AND OI.order_num = O.order_num JOIN Customers C ON
AND C.cust_id = O.cust_id C.cust_id = O.cust_id
AND C.cust_id = 1000000004 WHERE C.cust_id = 1000000004
AND P.prod_id = 'BNBG01' AND P.prod_id = 'BNBG01'

In the first query Customer_2 and Price_2 are considered to be dummy columns or place holders; the only
reason they are placed there is to satisfy the UNION condition that column names must match. A zero is used
as a dummy value for Price_2 because prod_price is a numeric field and the data type for Price_1 in the first
query and Price_2 in the second query must match.

Results 7.3
Customer_1 Price_1 Customer_2 Price_2
.00 Fun4All 3.49
The Toy Store 11.99 .00

UNION is this case was used to format the results and present them in a more readable fashion. The place
holders where used to separated the results.

pdfMachine
A pdf writer that produces quality PDF files with ease!
38
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 8: Data Type Conversions
Converting data from one data type to another is often necessary. In order to accomplish this task database
systems provide conversion functions. This lesson will present some of the most common conversion
functions used in SQL.

SQL Server
SQL Server offers two conversion functions, CAST and CONVERT. CONVERT is a more versatile
function than CAST, and allows users to specify the style of the output with respect to date conversions.
CAST is preferred over CONVERT because it is based on the SQL-92 standard.

Example 8.1 Query without data conversions


SELECT GetDate() AS System_Date,
order_date
FROM Orders

Results 8.1
System_Date order_date
2007-04-21 14:33:10.670 5/1/2004 12:00AM
2007-04-21 14:33:10.670 1/12/2004 12:00AM
2007-04-21 14:33:10.670 1/30/2004 12:00AM
2007-04-21 14:33:10.670 2/3/2004 12:00AM
2007-04-21 14:33:10.670 2/8/2004 12:00AM

The order_date value is not in the standard month/day/year format that most people are used to seeing. In
Example 8.2, CAST will be used to convert the order_date and system date to a character string. The
GetDate() function returns the current system date and time. The default format for the datetime data type is
"mm/dd/yyyy hh:mm:ss" which stands for:

"Two digit Month/Two digit Day/Four digit Year Hours:Minutes:Seconds:Milleseconds"

Example 8.2 CAST


SELECT CAST(GetDate() AS char) AS System_Date,
CAST(order_date as char) as order_date
FROM Orders

Results 8.2
System_Date order_date
Apr 21 2007 2:32PM 5/1/2004
Apr 21 2007 2:32PM 1/12/2004

pdfMachine
A pdf writer that produces quality PDF files with ease!
39
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Apr 21 2007 2:32PM 1/30/2004
Apr 21 2007 2:32PM 2/3/2004
Apr 21 2007 2:32PM 2/8/2004

In Example 8.2 order_date was converted to a character string, cust_id was converted to an integer, and the
string '04/18/2004' was converted to a date. CAST changes the default date format to "mon d yyyy
hh:mmAM" which stands for:

"Three letter Month One Digit Day Four digit Year Hours:MinutesAM/PM"

In Example 8.3 will do the same thing using CONVERT.

Example 8.3 CONVERT


SELECT CONVERT(char,GetDate(), 101) AS System_Date,
CONVERT(varchar(15),order_date, 101) AS Order_Date
FROM Orders

Results 8.3
System_Date Order_Date
04/21/2007 05/01/2004
04/21/2007 01/12/2004
04/21/2007 01/30/2004
04/21/2007 02/03/2004
04/21/2007 02/08/2004

The difference between Results 8.3 and Results 8.2 is the format of the Order_Date. The CONVERT
function's third parameter determines how the date will look. In Example 8.3 the value 101 states that the
date should be in the "mm/dd/yyyy" format. For more information on the use of the CONVERT function,
refer to Microsoft's on-line documentation for CAST and CONVERT (T-SQL).

Oracle

Oracle offers five conversion functions: TO_NUMBER, TO_CHAR, TO_DATE as well as CAST and
CONVERT.

TO_NUMBER attempts to convert whatever value is passed in to a number type, TO_CHAR converts the
value to a character type and TO_DATE attempts to convert a string value to a date type. Any number or

pdfMachine
A pdf writer that produces quality PDF files with ease!
40
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
date can be converted to a character; character strings that contain alphabetical characters, or punctuation,
can not be converted to a number. String values that do not represent valid dates can not be converted to a
date.

For example TO_NUMBER('1234_B') would fail because of the letter "B" and the underscore.
TO_DATE('02/30/20001', 'mm/dd/yyyy') would fail because the month of February does not have thirty (30)
days.

Example 8.4 Query without data conversions


SELECT order_date,
SYSDATE AS System_Date
FROM Orders;

Results 8.4
ORDER_DATE SYSTEM_DATE
01-MAY-04 04-21-2007
12-JAN-04 04-21-2007
30-JAN-04 04-21-2007
03-FEB-04 04-21-2007
08-FEB-04 04-21-2007

The output from Example 8.4 appears as it would if you had run the query using SQL Plus in an Oracle
environment. The default date format for Oracle is "dd-mon-yy" which stands for:

"Two Digit Day-Three letter Month-Four Digit Year"

The SYSDATE function returns the current system date and time. The time is stored in Oracle but is only
displayed if the query specifies that it should be displayed.

Example 8.5 TO_CHAR, TO_NUMBER, TO_DATE


SELECT TO_CHAR(order_date, 'mm/dd/yyyy') AS Order_Date,
TO_NUMBER(cust_id) AS cust_id,
TO_DATE('04/18/2004','mm/dd/yyyy') AS System_Date
FROM Orders

pdfMachine
A pdf writer that produces quality PDF files with ease!
41
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Results 8.5
ORDER_DATE SYSTEM_DATE
05/01/2004 04/21/2007
01/12/2004 04/21/2007
01/30/2004 04/21/2007
02/03/2004 04/21/2007
02/08/2004 04/21/2007

For more information on the use of the Oracle data conversion functions, refer to Oracle's on-line
documentation which can be found at Oracle8i SQL Reference (Lists all SQL functions supported by
Oracle).

pdfMachine
A pdf writer that produces quality PDF files with ease!
42
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 9: VIEWS
A database View is virtual table that is populated with the results of a query. Put another
way, a view is a query that is stored in the database. Views can be queried just as tables
can be queried.

Example 9.1 View Creation


SQL Server Oracle
CREATE VIEW vVendor_Addresses AS CREATE OR REPLACE VIEW vVendor_Addresses AS
SELECT Vend_Id, SELECT Vend_Id,
LTRIM(RTRIM(vend_name)) AS Vend_Name, LTRIM(RTRIM(vend_name)) AS Vend_Name,
LTRIM(RTRIM(vend_address)) + ', ' + LTRIM(RTRIM(vend_address)) || ', ' ||
LTRIM(RTRIM(vend_city)) + ' ' + LTRIM(RTRIM(vend_city)) || ' ' ||
LTRIM(RTRIM(vend_state)) + ', ' + LTRIM(RTRIM(vend_state)) || ', ' ||
vend_zip AS Vend_Address vend_zip AS Vend_Address
FROM Vendors FROM Vendors

After the view Vendor_Addresses is created the results produced by that view can be
accessed through a query. Notice the use of the key words "CREATE OR REPLACE
VIEW" in Oracle and "CREATE VIEW" in SQL Server. "CREATE OR REPLACE"
allows users to change a view (re-create the view) without dropping the view first. In SQL
Server, a view must be dropped first with a "DROP VIEW vVendor_Addresses", and then
re-create it using "CREATE VIEW".

Example 9.2 Querying Views


SELECT *
FROM vVendor_Addresses

Results 9.2
Vend_Id Vend_Name Vend_Address
BRS01 Bears R Us 123 Main Street, Bear Town MI, 44444
BRE02 Bear Emporium 500 Park Street, Anytown OH, 44333
DLL01 Doll House Inc. 555 High Street, Dollsville CA, 99999
FRB01 Furball Inc. 1000 5th Avenue, New York NY, 11111
FNG01 Fun and Games Null
JTS01 Jouets et ours Null

Querying a view is exactly like querying a table: all the SQL syntax rules apply learned in
Lessons 2 - 7.

Inserting and updating data into views and/or tables will be discussed in Lesson 10.

Views that do not contain aggregates or concatenated fields can have data inserts and updates. In the case of

pdfMachine
A pdf writer that produces quality PDF files with ease!
43
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
vVendor_Addresses inserts and updates are not allowed due to the Vend_Address field. When inserting into
a view the constraint conditions that affect the insert are the same constraint condition that affect the table(s).
If an row were inserted

Lesson 10: CREATE TABLE, ALTER TABLE


In order for a database to be of any use it must have tables. Table can be created, dropped, and altered. Here, you will
learn the syntax for creating and altering tables.

CREATE TABLE
The basic syntax for creating a table is

CREATE TABLE table_name


(
column_name1 data_type [constraints],
column_name2 data_type [constraints],
.....
column_nameN data_type [constraints]
)

column_name and data_type are mandatory fields, constraints are optional.

Example 10.1 The Orders Table

CREATE TABLE Orders


(
order_num INTEGER NOT NULL,
order_date DATETIME NOT NULL,
cust_id CHAR(10) NOT NULL
);

The Orders table has three (3) columns and all of them have a NOT NULL constraint. This means that any insert into the
table must populate all three (3) columns.

Data Types
SQL Server Oracle
NUMERIC NUMBER
TINYINT: For numbers between 1 and 255. NUMBER(3): For numbers between -999 and 999.

pdfMachine
A pdf writer that produces quality PDF files with ease!
44
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
SMALLINT: For numbers between -32768 and 32767. NUMBER(5): For numbers between -99999 and 99999.
INTEGER or INT: For numbers between -2,147,483,648 and
NUMBER(10): For numbers between -9,999,999,999 and 9,999,999,999
2,147,483,647.
float: For numbers that require precision. NUMBER(n, m): n is the total number of digits allowed, and m is the number
of decimals places allowed. For example Number(5,2) allows numbers
between -999.99 and 999.99.
MONEY: For numbers that require only two decimal places. NUMBER(n, 2): For numbers that require only two decimal places.
CHAR: Character fields that are padded with spaces. CHAR: Character fields that are padded with spaces.
VARCHAR: Variable character fields. VARCHAR2: Variable character fields.
VARBINARY: Binary data. RAW : Binary data.
IMAGE: Binary Large Objects (BLOB). LONG RAW: Binary Large Objects (BLOB).
DATETIME: Date/Time information. DATE: Date/Time information.

Both char and varchar store string data types. The advantage of using char is faster access time: a char(10) column will a
have ten characters even if fewer than ten are entered into the field. The remaining length of the field is padded with spa
advantage of using varchar is that fields are not padded with spaces, this simplifies comparisons between character fields
saves some storage space as well.

Constraints
Constraints Type Function
NOT NULL During an INSERT or an UPDATE, data must be entered into this column,
a null value is not allowed.
CHECK Determines which values can be entered into a field. For example CHECK
( month_days BETWEEN 1 AND 31) would prevent users from entering a
value less than 1 or greater than 31 into a column called month_days.
PRIMARY KEY (Oracle) or IDENTITY (SQL Server) Prevents duplicate values from being entered into the column.
FOREIGN KEY Prevents the insertion of records into a child table if the parent table does
not contain a reference to those records (maintains referential integrity).

ALTER TABLE

The ALTER TABLE command is used to make changes to an existing table thus removing the need for dropping the tab
re-creating it. Using the ALTER command columns can be added, have constraints added or removed from them , and h
column data type changed. Some systems allow users to delete columns as well. Certain restrictions apply to changing t
example adding a NOT NULL constraint to a column that is currently populated with null values is not allowed; the new
would need to be populated for all rows in the table first, then the NOT NULL constraint can be applied.

The syntax for the ALTER TABLE command is as follows:

To change a column ALTER TABLE table_name ALTER COLUMN column_name change

Example: ALTER TABLE Orders ALTER COLUMN cust_id VARCHAR(50)

To add a column ALTER TABLE table_name ADD column_name data_type

pdfMachine
A pdf writer that produces quality PDF files with ease!
45
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Example: ALTER TABLE Orders ADD total_sale MONEY
To add a NOT NULL
ALTER TABLE table_name ALTER COLUMN column_name data_type NOT NULL
constraint
Example: ALTER TABLE Orders ALTER COLUMN total_sale MONEY NOT NULL

More information on ALTER TABLE for SQL Server and Oracle is available on the web.

Lesson 11: INSERT


Having tables in a database is of little use if data can't be placed in those tables. The INSERT command is used to add d
database tables. The syntax of the INSERT command is as follows:

Method One:
INSERT INTO table_name( column_name1, column_name2, ....... column_nameN)
VALUES( column_value1, column_value2, ....... column_valueN)
Method Two:
INSERT INTO table_name VALUES( column_value1, column_value2, ....... column_valueN)

Method One:

Each column of the table that is to be affected by the insert is listed and then the values are specified. Using this method
column values do not to be placed in the same order as they appear in the table. The value must appear in the same orde
the column names.

Method Two

Using this method, column names do not need to be specified. However, the column values must appear in the VALUE
clause in same order that they appear in the table.

Constraints
Table constraints are designed to ensure data quality. For example, allowing a null value for a customers address is not
conducive to delivering the merchandise to the customer. When INSERTING data into table directly, or indirectly throu
views, constraints must be taken into consideration:

NOT NULL Leaving out a column with this constraint in an INSERT will cause an error. Any column with a NOT
NULL constraint must be populated.
CHECK Values that are not within the CHECK parameters will not be allowed. For example, if a column has a
constraint that only allows the values 'Y' or 'N' to be inserted, inserting a 'y' or 'n' will cause an error.
PRIMARY KEY Some database systems allow for the direct inserting of primary key values, others do not. With SQL
Server, if the table automatically assigns a primary key, the following command needs to be executed
before the value can be inserted:
SET IDENTITY_INSERT tablename ON
After the inserts have taken place execute
SET IDENTITY_INSERT tablename OFF
FOREIGN KEY If the table has a foreign key constraint and you attempt to insert a reference value that is not in the

pdfMachine
A pdf writer that produces quality PDF files with ease!
46
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
parent table, an error will occur. For example, a customer order could not be inserted into the Orders
table if the customer did not exist in the Customers table.
Data field length Attempting to place a twenty (20) character long string into a ten (10) character long field will cause
an error.
Data Type Values placed in columns must match the column data type.

Example 11.1 Adding a Customer

Before the insert, execute the following query:

SELECT *
FROM Customers
WHERE cust_id = 1000000006

The result is that nothing is returned, Customer 1000000006 does not exist. To add the customer execute the following
command:

INSERT INTO Customers( cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip,


cust_contact, cust_email )
VALUES( '1000000006', 'New Customer', 'New Address', 'City', 'State', 'Zip', 'Contact', 'Email')
OR
INSERT INTO Customers
VALUES( '1000000006', 'New Customer', 'New Address', 'City', 'State', 'Zip', 'Contact', 'Email')

Now query the table for the customer again.

Results 11.1
cust_id cust_name cust_address cust_city cust_state cust_zip cust_contact cust_email
1000000006 New Customer New Address City State Zip Contact Email

The new customer has been added.

Lesson 12: UPDATE


Most data is not static in nature; changes occur and modifications become necessary. A customer's birth date is a static
value and will not need to be changed. A customer's address, and/or billing information, can change. When pre-existing
data needs to be modified the UPDATE command is used.

UPDATE
To change data that has been entered into a table use the UPDATE command. UPDATE changes the contents of a colum
or columns without deleting, or changing, the contents of the other columns. The syntax for the UPDATE statement is a
follows:

UPDATE table_name

pdfMachine
A pdf writer that produces quality PDF files with ease!
47
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
SET column_name1 = new_value1,
column_name2 = new_value2,
.....
column_nameN = new_valueN
[WHERE clause]

The WHERE clause is optional. If a WHERE clause is not used in an UPDATE statement the entire table will be affecte
by the UPDATE. The WHERE clause is used to limit the effect of the UPDATE.

Example 12.1 The Current Values

Before performing the update, execute the following query:

SELECT *
FROM Customers
WHERE cust_id = '1000000006'

Results 12.1
cust_id cust_name cust_address cust_city cust_state cust_zip cust_contact cust_email
1000000006 New Customer New Address City State Zip Contact Email

The values reflected in Results 12.1 show the values inserted into the Customers tables in Lesson 12. To change these
values we execute an UPDATE command.

Example 12.2 UPDATE


UPDATE Customers
SET cust_name = 'Mom & Pop Toys',
cust_address = '2324 Cake Street',
cust_city = 'Bakery',
cust_state = 'NY',
cust_zip = '00502',
cust_contact = '555-1234',
cust_email = '[email protected]'
WHERE cust_id = '1000000006'

Now to view the results of the UPDATE command.

SELECT *
FROM Customers
WHERE cust_id = '1000000006'

Results 12.2
cust_id cust_name cust_address cust_city cust_state cust_zip cust_contact cust_email
1000000006 Mom & Pop Toys 2324 Cake Street Bakery NY 00502 555-1234 [email protected]

pdfMachine
A pdf writer that produces quality PDF files with ease!
48
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
The results show that the changes have been made to the data in the Customers table.

pdfMachine
A pdf writer that produces quality PDF files with ease!
49
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Exercise: to check your knowledge

For T/F questions circle the correct response. For query questions, run the query and select the correct response. If the
question allows space for writing in the answer then write the answer in the space provided.

Lesson 1:
1. A field can contain more than one (1) value. T F
2. How many relations are in figure 1.2?

Lesson 2:
1. The statement “SELECT * FROM Customers” returns all T F
columns from the Orders table.
2. If you SELECT from more than one table, and both tables T F
have a column with the same name, the database system
knows which table the column value is to be retrieved from
and nothing more needs to be done.
3. Both SQL Server and Oracle allow concatenation. T F

Lesson 3.1:
1. If you omit the WHERE clause, how many rows are All
returned? None
Just a few
2. How many rows are returned if you SELECT all products
with a price of 3.49?
3. How many rows are returned if you SELECT all products
with a price not equal 3.49?
4. Which of the two operators shown have the same function? <>
>=
<=
!=

pdfMachine
A pdf writer that produces quality PDF files with ease!
50
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 3.2:
1. If you are using Oracle, string comparisons are not case T F
sensitive.
2. How many rows are returned using WHERE prod_name NOT
LIKE ‘%bean%’ in Example 3.2?
3. How many rows are return using WHERE prod_name
LIKE
'_ish bean b_g t_y' in Example 3.2?

Lesson 3.3:
1. Execute Examples 3.3 and 3.4. Are the results really the Y N
same?

2. How many products have a prod_price BETWEEN 4 and 6?

Lesson 3.4:
1. Execute Examples 3.9 and 3.10. Are the results really the Y N
same?
2. If you use a sub-query with IN and the sub-query does not
return
any results, how many rows will you get back?

Lesson 3.5:
1. Based on Results 3.15, how many customers don’t have
email
addresses in the database?

Lesson 4.1
1. Write a CROSS JOIN between the Customers table and the
Products table. How many rows are returned?

Lesson 4.2
1. Write a query that inner joins the Customers table and the
Orders table on cust_id. How many rows are returned?
2. What column should you use to join the Orders and
OrderItems
table?
3. Write a query that inner joins the Customers, Orders and
OrderItems tables. How many rows are returned?

pdfMachine
A pdf writer that produces quality PDF files with ease!
51
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 4.3
1. Write a query that left joins the Customers table and the
Orders
table on cust_id. How many rows do you get back?
2. Write a query that left joins the Customers, Orders and
OrderItems tables. How many rows are returned?

Lesson 4.4
1. Write a query that right joins the Customers table and the
Orders
table on cust_id. How many rows are returned?
2. Write a query that right joins the Customers, Orders and
OrderItems tables. How many rows are returned?

Lesson 4.5
1. Write a query that full joins the Customers table and the
Orders
table on cust_id. How many rows are returned?
2. Write a query that full joins the Customers, Orders and
OrderItems tables. How many rows are returned?
3. If you are using a database with lots of null values, which
join is
guaranteed to return results?

Lesson 5.1
1. Use COUNT to determine how many customers have a valid email.

2. How many records are in the OrderItems table.

Lesson 5.2
1. Execute Example 5.5 for the customer with a cust_id of
1000000005. What is the value returned?

Lesson 5.3
1. Execute Example 5.6 for the customer with a cust_id of
1000000003. What is the value returned?

Lesson 5.4
1. Execute Example 5.7 for the customer with a cust_id of
1000000004. What is the value returned?

Lesson 5.5
1. Execute Example 5.8 for the customer with a cust_id of
1000000005. What is the value returned?
pdfMachine
A pdf writer that produces quality PDF files with ease!
52
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
2. Execute Example 5.10 for the customer with a cust_id of
1000000004. List the values returned.

Lesson 5.6
Replace “MAX(prod_price)” with “MIN(prod_price)” in the
sub-query and run the sub-query for cust_id = 1000000005.
List
the values returned.

Lesson 5.7
1. Execute Example 5.12 for cust_id = 1000000002. List
the values returned.

Lesson 5.8
1. Execute Example 5.14 HAVING COUNT(*) < 4. How many
rows
were returned?
2. Execute Example 5.15 with
HAVING SUM(P.prod_price) BETWEEN 10 AND 20
AND MAX(P.prod_price) > 5.
How many rows are returned?

pdfMachine
A pdf writer that produces quality PDF files with ease!
53
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 6:
1. Execute example 6.1 for cust_state in the Customers table.
How may rows get an ‘Unknown’ value for state?
2. Select the vend_state from the Vendors table. Execute
Example 6.1 for the Vendors table keeping in mind the state
values stored in the table. How many ‘Unknown’ values are
returned?
3. Create a query, using CASE, that performs the following checks:
 If the SUM of the Products purchased is > 200 AND the
AVG for product price is > 5 print ‘Valued Customer’
Note: Use the OrderItems.quantity column for purchases.

 If the SUM for purchases > 100 print ‘Frequent Buyer’


Note: Use the OrderItems.quantity column for purchases.

 If the COUNT for purchases = 0 print ‘No Purchases’


Note: Use the OrderItems.order_item column for purchases.

 If none of the conditions match print ‘Simple’


Use Example 6.2 as a guide. Change the join on Customers to a
RIGHT JOIN to get any customers that have not placed an order. Be
sure to select the cust_id and use cust_id in a GROUP BY statement.
How many customers are valued customers? How many are frequent
customers? How many have placed zero orders? How many are
simple customers?

pdfMachine
A pdf writer that produces quality PDF files with ease!
54
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 7:
1. Modify Example 7.2 to return the vendor name, replace
customer 1000000004 with customer 1000000003. Which
vendor is used most by both customers?
2. Create a UNION using the query you created for question 1
and the query in Example 7.2. Use any prod_id from the
products table.
3. Modify the UNION in question 2 to a UNION ALL. How
many more rows are returned?

4. Modify the UNION is question 3 to the format in Example


7.3. Use placeholders for Vendor_1 and Vendor_2. Can you
see an advantage to using this method?

Lesson 8:
1. Select the SUM of the prod_price from the products table.

Use CAST and concatenation, “+”, to create the following


string:
$61.41.

If you don’t use CAST with your concatenation what


happens?
2. Concatenate the customer name with the order_date to
produce a string in the following format:
‘The Toy Store placed an order on 02/03/2004’
and use ORDER BY order_date.

Use CONVERT for the date field. Write down the string
for latest
date and the most recent date.

pdfMachine
A pdf writer that produces quality PDF files with ease!
55
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
Lesson 9:
1. Create a view similar to vVendor_Address for customers.
Name the view vCustomer_Contact since everyone in T F
class will be creating the same view and multiple views with
the same name are not allowed.

Compare the count from the query you used to create the
view and the view itself. Are they the same?
2. Create a view called vEverything that gets all information
in the schema: Customers, Order, OrderItems, Products,
and Vendors.

Use INNER joins for everything.


The view should contain cust_id, cust_name, order_num,
order_date, prod_id, prod_name, prod_price, vend_id and
vend_name.
3. Select * from vEverything.
4. Select * from vEverything for product names like “bear”?

5. How is selecting from a view different from selecting from


a table?

Lesson 10:
1. Follow Example 10.1 and add a customer to the
Customers_<your initials> table.

Use the concatenation of the day, month and year of your


birth as a
cust_id (04/12/1970  04121970).

Use your name and address information for the data (you will
change this information later). List all the columns when
adding
this customer.
2. Select * from Customers_<your initials>. Was your data added? T F
1. Add a second customer to the Customers_<your initials> table.
Use the cust_id from question one and add one to it. Insert the
data without listing all the column names.
4. Select * from Customers_<your initials> . Was your data added? T F

Lesson 11:
1. Execute Example 11.2 for the first customer you created.
Replace the cust_id with the new customer’s cust_id.
2. Select * from Customers_<your initials>. Did you change T F

pdfMachine
A pdf writer that produces quality PDF files with ease!
56
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!
the
data?
3. Change the data for the second customer you created. How
would
you verify that the data was changed?

Lesson 12
1. Create a table called YourFirstName_YourLastName (for
example John_Doe). Create three columns of type
Datetime, int,
and char(50). Do not place any constraints on the table
columns.
2. Insert a row into your table with a value for each column.
3. Select * from your table. Is the row there? T F
4. Alter your table. Change the int column to a money column
and
change char(50) to varchar(50).
5. Select * form the table again. Any difference? T F

pdfMachine
A pdf writer that produces quality PDF files with ease!
57
Produce quality PDF files in seconds and preserve the integrity of your original documents. Compatible across
nearly all Windows platforms, simply open the document you want to convert, click “print”, select the
“Broadgun pdfMachine printer” and that’s it! Get yours now!

You might also like