Introduction to SQL

Introduction to SQL
1. Basic Terms and Concepts
SQL: Structured Query Language:
- is a standard way of specifying data sets
- is a way to retrieve and manipulate data in a database
- is used for all database functions, including administration, schema creation, and data retrieval
-
can be used in the form of "embedded SQL" from an application program
Database
A body of data in which there are relationships among the data elements
Database Management System
Software that facilitates the definition of database structures and the storing and retrieving of data
from those structures
Terms
-
-
-
-
Table
o A set of rows or a set of lists of values: a "relation"
o Each column in a given row has a single data value
o Each column is of a single data type
o Called “entity” in logical model
o Called “file” in physical representation
Column
o Called “attribute” in logical model
o Called “field” in physical representation
Row
o All rows of a table have the same set of columns
o One or more columns whose contents are unique within the table and thus can
be used to identify the rows of that table
o Called “instance” in logical model
o Called “record” in physical representation
Primary Key
o Each row can be accessed by a unique "primary key"
Database Personnel/Job Functions
- SQL User/Application User
o Retrieve data
o Update data
o Insert data
o Delete data
- Database Designer
o Design database
o Create tables
o Implement business rules/security (integrity)
- Application Designer
o Design architecture
o Create tables
1
-
o Determine performance issues
o Program interpretability
o Write programs
Database System Administrator
o Install system
o Perform backup and recovery
o Monitor performance/security
2
Example: Supplier and Parts Database
ABC company has three tables which has the following contents:
S
SNO
S1
S2
S3
S4
S5
SNAME
Smith
Jones
Blake
Clark
Adams
STATUS
20
10
30
20
30
CITY
London
Paris
Paris
London
Athens
P
PNO
P1
P2
P3
P4
P5
P6
PNAME
Nut
Bolt
Screw
Screw
Cam
Cog
COLOR
Red
Green
Blue
Red
Blue
Red
WEIGHT
12
17
17
14
12
19
SP
SNO
S1
S1
S1
S1
S1
S1
S2
S2
S3
S4
S4
S4
PNO
P1
P2
P3
P4
P5
P6
P3
P4
P3
P3
P4
P4
CITY
London
Paris
Rome
London
Paris
London
QTY
300
200
400
200
100
100
300
400
300
300
200
400
2. Setting Up Tables
1. Creates the tables by issuing the following statements:
CREATE TABLE S
(SNO
CHAR(5),
SNAME CHAR(20),
STATUS SMALLINT,
CITY CHAR(15));
CREATE TABLE P
(PNO
CHAR(6),
PNAME CHAR(20),
COLOR CHAR(6),
WEIGHT SMALLINT,
CITY CHAR(15));
CREATE TABLE SP
(SNO
CHAR(5),
PNO
CHAR(6),
QTY
INTEGER);
2. Once the table is created, data can then be placed in it by issuing the command:
INSERT INTO S VALUES('S1', 'Smith', 20, 'London');
3
This command is repeated for each record of the table. Repeat this for all the tables of the
database.
3. Data Retrieval I
SELECT/FROM
Used to retrieve data from the database
- SELECT clause specifies the columns you wish to retrieve
- FROM clause specifies the table(s) from which the data is retrieved

Example 1: List all data in supplier table
Command:
SQL> SELECT * FROM S;
Result:
SNO
--------S1
S2
S3
S4
S5

SNAME
--------------------Smith
Jones
Blake
Clark
Adams
STATUS
------------20
10
30
20
30
CITY
----------London
Paris
Paris
London
Athens
Example 2: List only the city from the supplier table
Command:
SQL> SELECT CITY FROM S;
Result:
CITY
--------------London
Paris
Paris
London
Athens

Example3: List the name and city of suppliers
Command:
SQL> SELECT SNAME,CITY FROM S;
Result:
SNAME
-------------------Smith
Jones
Blake
Clark
Adams
CITY
--------------London
Paris
Paris
London
Athens
4
Re-ordering Columns
Order of column names in the select statement determines order of the columns in the result

