0% found this document useful (0 votes)
40 views152 pages

Chapter 6

Uploaded by

tuannhade180647
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views152 pages

Chapter 6

Uploaded by

tuannhade180647
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 152

Chapter 6

THE DATABASE LANGUAGE SQL

THE DATABASE LANGUAGE SQL 1


Objectives

▪ Student can write a SQL script.


▪ Student can compose SQL queries using set (and
bag) operators, correlated subqueries, aggregation
queries.
▪ Student can manipulate proficiently on complex
queries

THE DATABASE LANGUAGE SQL 2


Contents

▪ Integrity constraints
▪ Structure Query Language
▪ DDL
▪ DML
▪ DCL (self studying)
▪ Sub query

THE DATABASE LANGUAGE SQL 3


REVIEW

Relational
Getting
High-Level Database Relational
User
Design Schema DBMS
Requirement
Design

ER diagram Relational Database Schema

Figure 4.1: The database modeling and implementation process


Studied:
- ER diagram
- Relational model
- Convert ERD to Relational model
Now: we learn how to set up a relational database on
DBMS THE DATABASE LANGUAGE SQL 4
REVIEW – Entity Relationship Diagram

COMPANY Database

THE DATABASE LANGUAGE SQL 5


Integrity constraints

▪ Purpose: prevent semantic inconsistencies in


data
▪ Kinds of integrity constraints:
1. Key Constraints (1 table): Primary key, Candidate key
(Unique)
2. Attribute Constraints (1 table): NULL/NOT NULL; CHECK
3. Referential Integrity Constraints (2 tables): FOREIGN KEY
4. Global Constraints (n tables): CHECK or CREATE
ASSERTION (self studying)

We will implement these constraints by SQL

THE DATABASE LANGUAGE SQL 6


SQL Commands
 3 types:
SQL commands

Data Definition Data Manipulation Data Control


Language(DDL) Language(DML) Language(DCL)

Maintain and query Control the database:


Define the database:
- GRANT OR REVOKE
- CREATE, ALTER, DROP the database: PRIVILEGES TO
TABLES, VIEWS, INDEXES - UPDATING, INSERTING,
ACCESS THE
- ESTABLISHING DELETING AND
DATABASE
CONSTRAINTS QUERYING DATA
- COMMITING DATA

7
Data Definition Language(DDL)

 DDL statements are used to define a database


 Major CREATE statements:
◦ CREATE DATABASE – create a new database
◦ CREATE SCHEMA–defines a portion of the
database owned by a particular user
◦ CREATE TABLE–defines a table and its
columns
◦ CREATE VIEW–defines a logical table from
one or more views

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

 A SQL Server database can be created, altered


and dropped by one of two following methods:
◦ Using the designer with SQL Server
Management Studio (SSMS) or
◦ Using a Query
 After creating database, 2 files are generated:
◦ .MDF file – Data file (contains actual data)
◦ .LDF file _ Transaction Log file ( used to
recover the database)

10
Creating a new database
1. Using designer:
◦ Right-click to Database
menu, choose New Database

2. Using a Query: Ctrl +N


To create a new query
◦ Syntax:
CREATE DATABASE DatabaseName

◦ Example:
CREATE DATABASE DemoShopping

◦ Click Execute button to


create the DemoShopping database.
Creating a new database
Using the database
1. Click the combobox to
choose the database

2. Use Query
◦ Syntax:
USE DatabaseName

◦ Example
USE DemoShopping

Right-click to the database, choose Properties,


click Files to know database files
Altering/Deleting a Database

 To alter an existing database:


◦ Syntax:
ALTER DATABASE OldDatabase MODIFY NAME = NewDatabase

◦ Example:
ALTER DATABASE DemoShopping MODIFY NAME = DemoShopping2

 To drop a database
◦ Syntax:
DROP DATABASE TheDatabase

◦ Example:
DROP DATABASE DemoShopping2

◦ Dropping a database will delete the LDF and MDF files.


Creating the Database Schema
 Schema: logical database structure
◦ Is a group of database objects- such as tables and indexes – that
are related to each other.
 Authentication
◦ Process through which the DBMS verifies that only registered users
are able to access the database
◦ Log on to the RDBMS using a user ID and a password created by
the database administrator
 Syntax:

 Ex: CREATE SCHEMA AUTHORIZATION <creator>

