CHAPTER 7 STRUCTURED
QUERY LANGUAGE
PREPARED BY: PUAN SRI YUSMAWATI MOHD YUNUS
FSKM UiTMCNS
Learning Objectives
The basic commands and functions of SQL
How to use SQL for data administration (to
create tables and indexes)
How to use SQL for data manipulation (to add,
modify, delete, and retrieve data)
How to use SQL to query a database for useful
information
CONTENTS
Introduction To SQL
Data Definition Commands
Data Manipulation Commands
SQL Operators
Advanced Data Definition Commands
Advanced Select Queries
Join Database Tables
Introduction to SQL
Data definition language
• SQL includes commands to create
• Database objects such as tables, indexes, and views
• Commands to define access rights to those database objects
Data manipulation language
• Includes commands to insert, update, delete, and retrieve data within
the database tables
Basic command set has a vocabulary of less than 100
words
Nonprocedural language
American National Standards Institute (ANSI)
prescribes a standard SQL
Creating the Database
Two tasks must be completed
• create the database structure
• create the tables that will hold the end-user
data
First task
• RDBMS creates the physical files that will
hold the database
• Tends to differ substantially from one
RDBMS to another
The Database Schema
Authentication Schema
• Process through which the • Group of database objects—
DBMS verifies that only such as tables and indexes—
registered users are able to that are related to each other
access the database
• Log on to the RDBMS using a
user ID and a password created
by the database administrator
Creating Table Structures
Use one line per column (attribute) definition
Use spaces to line up the attribute characteristics and constraints
Table and attribute names are capitalized
NOT NULL specification
UNIQUE specification
Primary key attributes contain both a NOT NULL and a UNIQUE
specification
RDBMS will automatically enforce referential integrity for foreign
keys
Command sequence ends with a semicolon
Other SQL Constraints
NOT NULL constraint
• Ensures that a column does not accept nulls
UNIQUE constraint
• Ensures that all values in a column are unique
DEFAULT constraint
• Assigns a value to an attribute when a new row is
added to a table
CHECK constraint
• Validates data when an attribute value is entered
SQL Indexes
When a primary key is declared, DBMS automatically creates a
unique index
Often need additional indexes
Using the CREATE INDEX command, SQL indexes can be created
on the basis of any selected attribute
Composite index
• Index based on two or more attributes
• Often used to prevent data duplication
A Duplicated TEST Record
Creating Table Structures - Example
Attribute (Field) Name Data Declaration
EMP_NUM INTEGER
EMP_LNAME VARCHAR(15)
EMP_FNAME VARCHAR(15)
EMP_INITIAL CHAR(1)
EMP_HIREDATE DATE
JOB_CODE CHAR(3)
CREATE TABLE EMP(
EMP_NUM INTEGER PRIMARY KEY,
EMP_LNAME VARCHAR(15) NOT NULL,
EMP_FNAME VARCHAR(15) NOT NULL,
EMP_INITIAL CHAR(1),
EMP_HIREDATE DATE,
JOB_CODE CHAR(3) DEFAULT ‘000’,
FOREIGN KEY (JOB_CODE) REFERENCES JOB);
Adding table Saving table
Listing table rows
rows changes
Updating table Restoring table Deleting table
rows contents rows
Inserting table
rows with a select
subquery
Common SQL Data Manipulation
Commands
Saving Table Changes
Changes made to table contents are not physically saved
on disk until
• Database is closed
• Program is closed
• COMMIT command is used
Syntax
• COMMIT [WORK]
Will permanently save any changes made to any table in
the database
Listing Table Rows
SELECT
• Used to list contents of table
Syntax
• SELECT columnlist
FROM tablename
Columnlist represents one or more attributes, separated by
commas
Asterisk can be used as wildcard character to list all
attributes
Updating Table Rows
UPDATE
◦ UPDATE EMPin a table
Modify data
SET EMP_PCT = 3.85
Syntax
WHERE EMP_NUM = '103';
◦ UPDATE
UPDATEEMP tablename
SET columnnameEMP_PCT
SET = expression [, columname =
= 5.00
WHERE EMP_NUM = ‘101’;
expression]
[WHERE conditionlist];
UPDATE EMP
If SET
more than oneEMP_PCT
attribute is to
= 8.00 be updated in
WHERE EMP_NUM = ‘102’;
the row, separate corrections with commas
Restoring Table Contents
ROLLBACK
• Used restore the database to its previous condition
• Only applicable if COMMIT command has not been used to permanently
store the changes in the database
Syntax
• ROLLBACK;
COMMIT and ROLLBACK only work with data manipulation
commands that are used to add, modify, or delete table rows
Deleting Table Rows
DELETE
◦ Deletes
DELETE a table
FROM EMProw
WHERE EMP_LNAME = 'Smithfield'
Syntax
AND EMP_FNAME = 'William'
AND
◦ DELETE FROM EMP_HIREDATE
tablename = '22-June-02'
AND[WHERE conditionlist
JOB_CODE]; = '500';
WHERE condition is optional
If WHERE condition is not specified, all rows
from the specified table will be deleted
Inserting Table Rows - Example
INSERT INTO EMP_1 VALUES (‘101’, ‘News’, ‘John’, ‘G’, ’08-Nov-
98’, ‘502’);
INSERT
• INSERT INTO EMP_1 VALUES (‘102’, ‘Senior’, ‘David’, ‘H’, ’12-
Jul-87’, ‘501’);
• Inserts multiple rows from another table (source)
• Uses SELECT subquery
• Query that is embedded (or nested) inside another query
• Executed first
• Syntax
• INSERT INTO tablename SELECT columnlist FROM
tablename
INSERT INTO PART (PART_CODE, PART_DESCRIPT,
PART_PRICE)
SELECT P_CODE, P_DESCRIPT, P_PRICE FROM PRODUCT;
Selecting Rows with Conditional
Restrictions
Select partial table contents by placing restrictions
on rows to be included in output
◦ Add conditional restrictions to the SELECT statement,
using WHERE clause
Syntax
◦ SELECT columnlist
FROM tablelist
[ WHERE conditionlist ] ;
SELECT P_DESCRIPT,
P_INDATE, P_PRICE,
V_CODE FROM
PRODUCT WHERE
V_CODE = 21344;
Comparison Operators
Selected PRODUCT Table Attributes for
VENDOR Codes Other than 21344
SELECT P_DESCRIPT,
P_INDATE, P_PRICE,
V_CODE FROM
PRODUCT WHERE
V_CODE <>
21344;
Selected PRODUCT Table Attributes
with a P_PRICE Restriction
SELECT
P_DESCRIPT,
P_ONHAND,
P_MIN,
P_PRICE
FROM PRODUCT
WHERE P_PRICE <=
10;
Selected PRODUCT Table Attributes: Date
Restriction
SELECT P_DESCRIPT,
P_ONHAND, P_MIN,
P_PRICE, P_INDATE
FROM PRODUCT WHERE
P_INDATE >= ’20 – Jan
– 2004’;
SELECT Statement with a Computed
Column
SELECT P_DESCRIPT,
P_ONHAND, P_PRICE,
P_ONHAND * P_PRICE
FROM PRODUCT;
SELECT Statement with a Computed
Column and an Alias
SELECT P_DESCRIPT,
P_ONHAND, P_PRICE,
P_ONHAND * P_PRICE
AS TOTVALUE FROM
PRODUCT;
Arithmetic Operators: The Rule of
Precedence
Perform
Perform power
operations within
operations
parentheses
Perform Perform
multiplications additions and
and divisions subtractions
Selected PRODUCT Table Attributes:
The Logical OR
SELECT P_DESCRIPT,
P_INDATE, P_PRICE,
V_CODE FROM
PRODUCT WHERE
V_CODE = 21344 OR
V_CODE = 24288;
Selected PRODUCT Table Attributes:
The Logical AND
SELECT P_DESCRIPT,
P_INDATE, P_PRICE,
V_CODE FROM
PRODUCT WHERE
PRICE < 50 AND
P_INDATE > ’15 – Jan
– 2004’;
Selected PRODUCT Table Attributes:
The Logical AND and OR
SELECT P_DESCRIPT,
P_INDATE, P_PRICE,
V_CODE FROM
PRODUCT WHERE
(P_PRICE < 50 AND
P_INDATE > ’15 – Jan
– 2004’) OR V_CODE =
24288;
Special Operators
BETWEEN
• Used to check whether attribute value is within a range
IS NULL
• Used to check whether attribute value is null
LIKE
• Used to check whether attribute value matches a given string pattern
IN
• Used to check whether attribute value matches any value within a value list
EXISTS
• Used to check if a subquery returns any rows
Advanced Data Definition Commands
All changes in the table structure are made by
using the ALTER command
• Followed by a keyword that produces specific change
• Three options are available
• ADD
• MODIFY
• DROP
Changing a Column’s Data Type
• ALTER can be used to change data type
Changing column data • Some RDBMSs (such as Oracle) do not permit
types changes to data types unless the column to be
changed is empty
• Use ALTER to change data characteristics
• If the column to be changed already contains
Changing column data data, changes in the column’s characteristics are
characteristic permitted if those changes do not alter the data
type
• Use ALTER to add a column
• Do not include the NOT NULL clause for new
column
Add & drop column • Use ALTER to drop a column
• Some RDBMSs impose restrictions on the
deletion of an attribute
The Effect of Data Entry into the New
P_SALECODE Column
UPDATE PRODUCT
SET P_SALECODE = ‘1’
WHERE P_CODE = ‘1546-QQ2’;
Update of the P_SALECODE Column in
Multiple Data Rows
UPDATE PRODUCT
SET P_SALECODE = ‘1’
WHERE P_CODE =
‘2232/QWE’
OR P_CODE = ‘2232/QTY’;
The Effect of Multiple Data Updates in
the PRODUCT Table (MS Access)
UPDATE PRODUCT
SET P_SALECODE = ‘2’
WHERE P_INDATE <
’25-Dec-2003’;
UPDATE PRODUCT
SET P_SALECODE = ‘1’
WHERE P_INDATE >=
’16-Jan-2004’;
AND P_INDATE <=
’10-Feb-2004’;
Copying Parts of Tables
SQL permits copying contents of selected table
columns so that the data need not be reentered
manually into newly created table(s)
First create the PART table structure
Next add rows to new PART table using
PRODUCT table rows
PART Attributes Copied from the
PRODUCT Table
INSERT INTO PART (PART_CODE,
PART_DESCRIPT, PART_PRICE)
SELECT P_CODE, P_DESCRIPT,
P_PRICE FROM PRODUCT;
Advanced Select Queries
SQL provides useful functions
• Count
• Find minimum and maximum values
• Calculate averages
SQL allows the user to limit queries to only
those entries having no duplicates or entries
whose duplicates may be grouped
Selected PRODUCT Table Attributes:
Ordered by (Ascending) P_PRICE
SELECT P_CODE,
P_DESRIPT, P_INDATE,
P_PRICE FROM
PRODUCT ORDER BY
P_PRICE;
Some Basic SQL Aggregate Functions
COUNT
MAX & MIN
SUM
AVG
GROUP BY
Joining Database Tables
Ability to combine (join) tables on common
attributes is most important distinction between a
relational database and other databases
Join is performed when data are retrieved from more
than one table at a time
Join is generally composed of an equality
comparison between the foreign key and the primary
key of related tables
Creating Links Through Foreign Keys
The Results of a Join
SELECT
PRODUCT.P_DESCRIPT,
PRODUCT.P_PRICE,
VENDOR.V_NAME,
VENDOR.V_CONTACT,
VENDOR.V_AREACODE,
VENDOR.V_PHONE
FROM PRODUCT,
VENDOR WHERE
PRODUCT.V_CODE =
VENDOR.V_CODE;
An Ordered and Limited Listing
After a JOIN
SELECT P_DESCRIPT,
P_PRICE, V_NAME,
V_CONTACT,
V_AREACODE, V_PHONE
FROM PRODUCT,
VENDOR WHERE
PRODUCT.V_CODE =
VENDOR.V_CODE AND
P_INDATE > ’15-Jan-
2004’;
Converting an ER Model
into a Database Structure
Requires following specific rules that govern
such a conversion
Decisions made by the designer to govern data
integrity are reflected in the foreign key rules
Implementation decisions vary according to
the problem being addressed
The Ch06_Artist Database ERD
and Tables
A Data Dictionary for the Ch06_Artist
Database