Example4: List the supplier name, city and status
Command:
SQL> SELECT SNAME, CITY, STATUS FROM S;
Result:
SNAME
-------------------Smith
Jones
Blake
Clark
Adams
CITY
--------------London
Paris
Paris
London
Athens
STATUS
--------20
10
30
20
30
Eliminating Duplicates
DISTINCT eliminates duplicate rows in the output
- DISTINCT works on the entire row
- DISTINCT is used to:
o Find each possible value in a particular column
o Group values into categories

Example 5: List one occurrence of the city from supplier table
Command:
SQL> SELECT DISTINCT CITY FROM S;
Result:
CITY
--------------Athens
London
Paris
Qualified Retrieval – SELECT/FROM/WHERE
The WHERE clause limits which rows are retrieved

Example: List the supplier names in Paris
Command:
SQL> SELECT SNAME FROM S WHERE CITY = 'Paris';
Result:
SNAME
-------------------Jones
Blake
Search conditions are Boolean expressions (true/false tests) applied to each row to determine what
5
should be returned
Qualifications in the WHERE clause
- Ranges (BETWEEN and NOT BETWEEN)
- Character matches (LIKE and NOT LIKE)
- Unknown values (IS NULL and IS NOT NULL)
- Lists (IN and NOT IN)
- Operators
o Equal to (=)
o Less than (>)
o Greater than (<)
o Less than or equal to (>=)
o Greater than or equal to (<=)
o Not equal to (!=, <>)
o Not greater than (!>)
o Not less than (!<)
- Combinations of the above (AND, OR)
Note:
-
-
< treated earlier than > in sort order and in comparing dates
In comparing strings, < and > depend on the sort order selected. For example,
upper-case letters appear first in sorted output in some cases
Upper-case letters are treated earlier than numbers
When more than one logical operator is used, the default order in which they are
evaluated is: NOT  AND  OR
Ranges
BETWEEN is used to specify an inclusive range: lower and upper values are included for the
search

Example
Command:
SQL> SELECT PNO, PNAME FROM P WHERE WEIGHT BETWEEN 12 AND 17;
Result:
PNO
-----P1
P2
P3
P4
P5
PNAME
-------------------Nut
Bolt
Screw
Screw
Cam
NOT BETWEEN excludes the lower and upper values that are specified

Example
Command:
SQL> SELECT PNO, PNAME FROM P WHERE WEIGHT NOT BETWEEN 12 AND 17;
6
Result:
PNO
-----P6
PNAME
-------------------Cog
Character Matches
LIKE keyword

-
Used to select rows containing fields that match specified portions of character
strings
-
Only used with character data
Can use wildcard, %, which means “any string of zero or more characters”
Example: Find the part name that begin with C
Command:
SQL> SELECT PNAME FROM P WHERE PNAME LIKE 'C%';
Result:
PNAME
-------------------Cam
Cog

Example: Find those parts whose names do not begin with capital C
Command:
SQL> SELECT PNAME FROM P WHERE PNAME NOT LIKE 'C%';
Result:
PNAME
-------------------Nut
Bolt
Screw
Screw
Lists
IN keyword allows you to select rows with columns whose contents match any one of a list of
possible values

Example: Find suppliers in London or Paris
Command:
SQL> SELECT SNAME FROM S WHERE CITY IN ('Paris', 'London');
Result:
SNAME
-------------------Smith
Jones
Blake
Clark
7

Example: Find suppliers not in London or Paris
Command:
SQL> SELECT SNAME FROM S WHERE CITY NOT IN ('Paris', 'London');
Result:
SNAME
-------------------Adams
Connecting Conditions
Connect conditions with logical operators: AND/OR
AND connects two or more conditions - Returns results only when all of the conditions are true

Example: Find all the green parts that are produced in Paris.
Command:
SQL> SELECT PNAME FROM P WHERE COLOR = 'Green' AND CITY = 'Paris';
Result:
PNAME
-------------------Bolt
OR connects two or more conditions Returns results when any of the conditions are true Is
inclusive