Example (For most RDBMS, it is optional)


CREATE SCHEMA AUTHORIZATION vku

14
Some Common SQL Data Types
Some Common SQL Data Types

 Exact numeric data types:


Some Common SQL Data Types

 Approximate numeric data types:


The approximate numeric data type stores floating
point numeric data. They are often used in scientific
calculations.
Some Common SQL Data Types

 Date & Time data types


Some Common SQL Data Types
 Character strings data types
Character strings data types allow you to store either
fixed-length (char) or variable-length data (varchar).

 Unicode character string data types store either fixed-


length (nchar) or variable-length (nvarchar)
Some Common SQL Data Types

 Binary string data types


The binary data types stores fixed and variable
length binary data.
Some Common SQL Data Types
 Other data types
SQL Constraints

 A constraint is a mechanism that may be used to


limit the values entered into a column.

CONSTRAINTS

NOT NULL CHECK FOREIGN KEY PRIMARY KEY

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

 NOT NULL constraint


◦ Ensures that a column does not accept nulls
 UNIQUE constraint
◦ Ensures that all values in a column are unique
◦ you can have many UNIQUE constraints per table,
but only one PRIMARY KEY constraint per table.
 DEFAULT constraint
◦ Assigns a value to an attribute when a new row is
added to a table
 CHECK constraint
◦ is a kind of domain integrity
◦ Validates data when an attribute value is entered
24
Creating a Table with foreign key
constraint
 Example:

◦ Each product is supplied by only a single vendor.


◦ A vendor may supply many products
◦ PRODUCT is optional to VENDOR.
◦ Some vendors have never supplied a product
(VENDOR is optional to PRODUCT)

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:

 Data Types can be string, numeric, and date/time.


Not all data types are supported by every relational
database vendors.
 To make the SQL code more readable:
◦ one line per column definition,
◦ SQL keywords should be upper-case letters
◦ User-defined words should be lower-case letters
Creating a Table with primary key
constraint
 Syntax 1:

 Syntax 2: you can named for constraint

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

CREATE TABLE Vendor (


V_Code INT NOT NULL,
V_Name VARCHAR(35) NOT NULL,
V_Contact VARCHAR(15) NOT NULL, Primary keys can
V_AreaCode CHAR(3) NOT NULL, never have NULL
V_Phone CHAR(8) NOT NULL,
V_State CHAR(2) NOT NULL, values
V_Order CHAR(1) NOT NULL,
CONSTRAINT PK_Vendor PRIMARY KEY (V_Code)
)

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

CREATE TABLE Product (


P_Code VARCHAR(10) NOT NULL,
P_Descript VARCHAR(35) NOT NULL,
P_InDate DATE NOT NULL,
P_QOH INT NOT NULL,
P_Min INT NOT NULL,
P_Price DECIMAL(8,2) NOT NULL,
P_Discount DECIMAL(8,2) NOT NULL,
V_Code INT NULL,
CONSTRAINT PK_Product PRIMARY KEY (P_Code),
CONSTRAINT FK_Product_Vendor_Vcode
FOREIGN KEY (V_Code) REFERENCES Vendor)
Foreign key of
child_table
33
Foreign key constraint with
Delete and Update rules
DELETE AND UPDATE rules in SQL Server foreign key
can be use with the following options:
 NO ACTION (the default)
◦ Error message would be generated, and no action is
performed
 CASCADE
◦ if the parent record is deleted/updated, associated records in
child table are also deleted/updated.
 SET NULL
◦ if the parent record is deleted/updated, associated records in
child table are set to null
◦ Foreign key column should allow NULL values
 SET DEFAULT
◦ if the parent record is deleted/updated, associated records in
child table are set to default value specified in column
definition.
◦ Also default value should be present in primary key column.
Foreign key constraint with
Delete and Update rules
CREATE TABLE Product (
 Example P_Code VARCHAR(10) NOT NULL,
P_Descript VARCHAR(35) NOT NULL,
P_InDate DATE NOT NULL,
P_QOH INT NOT NULL,
P_Min INT NOT NULL,
P_Price DECIMAL(8,2) NOT NULL,
P_Discount DECIMAL(8,2) NOT NULL,
V_Code INT NULL,
CONSTRAINT PK_Product PRIMARY KEY (P_Code),
CONSTRAINT FK_Product_Vendor_Vcode
FOREIGN KEY (V_Code) REFERENCES Vendor
ON UPDATE CASCADE
)

