Chapter 6
Chapter 6
▪ Integrity constraints
▪ Structure Query Language
▪ DDL
▪ DML
▪ DCL (self studying)
▪ Sub query
Relational
Getting
High-Level Database Relational
User
Design Schema DBMS
Requirement
Design
COMPANY Database
7
Data Definition Language(DDL)
8
Creating a 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
9
Creating a database
10
Creating a new database
1. Using designer:
◦ Right-click to Database
menu, choose New Database
◦ Example:
CREATE DATABASE DemoShopping
2. Use Query
◦ Syntax:
USE DatabaseName
◦ Example
USE DemoShopping
◦ Example:
ALTER DATABASE DemoShopping MODIFY NAME = DemoShopping2
To drop a database
◦ Syntax:
DROP DATABASE TheDatabase
◦ Example:
DROP DATABASE DemoShopping2
14
Some Common SQL Data Types
Some Common SQL Data Types
CONSTRAINTS
DEFAULT
UNIQUE
SQL Constraints
Primary Key Constraints
◦ Is a way to enforce Entity Integrity
◦ Ensures that values in a primary key column are unique
and not null.
◦ A primary key can be one column or combination of
columns
Foreign key Constraints
◦ Is a way to enforce Referential integrity
◦ Ensures that if the foreign key contains a value, that
value must refer to an existing value in the parent table.
◦ The parent table in such a parent–child relationship
should be created first so that the child table will
reference an existing parent table when it is created
23
SQL constraints
25
The Vendor and Product tables
Vendor table
Product table
26
The Database Model
Example
27
The Database Model
The database model reflects the following business
rules:
◦ A customer may generate many invoices. Each
invoice is generated by one customer.
◦ An invoice contains one or more invoice lines. Each
invoice line is associated with one invoice.
◦ Each invoice line references one product. A product
may be found in many invoice lines.
◦ A vendor may supply many products. Some
vendors do not yet supply products.
◦ If a product is vendor-supplied, it is supplied by only
a single vendor.
◦ Some products are not supplied by a vendor.
28
Creating a table
Creating a simple table using syntax:
30
Creating a table with primary key
constraint CREATE TABLE Vendor (
V_Code INT PRIMARY KEY,
Example: V_Name VARCHAR(35) NOT NULL,
V_Contact VARCHAR(15) NOT NULL,
V_AreaCode CHAR(3) NOT NULL,
V_Phone CHAR(8) NOT NULL,
V_State CHAR(2) NOT NULL,
V_Order CHAR(1) NOT NULL
)
Or
31
Creating a Table with foreign key
constraint
Syntax
32
Creating a Table with foreign key
constraint
CREATE TABLE Vendor (
Example V_Code INT NOT NULL,
…
V_Order CHAR(1) NOT NULL,
Primary key of CONSTRAINT PK_Vendor PRIMARY KEY(V_CODE)
)
parent table
35
Creating a table with DEFAULT,
CHECK, UNIQUE constraint
Example: CUSTOMER table
CREATE TABLE Customer (
CUS_Code INT PRIMARY KEY,
CUS_Lname NVARCHAR(30) NOT NULL,
CUS_Fname NVARCHAR(30) NOT NULL,
CUS_Initial CHAR(1),
CUS_AreaCode CHAR(3)
DEFAULT '615' NOT NULL
CHECK(CUS_AreaCode IN('615','713','931')),
CUS_Phone CHAR(8) NOT NULL,
CUS_Balance DECIMAL DEFAULT 0.00,
CONSTRAINT UQ_CUS_LName_FName
UNIQUE (CUS_Lname, CUS_Fname)
)
36
Creating a table with constraints
Invoice table
◦ the DEFAULT constraint assigns a default date
to a new invoice
◦ the CHECK constraint validates that the
invoice date is greater than January 1, 2016
CREATE TABLE Invoice (
INV_Number INT PRIMARY KEY,
CUS_CodeINT NOT NULL,
INV_Date DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
CONSTRAINT FK_Inv_Cus_CusCode FOREIGN KEY(CUS_Code)
REFERENCES Customer,
CONSTRAINT CK_INVDate CHECK (INV_Date > '2016-01-01')
)
37
Creating a table with constraints
Invoice table has
◦ a composite primary key (INV_NUMBER,
LINE_NUMBER)
◦ a UNIQUE constraint
in INV_NUMBER and P_CODE to ensure that
the same product is not ordered twice in the
same invoice.
CREATE TABLE Line (
INV_Number INTEGER NOT NULL, Some primary keys are composite– composed of multiple
LINE_Number NUMERIC(2,0) NOT NULL, attributes
P_Code VARCHAR(10) NOT NULL,
LINE_Units DECIMAL(9,2) DEFAULT 0.00 NOT NULL,
LINE_Price DECIMAL(9,2) DEFAULT 0.00 NOT NULL,
PRIMARY KEY (INV_Number,LINE_Number),
FOREIGN KEY (INV_Number) REFERENCES Invoice ON DELETE CASCADE,
FOREIGN KEY (P_Code) REFERENCES Product(P_Code),
CONSTRAINT UQ_Line UNIQUE(INV_Number, P_Code))
38
Altering a table
◦ To drop a column
ALTER TABLE table_name
DROP COLUMN column_name
Altering a table
◦ To remove a constraint
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
41
Removing a table
DROP TABLE statement removes the specified table
from a database
Syntax
DROP TABLE Table_name [RESTRIC|CASCADE]
◦ Default option is RESTRICT, the table will not be
dropped if there are any dependent objects, such
as views or constraints, that currently reference
the table.
◦ If CASCADE is specified, all dependent objects
will also be dropped as the table is dropped.
42
Removing a table
Example:
43
Auto-increment
Auto-increment allows a unique number to be
generated automatically when a new record is
inserted into a table.
Often this is the primary key field that we would like
to be created automatically every time a new record
is inserted.
Auto-increment
46
Exercises
Ex2: Create a database scheme that consists of four
tables:
Product(maker, model, type)
PC(code, model, speed, ram, hd, cd, price)
Laptop(code, model, speed, ram, hd, screen, price)
Printer(code, model, color, type, price)
Exercises
48
INSERT Statement
INSERT command is used to enter data into a table.
◦ Example:
INSERT INTO Vendor (V_Code,V_Name,V_Contact,V_AreaCode,V_Phone,V_State,V_Order)
VALUES(21225,'Bryson, Inc.','Smithson','615','223-3234','TN','Y')
49
INSERT Statement
You do not need to specify the column (s) name if you are adding
values for all the columns of the table. However, make sure the
order of the values is in the same order as the columns in the
table.
Inserting Rows with Null Attributes with NULL keyword when all the
attribute values must be specified
INSERT INTO Vendor VALUES(21225,'Bryson, Inc.','Smithson','615','223-
3234','TN','Y')
50
INSERT Statement
Inserting Rows with Optional Attributes
◦ Rather than declaring each attribute as NULL in the INSERT command, you can indicate
just the attributes that have required values.
◦ Example: assume that the only required attributes for the PRODUCT table are P_Code and
P_Descript
51
INSERT Statement
End-user applications are best created with utilities
to create a form-based data view and entry screen
52
INSERT Statement
54
The content of Product table
Update statement
UPDATE Product
SET P_InDate = '01-18-2016', P_Price = 17.99, P_Min = 10
WHERE P_CODE = '13-Q2/P2'
Example
DELETE FROM Product
WHERE P_Code = 'BRT-345'
TRUNCATE vs DELETE
◦ TRUNCATE is a DDL whereas DELETE is
a DML
◦ You can use WHERE clause(conditions)
with DELETE but you can't use WHERE
clause with TRUNCATE
◦ You can't rollback data in TRUNCATE but in
DELETE you can rollback data
◦ TRUNCATE is faster than DELETE.
SELECT Statement
The SELECT Statement is used to retrieve data from a
database table.
The basic syntax of SELECT Statement:
SELECT columnlist
FROM tablelist
[ WHERE conditionlist ]
63
SELECT Statement
◦ Result:
64
SELECT Statement
65
SELECT Statement
Example: lists all of the rows of the product for
which the vendor code is not 21344.
SELECT P_Descript, P_InDate, P_Price, V_Code
FROM Product
◦ Result: WHERE V_Code <> 21344
66
SELECT Statement
Using Comparison Operators on Character Attributes
◦ String (character) comparisons are made left-to-
right ASCII character comparison
SELECT P_Code, P_Descript, P_QOH, P_Min, P_Price
FROM Product
WHERE P_Code < '1558-QW1'
◦ Result:
67
SELECT Statement
Using Comparison Operators on Dates
◦ Using yyyy-mm-dd format for date
68
SELECT Statement
Using Computed Columns and Column Aliases
◦ Example: determine the total value of each of
the products
69
SELECT Statement
Using Alias
◦ Alias: alternate name given to a column or table in
any SQL statement to improve the readability
◦ Is useful with calculations
◦ There can also be the optional AS keyword between the
column/table name and alias
SELECT P_Descript, P_QOH AS Quantity, P_Price Price,
P_QOH * P_Price AS TotalValue
FROM Product
70
SELECT Statement
Logical Operators: AND, OR, NOT
71
SELECT Statement
Logical Operators: AND, OR, NOT
◦ You can combine the logical OR with the logical
AND to place further restrictions on the output
72
SELECT Statement
Special Operators
◦ BETWEEN - Used to check whether an attribute
value is within a range.
◦ IS NULL - Used to check whether an attribute
value is null
◦ LIKE - Used to check whether an attribute value
matches a given string pattern
◦ IN - Used to check whether an attribute value
matches any value within a value list
◦ EXISTS - Used to check whether a subquery
returns any rows
73
SELECT Statement
Special operators
◦ BETWEEN
74
SELECT Statement
Special operators
◦ IS NULL SELECT P_Code, P_Descript, V_Code
FROM Product
WHERE V_Code IS NULL
75
SELECT Statement
Special operators
◦ LIKE
◦ The LIKE special operator is used in conjunction
with wildcards to find patterns within string
attributes.
◦ use the percent sign ( % ) and underscore ( _ )
wildcard characters
% matches any substring.
_ matches one character
76
SELECT Statement
Special operators
◦ LIKE
SELECT V_Name, V_Contact, V_AreaCode, V_Phone
FROM dbo.Vendor
WHERE V_Contact LIKE 'Smith%'
77
SELECT Statement
Special operators
◦ IN
◦ All of the values in the list must be of the
same data type.
SELECT *
FROM Product
WHERE V_Code IN (21344, 24288)
SELECT *
FROM Product
WHERE V_Code = 21344 OR V_Code = 24288
78
SELECT Statement
Special operators
◦ EXISTS
◦ Is used to check if a subquery returns any rows, run
the main query; otherwise, do not.
◦ EX: list all vendors but only if there are products with
the quantity on hand, and less than double the
minimum quantity
SELECT *
FROM Vendor
WHERE EXISTS(SELECT*FROM Product WHERE P_QOH < P_Min * 2)
79
SELECT Statement
Use DISTINCT keyword to eliminates all
duplicate rows in the table resulting from the
query
SELECT V_Code SELECT DISTINCT V_Code
FROM Product FROM Product
80
Sorting Results: The ORDER BY
Clause
ORDER BY clause is used to sort the result set in
ascending (ASC) or descending (DESC) order. the
default order is ascending.
◦ Syntax:
81
Sorting Results: The ORDER BY
Clause
Example: SELECT P_Code, P_Descript, P_QOH, P_Price
FROM dbo.Product
ORDER BY P_Price
82
Sorting Results: The ORDER BY
Clause
Result
83
Sorting Results: The ORDER BY
Clause
EMPLOYEE Table Contents
84
Sorting Results: The ORDER BY
Clause
Cascading order sequence
SELECT EMP_LName, EMP_FName, EMP_Initial, EMP_AreaCode, EMP_Phone
FROM Employee
ORDER BY EMP_LName, EMP_FName, EMP_Initial
85
Sorting Results: The ORDER BY
Clause
Descending order
86
Aggregate Functions
An aggregate function allows you to perform a
calculation on a set of values to return a single scalar
value
Syntax
87
The contents of Product table
88
Aggregate Functions
COUNT
◦ The default is ALL
89
Aggregate Functions
COUNT
SELECT COUNT(*)
FROM dbo.Product
91
Aggregate Functions
SUM
SELECT SUM(P_QOH * P_Price) AS TOTVALUE
FROM Product
92
Aggregate Functions
AVERAGE
93
GROUP BY Clause
GROUP BY is particularly useful when paired with
aggregate functions.
The GROUP BY clause allows you to arrange the
rows returned by SELECT statement in groups. The
groups are determined by the columns that you
specify in the GROUP BY clause.
Syntax:
94
GROUP BY Clause
95
GROUP BY Clause
The command will should be written
SELECT V_Code, COUNT(P_Code) AS Quantity
FROM Product
GROUP BY V_Code
ORDER BY Quantity
96
HAVING Clause
The HAVING clause is often used with the GROUP
BY clause in the SELECT statement to filter group of
rows based on a specified condition.
The WHERE clause is used to restrict the rows that
you select. But the HAVING clause is used to restrict
groups.
97
SQL statement processing order
98
HAVING Clause
SELECT V_Code,COUNT(P_Code),AVG(P_Price)
FROM Product
GROUP BY V_Code
HAVING AVG(P_Price)<10
99
SubQuery & Joins
1 SubQuery
100
SubQuery
101
Subquery
102
Subquery
103
Subquery
104
WHERE Subqueries
Syntax SELECT column_list
FROM table
WHERE expression OPERATOR
(SELECT column_list
FROM table)
The subquery (inner query) executes once before the main query.
The result of the subquery is used by the main query (outer query).
105
The contents of Employees table
106
The contents of Departments
table
107
Scalar Subquery
108
Scalar Subquery
Syntax
θ
SELECT ......
can be
FROM ......
=
WHERE ...... θ <>
( SELECT ...... >
FROM ...... >=
WHERE ...... ) <
<=
109
Scalar Subquery
Example
SELECT employee_id, first_name, last_name, salary
FROM Employees
WHERE salary >(SELECT AVG(salary) FROM employees)
ORDER BY salary
Inner query
results
110
Multi-Valued Subquery
Multi-valued subquery returns multiple values to the
outer query
Query uses the set comparion operators (IN, ALL,
ANY).
SYMBOL MEANING
IN Equal to any member in a list
111
Multi-Valued Subquery
Syntax:
SELECT ...... θθ
FROM ...... can be
WHERE ...... θθ IN
( SELECT ......
NOT IN
FROM ...... θ ANY
WHERE ...... ) θ ALL
EXISTS
NOT EXISTS
112
Multi-Valued Subquery with IN
Example
SELECT employee_id, first_name, last_name,
department_id
FROM Employees
WHERE department_id IN (SELECT department_id
FROM departments
Can’t use ‘=’ comparison. WHERE location_id = 1700)
Subquery can return many Inner query
department_id results
113
Multi-Valued Subquery with ALL
Example
SELECT employee_id, first_name, last_name, salary, department_id
FROM Employees
WHERE salary > ALL (SELECT salary
FROM employees
WHERE department_id = 10)
AND department_id<>10
If ‘>’ is true for
every value,
ALL returns true,
else false.
114
Multi-Valued Subquery with ANY
Example
SELECT employee_id, first_name, last_name, salary, department_id
FROM Employees
WHERE salary > ANY (SELECT salary
FROM employees
WHERE department_id = 10)
AND department_id<>10
If ‘>’ is true for
at least one value,
ANY returns true,
else false.
115
EXISTS/NOT EXISTS
116
EXISTS/NOT EXISTS
The keyword EXISTS does not follow a column
name or other expression
The SELECT list of a subquery introduced by
EXISTS typically only uses an asterisk (*)
117
EXISTS/NOT EXISTS
Example: Show all the employees information if
there is at least one employee with a salary in
excess of 200,000
SELECT employee_id, first_name, last_name, salary, department_id
FROM Employees
WHERE EXISTS (SELECT * FROM employees WHERE salary > 200000)
118
Correlated subqueries
119
Correlated subqueries
120
Correlated subqueries
121
Subqueries in FROM clause
122
Subqueries in SELECT clause
123
Multiple Table
joins
124
Multiple Tables Joins
125
Multiple Tables Joins
Type of joins
◦ Equijoin or Inner Join
◦ Self join
◦ Outer join
◦ Cross Join
126
The contents of Product table
127
The contents of Vendor table
128
Inner Join
Also called as Equijoin
◦ This join combines the rows retrieved from two
or more tables, based on a common field
between them.
◦ This join creates a new result table by
combining columns values of the tables based
upon the join condition.
◦ To join n tables together, you need a minimum of n-1
join conditions
Uses an equality operator (=) to join tables.
INNER JOIN or simply JOIN is used in the query
129
Inner join
The INNER JOIN keyword selects all rows from
tables as long as there is a match between the
columns
ANSI syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name
You can join more than two tables based upon the
join conditions.
130
Inner join
Example
SELECT Product.P_Descript, Product.P_Price,
Vendor.V_Name, Vendor.V_Contact,Vendor.V_AreaCode,
Vendor.V_Phone
FROM Product INNER JOIN Vendor
ON Product.V_Code = Vendor.V_Code
132
Inner join
133
Self Join
A Self join or Recursive Join is a type of SQL join
which is used to join a table to itself.
The table has a Foreign key that references its
own Primary key.
An alias is especially useful when a table must be
joined to itself in a recursive query to avoid
column ambiguity.
134
Self Join
Example: list of all employees with their
managers
names by joining the EMP table to itself.
135
The content of Emp table
136
Self Join
Result
137
The content of Product table
138
The content of Vendor table
139
Outer join
Outer join is a join in which rows that do not have
matching values in common columns are also
included in the result table .
Null values appear in columns where there is not a
match between tables
Outer join
◦ Left outer join
◦ Right outer join
◦ Full outer join
140
Left Outer Join
141
Left Outer Join
Example: Show V_Code, V_Name for all vendors
listed in the Vendor table. Include P_Code,
P_Descript even if there is no product for that vendor.
142
Left Outer Join
Result
143
Right Outer Join
144
Right Outer Join
145
Right Outer Join
Result
146
Full Outer Join
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition
147
Full Outer Join
148
Full Outer Join
Result
149
Cross Join
A cross join performs a relational product (also
known as the Cartesian product) of two
tables
SELECT column_name(s)
FROM table1
CROSS JOIN table2
150
Cross Join
Example
SELECT P.P_Code, P.P_Descript, V.V_Code, V_Name
FROM VENDOR V CROSSJOIN PRODUCT P
151
Cross Join
The command performs a cross join of the VENDOR
and PRODUCT tables that generates 176 rows.
(There are 11 vendor rows and 16 product rows,
yielding 11 × 16 = 176 rows.)
Some rows of the
result
152