Example: Find all the parts which are green produced in Paris.
Command:
SQL> SELECT PNAME FROM P WHERE COLOR = 'Green' OR CITY = 'Paris';
Result:
PNAME
-------------------Bolt
Cam
3. Data Retrieval II
Renaming Columns
There are two ways to rename a column heading
1. Use column_name “new_column_name”

Example
8
Command:
SQL> SELECT PNO PART_NUMBER, PNAME PART_NAME FROM P;
Result:
PART_NUMBER
----------------------P1
P2
P3
P4
P5
P6
PART_NAME
-------------------Nut
Bolt
Screw
Screw
Cam
Cog
2. Use Numeric Expression - Arithmetic Operators
Symbol
+
*
/
%

Operation
Addition
Subtraction
Multiplication
Division
Modulo
Example
Command:
SQL> SELECT PNO, PNAME, WEIGHT+10 FROM P;
Result:
PNO
--------P1
P2
P3
P4
P5
P6
PNAME
--------------------Nut
Bolt
Screw
Screw
Cam
Cog
WEIGHT+10
-----------------22
27
27
24
22
29
ORDER BY
o
o
o

The order by clause sorts the query results (in ascending order by default)
Items named in an order by clause need not appear in the select_list
When using order by, nulls are listed first
Example
Command:
SQL> SELECT SNAME, STATUS FROM S ORDER BY STATUS;
Result:
SNAME
------------------Jones
Smith
Clark
Blake
Adams
STATUS
------------10
20
20
30
30
9
4. Organizing and Summarizing Data
Aggregate Functions
Aggregate
COUNT(*)
COUNT(col_name)
MAX(col_name)
MIN(col_name)
SUM(col_name)
AVG(col_name)
Meaning
number of selected rows
number of non-null values in column
highest value in column
lowest value in column
total of values in column
average of values In column
Note:
o
o
o
o
o
Aggregates ignore null values (except count (*) )
SUM and AVG only work with numeric values
Only one row is returned (if a group by clause is not used)
Aggregates may not be used in a where clause
Aggregates can be applied to all rows in a table or to a subset of a table
COUNT
COUNT adds up the number of rows meeting the condition

Example
Command:
SQL> SELECT COUNT(*) FROM S;
Result:
COUNT(*)
--------------5
MAX/MIN
MAX finds the largest value in the column

Example
Command:
SQL> SELECT MAX(WEIGHT) FROM P;
Result:
MAX(WEIGHT)
--------------------19
MIN finds the smallest value in the column

Example
10
Command:
SQL> SELECT MIN(WEIGHT) FROM P;
Result:
MIN(WEIGHT)
-------------------12
SUM/AVG
SUM adds up the values in the column

Example
Command:
SQL> SELECT SUM(STATUS) FROM S;
Result:
SUM(STATUS)
--------------------110
AVG adds the values in the column and divides by the number of rows that have a value in that
column

Example
Command:
SQL> SELECT AVG(WEIGHT) FROM P;
Result:
AVG(WEIGHT)
--------------------15.166667
5. Joins
Simple Equijoin
The join operations retrieves data from two or more tables. The join operations is based on the
values of a column in all tables to be equal.

Example: Get all combinations of supplier and part information such that the supplier and part
are in the same city.
Command:
SQL> SELECT S.*, P.* FROM S,P WHERE S.CITY = P.CITY;
Result:
SNO
------------S1
SNAME
------------Smith
STATUS
------------20
CITY
------------London
PNO
------------P1
PNAME
------------Nut
COLOR
------------Red
WEIGHT
------------12
CITY
------------London
11
S4
S1
S4
S1
S4
S2
S3
S2
S3
Clark
Smith
Clark
Smith
Clark
Jones
Blake
Jones
Blake
20
20
20
20
20
10
30
10
30
London
London
London
London
London
Paris
Paris
Paris
Paris
P1
P4
P4
P6
P6
P2
P2
P5
P5
Nut
Screw
Screw
Cog
Cog
Bolt
Bolt
Cam
Cam
Red
Red
Red
Red
Red
Green
Green
Blue
Blue
12
14
14
19
19
17
17
12
12
London
London
London
London
London
Paris
Paris
Paris
Paris
Conditional join
The join operations retrieves data from two or more tables. The join operations is based on
satisfying a given condition.