◦ ON UPDATE CASCADE specification ensures that if you make a change


in any V_CODE in VENDOR table that will result in that value changing in
the PRODUCT table to match.


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

 Use ALTER TABLE statement is used to


◦ To add a column to an existing table:
ALTER TABLE table_name
ADD column_name datatype

◦ To change the data type of a column in a table


ALTER TABLE table_name
ALTER COLUMN column_name datatype

◦ To drop a column
ALTER TABLE table_name
DROP COLUMN column_name
Altering a table

 Use ALTER TABLE statement is also used to


◦ To add a constraint to an existing table:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name constraint_type syntax

◦ To remove a constraint
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;

 Show all constraints in a table


exec sp_helpconstraint 'table_name'
Altering a table with examples
 To add column for a table
◦ Add a column named CUS_Address to the Customer
table ALTER TABLE dbo.Customer
ADD CUS_Address NVARCHAR(50) DEFAULT N'Đà Nẵng'
 To add constraints for a table
◦ Add a primary key for Vendor table if you forget to create
it. Note: you only create a primary key on column(s) that
are already defined as NOT NULL
ALTER TABLE Vendor
ADD CONSTRAINT PK_Vendor PRIMARY KEY(V_Code)
◦ Add a foreign key for Product table

ALTER TABLE Product


ADD CONSTRAINT FK_Product_Vendor_Vcode
FOREIGN KEY (V_Code) REFERENCES Vendor
ON UPDATE CASCADE

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:

DROP TABLE Table_name [RESTRIC|CASCADE]

 Many RDBMSs allows users to retain the table’s structure


but remove all of the data that have been entered in the
table with its TRUNCATE TABLE command
◦ Syntax:

TRUNCATE TABLE Table_name


◦ Example
TRUNCATE TABLE Customer

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

 To create an identity column for a table:

◦ seed is the value of the first row loaded into


the table.
◦ increment is the incremental value added to
the identity value of the previous row.
 The default value of seed and increment is 1.
 Example: CREATE TABLE Employee
(
Emp_ID int PRIMARY KEY IDENTIY(1,1),
LastName nvarchar(255) NOT NULL,
FirstName nvarchar(255),
Address nvarchar(255),
)
Exercises

 Ex1: Create the following tables (Employee,


Department)
◦ Use Auto-increment
◦ apply 4 rules: No action, Cascade, set null, set
default.

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

 Ex3: Create a database named BookDB


◦ Use the SQL statements to create the tables:
Books (BookID, BookTitle, CopyRight, Year),
Authors (AuthorID, AuthorFName,
AuthorMName, AuthorLName, DateOfBirth,
Gender, Address) and AuthorBook (BookID,
AuthorID)
◦ Set the constraints for the tables

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

 Note for INSERT statement


◦ The row contents are entered between parentheses
◦ Character (string) and date values must be entered between apostrophes
( ’ ).
◦ Numerical entries are not enclosed in apostrophes.
◦ Attribute entries are separated by commas.
◦ A value is required for each column in the table.

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

INSERT INTO Product


VALUES ('BRT-345','Titanium drill bit','18-Oct-15', 75, 10, 4.50, 0.06, NULL)

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

 You can insert more than one record at a time.


◦ Example
INSERT INTO Product(P_Code, P_Descript)
VALUES('BRT-345','Titanium drill bit')

INSERT INTO Vendor VALUES


(21226,'SuperLoo, Inc.','Flushing','904','215-8995','FL','N'),
(21231,'D&E Supply‘ ,'Singh' ,'615','228-3245','TN','Y'),
(21344,'Gomez Bros.' ,'Ortega' ,'615','889-2546','KY','N')

51
INSERT Statement
 End-user applications are best created with utilities
to create a form-based data view and entry screen

52
INSERT Statement

 SQL Server automatically uses the following


value for the column that is available in the table
but does not appear in the column list of the
INSERT statement:
◦ The next incremental value if the column has an
IDENTITY property.
◦ The default value if the column has a default value
specified.
◦ The NULL if the column is nullable
◦ The calculated value if the column is a computed
column.
◦ The current timestamp value if the data type of the
column is a timestamp data type
53
INSERT Statement

 Any changes made to the table contents are not


physically saved on disk until
◦ Database is closed
◦ Program is closed
◦ COMMIT command is used
 Saving table changes by
COMMIT;
◦ Will permanently save any changes (such as
rows added, attributes modified, and rows
deleted) made to any table in the database

54
The content of Product table
Update statement

 The UPDATE statement is used to modify the


existing records in a table.

◦ Value1, value2,…can be an expression.


◦ If more than one attribute is to be updated in the
row, separate the corrections with commas.
◦ The WHERE clause is optional, that specifies
which record(s) that should be updated.
◦ If you omit the WHERE clause, all records in the
table will be updated!
Update statement
 Example
UPDATE Product
SET P_InDate = '01-18-2016'
WHERE P_Code = '13-Q2/P2'

UPDATE Product
SET P_InDate = '01-18-2016', P_Price = 17.99, P_Min = 10
WHERE P_CODE = '13-Q2/P2'

 Use can use the command to list contents of


table
SELECT * FROM Product
UPDATE statement

 Restoring Table Contents by ROLLBACK statement


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

 Use BEGIN TRANSACTION before DML commands


before using ROLLBACK command.
 COMMIT and ROLLBACK only work with data
manipulation commands that are used to add, modify,
or delete table rows
58
DELETE statement

 The DELETE statement is used to delete existing


records in a table.

◦ The WHERE clause is optional, that specifies


which record(s) should be deleted.
◦ If you omit the WHERE clause, all records in
the table will be deleted!
DELETE statement

 Example
DELETE FROM Product
WHERE P_Code = 'BRT-345'

DELETE FROM Product


WHERE P_Min = 5
DELETE statement

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

◦ SELECT identifies what columns to be projected into the


table that will be the results of the command
◦ FROM identifies which table (s) needed to process the
query
◦ WHERE: restricts the query to rows that meet
conditions, the WHERE clause is optional.
62
SELECT Statement
 The contents of Product table:

63
SELECT Statement

 Example: Showing the description, date, and


price of products with a vendor code of 21344
SELECT P_Descript, P_InDate, P_Price, V_Code
FROM Product
WHERE V_Code = 21344

◦ Result:

64
SELECT Statement

 Using asterisk ( * ) to select all columns in the


table
SELECT * FROM Product

 The comparison operators can be used to restrict


output

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

SELECT P_Descript, P_QOH, P_Min, P_Price, P_InDate


FROM Product
WHERE P_InDate >= '2018-01-20'
◦ Result:

68
SELECT Statement
 Using Computed Columns and Column Aliases
◦ Example: determine the total value of each of
the products

SELECT P_Descript, P_QOH, P_Price, P_QOH * P_Price


FROM Product
◦ Result

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

SELECT P_Descript, P_InDate, P_Price, V_Code


FROM Product
WHERE V_Code = 21344 OR V_Code = 24288

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

SELECT P_Descript, P_InDate, P_Price, V_Code


FROM Product
WHERE (P_Price < 50 AND P_InDate > '2018-01-15')
OR V_Code = 24288

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

SELECT * FROM Product


WHERE P_Price BETWEEN 50.00 AND 100.00

SELECT * FROM Product


WHERE P_Price>= 50.00 AND P_Price<= 100.00

74
SELECT Statement
 Special operators
◦ IS NULL SELECT P_Code, P_Descript, V_Code
FROM Product
WHERE V_Code IS NULL

◦ NULL is a special property of an attribute that


represents the absence of any value

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:

◦ If the ordering column has nulls, they are listed


either first or last, depending on the RDBMS.
◦ The ORDER BY clause must always be listed
last in the SELECT command sequence.

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

SELECT P_Descript, V_Code, P_InDate, P_Price


FROM Product
WHERE P_InDate < '2018-01-21' AND P_Price <= 50.00
ORDER BY V_Code, P_Price DESC

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(V_Code) AS 'Số lượng V_Code'


FROM dbo.Product

SELECT COUNT( DISTINCT V_Code) AS 'Số lượng V_Code'


FROM dbo.Product

SELECT COUNT(*)
FROM dbo.Product

◦ COUNT(*) returns the number of total rows from the query,


including the rows that contain nulls. 90
Aggregate Functions
 MAX/MIN
SELECT MAX(P_Price) AS 'Max Price'
FROM dbo.Product

SELECT P_Code, P_Descript, P_Price


FROM Product
WHERE P_Price = (SELECT MAX(P_Price) FROM Product)

91
Aggregate Functions

 SUM
SELECT SUM(P_QOH * P_Price) AS TOTVALUE
FROM Product

92
Aggregate Functions
 AVERAGE

SELECT AVG(P_Price) AS AveragePrice


FROM Product

SELECT P_Descript,P_QOH, P_Price, V_Code


FROM Product WHERE P_Price > (SELECT AVG(P_Price)FROM
Product)
ORDER BY P_Price DESC

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

 The GROUP BY clause is valid only when used


in conjunction with one of the SQL aggregate
functions: COUNT, MIN, MAX, AVG, SUM
SELECT V_Code, P_Code
FROM Product
GROUP BY V_Code
 The above command will result an error:

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

 With HAVING clause


SELECT V_Code,COUNT(P_Code),AVG(P_Price)
FROM Product
GROUP BY V_Code

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

2 Multiple Table joins

100
SubQuery

 Subquery is a query inside another query


◦ A subquery can be nested inside a SELECT, INSERT,
UPDATE or DELETE statement or inside another
subquery.
◦ A subquery is usually added within the WHERE clause of
another SQL SELECT statement.
 In a subquery SELECT statement, can not include:
◦ the keyword DISTINCT in the SELECT phrase,
◦ an ORDER BY phrase.

101
Subquery

 Subqueries can be:


◦ Noncorrelated subqueries (Self-contained
subqueries)
◦ have no dependency on outer query
◦ execute once for the entire outer query
◦ Correlated subqueries
◦ depend on values from outer query
◦ execute once for each row returned by the outer
query
◦ Can use the EXISTS operator

102
Subquery

 A subquery is must be enclosed within


parentheses
 Subquery can return:
◦ One single value (Scalar Subquery) - One
column and one row
◦ A list of values (Multi-Valued Subquery) - One
column and multiple rows
◦ A virtual table - Multicolumn, multirow set of
values
◦ No value - Output of the outer query might result
in an error or a null empty set

103
Subquery

 The most common type of subquery uses an inner


SELECT subquery on the right side of a WHERE
comparison expression (WHERE subqueries)
 A subquery can be used within a SQL data
manipulation language (DML) statement such
as INSERT, UPDATE, or DELETE

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

 The Scalar sub query returns one single value to


outer query
◦ Uses operators: can be >, <, =, >=, or <=, <>
◦ Value generated by the subquery must be of a
comparable data type
 If the query returns multiple values, the DBMS will
generate an error.
 If inner query returns an empty set, result is
converted to NULL

108
Scalar Subquery
 Syntax
θ
SELECT ......
can be
FROM ......
=
WHERE ...... θ <>
( SELECT ...... >
FROM ...... >=
WHERE ...... ) <
<=

Must ensure that the subquery returns a SINGLE VALUE,


i.e. a table of one row and one column, or an ERROR results.

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

ANY Return rows that match any value on a list

ALL Return rows that match all values in a list

111
Multi-Valued Subquery
 Syntax:
SELECT ...... θθ
FROM ...... can be
WHERE ...... θθ IN
( SELECT ......
NOT IN
FROM ...... θ ANY
WHERE ...... ) θ ALL
EXISTS
NOT EXISTS

θ is any of =, <>, >, >=, <, <=

The subquery can return MULTIPLE VALUES,


i.e. one column of many rows.
However there is no problem if only one row is returned.

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

 When a subquery is used with the keyword EXISTS,


it functions as an existence test
◦ True or false only – no rows passed back to outer
query
 EXISTS evaluates to TRUE or FALSE
◦ If any rows are returned by the subquery,
EXISTS returns TRUE
◦ If no rows are returned, EXISTS returns FALSE
 Syntax:

WHERE [NOT] EXISTS (subquery)

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)