Example 1: Get all combinations of supplier and part information such that the supplier city
follows the part city in alphabetical order.
Command:
SQL> SELECT S.*, P.* FROM S,P WHERE S.CITY > P.CITY;
Result:
SNO
------------S2
S3
S2
S3
S2
S3

SNAME
------------Jones
Blake
Jones
Blake
Jones
Blake
STATUS
------------10
30
10
30
10
30
CITY
------------Paris
Paris
Paris
Paris
Paris
Paris
PNO
------------P1
P1
P4
P4
P6
P6
PNAME
------------Nut
Nut
Screw
Screw
Cog
Cog
COLOR
------------Red
Red
Red
Red
Red
Red
WEIGHT
------------12
12
14
14
19
19
CITY
------------London
London
London
London
London
London
Example 2: Get all combinations of supplier and part information where the supplier and part
concerned are co-located, but omitting suppliers with status 20.
Command:
SQL> SELECT S.*, P.* FROM S,P WHERE S.CITY = P.CITY AND S.STATUS != 20;
Result:
SNO
------------S2
S3
S2
S3
SNAME
------------Jones
Blake
Jones
Blake
STATUS
------------10
30
10
30
CITY
------------Paris
Paris
Paris
Paris
PNO
------------P2
P2
P5
P5
PNAME
------------Bolt
Bolt
Cam
Cam
COLOR
------------Green
Green
Blue
Blue
WEIGHT
------------17
17
12
12
CITY
------------Paris
Paris
Paris
Paris
Retrieving Specified Columns From a Join

Example: Get all supplier number/part number combinations such that the supplier and part in
question are co-located.
Command:
SQL> SELECT S.SNO, P.PNO FROM S,P WHERE S.CITY = P.CITY;
Result:
SNO
-------
PNO
--------
12
S1
S4
S1
S4
S1
S4
S2
S3
S2
S3
P1
P1
P4
P4
P6
P6
P2
P2
P5
P5
Join of Three Tables
Retrieving information from three tables.

Example: get all pairs of supplier numbers such that the two suppliers concerned are
co-located.
Command:
SQL> SELECT DISTINCT S.CITY, P.CITY FROM S, SP, P
WHERE S.SNO = SP.SNO AND SP.PNO = P.PNO;
Result:
CITY
--------------London
London
London
Paris
Paris
CITY
--------------London
Paris
Rome
London
Rome
Joining a Table with Itself
Get all pairs of supplier numbers such that the two suppliers concerned are co-located.
Command:
SQL> SELECT FIRST.SNO, SECOND.SNO FROM S FIRST, S SECOND
WHERE FIRST.CITY = SECOND.CITY;
Result:
SNO
------S5
S1
S4
S1
S4
S2
S3
S2
S3
SNO
-------S5
S1
S1
S4
S4
S2
S2
S3
S3
6. Subqueries
Subqueries are alternate way of retrieving information from tables. A subquery is a select
13
statement used as an expression in part of another select, update, insert, or delete.

Example 1: Get supplier names for suppliers who supply part P2.
Command:
SQL> SELECT SNAME FROM S WHERE SNO IN (SELECT SNO FROM SP WHERE PNO = 'P2');
Result:
SNAME
-------------------Smith

Example 2: Get supplier names for suppliers who supply at least one red part.
Command:
SQL> SELECT SNAME FROM S WHERE SNO IN
(SELECT DISTINCT SNO FROM SP WHERE PNO IN (SELECT PNO FROM P WHERE COLOR = 'Red'));
Result:
SNAME
-------------------Smith
Jones
Clark

Example 3: Get supplier numbers for suppliers who supply at least one part supplied by
supplier s2.
Command:
SQL> SELECT DISTINCT SNO FROM SP WHERE PNO IN
(SELECT PNO FROM SP WHERE SNO = 'S2');
Result:
SNO
------S1
S2
S3
S4
14