The SELECT list typically only


uses an asterisk because no data
will be returned

118
Correlated subqueries

 Example 1: Finds all employees whose salary is


higher than the average salary of the employees in
their departments:
SELECT employee_id, first_name, last_name, salary, department_id
FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees
WHERE department_id = e.department_id)

119
Correlated subqueries

 Example 2: returns all departments which have


no employees:
SELECT
department_id, department_name
FROM
departments d
WHERE NOT EXISTS( SELECT * FROM employees e
WHERE e.department_id = d.department_id)

120
Correlated subqueries

 Example 3: Which departments have exactly 2


employees working on them ?
SELECT * FROM Departments d
WHERE 2 = (SELECT count(*) FROM employees e
WHERE e.department_id = d.department_id)

121
Subqueries in FROM clause

 Example: Get the maximum of the average


departmental salaries.
SELECT FORMAT(MAX( AvSal ),'C2') AS MaxAvSal
FROM ( SELECT department_id, ROUND(AVG( Salary),2) AS AvSal
FROM employees
GROUP BY department_id ) AS Emp_Averages

This is a useful way of applying


an aggregate function to the result
of an aggregate function.

122
Subqueries in SELECT clause

 Example: Get the additional amount of salary that


each employee receives over and above the
minimum company salary.
SELECT employee_id, first_name, last_name,
( Salary - ( SELECT Min(Salary)
FROM employees ) ) AS Additional
FROM employees

This is a useful way of doing a scalar calculation in each row


that requires the resulting value of an aggregation.

123
Multiple Table
joins

124
Multiple Tables Joins

 Ability to combine (join) tables on common


attributes is most important distinction between a
relational database and other databases
 Join clause is used to combine rows from two
or more tables, based on a related column
between them.
 Join is generally composed of an equality
comparison between the foreign key and the
primary key of related tables

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

 Or use EquiJoin based on equality V_Code (old-


style 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
131
Inner join
 Result

132
Inner join

 Joining Tables With a Alias


◦ An alias may be used to identify the source
table from which the data is taken
SELECT P.P_Descript,P.P_Price,V.V_Name,
V.V_Contact,V.V_AreaCode, V.V_Phone
FROM Product P INNER JOIN Vendor V
ON P.V_Code = V.V_Code

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.

SELECT E.EMP_Num, E.EMP_LName, E.EMP_MGR, M.EMP_LName


FROM EMP E
INNER JOIN EMP M
ON E.EMP_MGR = M.EMP_Num
ORDER BY E.EMP_MGR

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

 In Left outer join (or Left Join)


◦ Returns all rows from the left table (table1) and
the matching rows from the right table (table2)
◦ If no records match from the left table, it shows
those records with NULL values
 Syntax:
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name

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.

SELECT V.V_Code, V_Name, P.P_Code, P.P_Descript


FROM VENDOR V LEFT JOIN PRODUCT P
ON V.V_Code = P.V_Code

142
Left Outer Join

 Result

143
Right Outer Join

 In Right outer join (or Right Join)


◦ Returns all rows from the right table (table2)
and the matching rows from the left table
(table1)
◦ If no records match from the right table, it
shows those records with NULL values
 Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name

144
Right Outer Join

 Example: Show P_Code, P_Descript for all products


listed in the Product table. Include V_Code,
V_Name even if there is no Vendor for that product.

SELECT P.P_Code, P.P_Descript, P.V_Code, V_Name


FROM VENDOR V RIGHTJOIN PRODUCT P
ON V.V_Code = P.V_Code

145
Right Outer Join

 Result

146
Full Outer Join

 Full Outer Join or Full Join


◦ returns all records when there is a match in left
(table1) or right (table2) table records.
 Syntax

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition

147
Full Outer Join

 Example: List P_Code, P_Descript, V_Code and


V_Name of all products and vendors, regardless
of whether or not the products have vendor or the
vendors supply the products.

SELECT P.P_Code, P.P_Descript, V.V_Code, V_Name


FROM VENDOR V FULL JOIN PRODUCT P
ON V.V_Code = P.V_Code

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

 Or using other syntax (all DBMSs use this style)


SELECT P.P_Code, P.P_Descript, V.V_Code, V_Name
FROM VENDOR V, 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

You might also like