100% found this document useful (1 vote)
18 views

Chapter 1 - Advanced SQL

The document is a comprehensive guide on Advanced Structured Query Language (SQL) by Dr. Cao Thi Nhan, covering essential topics such as SQL data definition, data types, and commands for data manipulation including INSERT, DELETE, and UPDATE. It also discusses basic and complex retrieval queries, specifying constraints, and the relational data model with practical examples. Additionally, it addresses advanced SQL concepts like nested queries, outer joins, and handling NULL values.

Uploaded by

Bảo Châu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
18 views

Chapter 1 - Advanced SQL

The document is a comprehensive guide on Advanced Structured Query Language (SQL) by Dr. Cao Thi Nhan, covering essential topics such as SQL data definition, data types, and commands for data manipulation including INSERT, DELETE, and UPDATE. It also discusses basic and complex retrieval queries, specifying constraints, and the relational data model with practical examples. Additionally, it addresses advanced SQL concepts like nested queries, outer joins, and handling NULL values.

Uploaded by

Bảo Châu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Chapter 1

ADVANCED STRUCTURED QUERY


LANGUAGE

Dr. Cao Thi Nhan


Content
1. Introduction
2. SQL Data Definition and Data Types
3. INSERT, DELETE, and UPDATE Statements in SQL
4. Basic Retrieval Queries in SQL
5. More Complex SQL
6. View
7. Indexes
Dr. Cao Thi Nhan
Introduction
SQL language
Considered one of the major reasons for the commercial
success of relational databases
SQL
Structured Query Language
Statements for data definitions, queries, and updates.
Core specification
Plus specialized extensions
SQL Data Definition and Data Types
▪ Terminology:
o Table, row, and column used for relational model terms relation,
tuple, and attribute
▪ CREATE statement
o Main SQL command for data definition
▪ SQL schema
o Identified by a schema name
o Includes an authorization identifier and descriptors for each element
▪ Schema elements include
o Tables, constraints, views, domains, and other constructs
▪ Each statement in SQL ends with a semicolon
SQL Data Definition and Data Types
▪ SQL environment
o Installation of an SQL-compliant RDBMS on a computer system
▪ CREATE SCHEMA statement
o CREATE SCHEMA COMPANY AUTHORIZATION ‘Jsmith’;
CREATE TABLE command in SQL
▪ Specify a new relation
o Provide name
o Specify attributes and initial constraints
▪ Can optionally specify schema:
o CREATE TABLE SchemaName.TableName …
CREATE TABLE COMPANY.EMPLOYEE …
Or
o CREATE TABLE TableName ...
CREATE TABLE EMPLOYEE
Data types in Microsoft SQL Server

Data type SQL Server

String varchar(n), char(n), nvarchar(n), nchar(n), text, …

Number tinyint, smallint, int, bigint,


numeric(m, n), decimal(m,n), float, real,
smallmoney, money

Date, time smalldatetime, datetime…

Logical / Boolean Bit (0, 1, NULL)


Others Cursor, xml, spatial geometry types, binary strings (image, binary)
Relational data model example
1. EMPLOYEE (Fname, Minit, Lname, Ssn, Bdate, Address, Sex, Salary,
Super_ssn, Dno)
2. DEPARTMENT (Dnumber, Dname, Mgr_ssn, Mgr_start_date)
3. DEPT_LOCATIONS (Dnumber, Dlocation)
4. PROJECT (Pnumber, Pname, Plocation, Dnum)
5. WORKS_ON (Essn, Pno, Hours)
6. DEPENDENT (Essn, Dependent_name, Sex, Bdate, Relationship)
Relational data model example
CREATE TABLE command in SQL
Not null, Unique, Primary key, Foreign
▪ CREATE TABLE command key …
CREATE TABLE <Table_name> (
<Column name 1> <Data type> [<Constraint>],
<Column name 2> <Data type> [<Constraint>],

[< Constraint >] Primary key, Foreign key …
)
CREATE TABLE command in SQL
EMPLOYEE (Ssn, Fname, Minit, Lname, Bdate, Address, Sex, Salary, Super_ssn, Dno)
CREATE TABLE EMPLOYEE (
Ssn char(10) primary key,
Fname varchar(30) not null,
Minit varchar(2) not null,
Lname varchar(30) not null,
Bdate smalldatetime,
Address varchar(50),
Sex bit,
Super_ssn char(10),
Dno int
)
CREATE TABLE command in SQL
EMPLOYEE (Ssn, Fname, Minit, Lname, Bdate, Address, Sex, Salary, Super_ssn, Dno)
DEPARTMENT (Dnumber, Dname, Mgr_ssn, Mgr_start_date)

?!
CREATE TABLE DEPARTMENT (
Dnumber int primary key, Order
Dname varchar(30) not null,
Mgr_ssn char(10) foreign key references EMPLOYEE (Ssn),
Mgr_start_date smalldatetime,
)
CREATE TABLE command in SQL
EMPLOYEE (Ssn, Fname, Minit, Lname, Bdate, Address, Sex, Salary, Super_ssn, Dno)
PROJECT (Pnumber, Pname, Plocation, Dnum)
WORKS_ON (Essn, Pno, Hours)
CREATE TABLE WORKS_ON (
Primay key has
Essn
Pno
char(10),
int, ?! some attributes
Hours int not null,
primary key (Essn, Pno)
foreign key (Essn) references EMPLOYEE (Ssn),
foreign key (Pno) references PROJECT (Pnumber),
)
CREATE TABLE command in SQL
Specifying Constraints in SQL
▪ NOT NULL
o NULL is not permitted for a particular attribute
▪ Default value
o DEFAULT <value>
▪ CHECK clause
o Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21);
o Score float Check (Score>=0 and Score<=10)
Specifying Constraints in SQL
▪ PRIMARY KEY clause
o Specifies one or more attributes that make up the primary key of a
relation
o Dnumber INT PRIMARY KEY;
▪ UNIQUE clause
o Specifies alternate (secondary) keys
o Dname VARCHAR(15) UNIQUE;
Specifying Constraints in SQL
▪ FOREIGN KEY clause
o Default operation: reject update on violation
o Attach referential triggered action clause
✓ Options include SET NULL, CASCADE, and SET DEFAULT
✓ Action taken by the DBMS for SET NULL or SET DEFAULT is the same
for both ON DELETE and ON UPDATE
✓ CASCADE option suitable for “relationship” relations
INSERT, DELETE, and UPDATE Statements in SQL
▪ Three commands used to modify the database: INSERT, DELETE,
UPDATE
INSERT Command in SQL
▪ Specify the relation name and a list of values for the tuple
INSERT INTO <Table Name> [(<List of attribute>)] VALUES (<List of value>)
INSERT INTO <Table Name> <Select query>
DELETE Command in SQL
▪ Removes tuples from a relation
o Includes a WHERE clause to select the tuples to be deleted
DELETE FROM <Table Name> [WHERE <Criteria>]

DELETE FROM EMPLOYEE WHERE ssn=‘123456789’


DELETE FROM EMPLOYEE
UPDATE Command in SQL
▪ Modify attribute values of one or more selected tuples
▪ Additional SET clause in the UPDATE command
o Specifies attributes to be modified and new values
UPDATE <Table Name>
SET <Attribute 1> = <new value>,
<Attribute 2> = <new value>,…
[WHERE <Criteria>]
Content
1. Introduction
2. SQL Data Definition and Data Types
3. INSERT, DELETE, and UPDATE Statements in SQL
4. Basic Retrieval Queries in SQL

Dr. Cao Thi Nhan


Basic Retrieval Queries in SQL
▪ SELECT statement
o One basic statement for retrieving information from a database

SELECT [DISTINCT] attribute list | fucntion


FROM table list
[WHERE condition]
[GROUP BY attribute list of group]
[HAVING condition after group by]
[ORDER BY attribute 1 ASC | DESC, attribute 2 ASC | DESC,… ]
[UNION | INTERSECT | MINUS <Query>]
Basic Retrieval Queries in SQL
▪ Basic SELECT statement

SELECT [DISTINCT] attribute list | fucntion


FROM table list
[WHERE condition]
o Attribute list: a list of attribute name whose values are to be retrieved
by the query
o Table list: a list of relation names required to process the query.
o Condition: is the conditional expression that identifies the tuples to be
retrieved by the query: >, <, =, AND, OR…
Basic Retrieval Queries in SQL
Basic Retrieval Queries in SQL
Basic Retrieval Queries in SQL
▪ Same name can be used for two (or more) attributes
o As long as the attributes are in different relations
o Must qualify the attribute name with the relation name to prevent ambiguity
EMPLOYEE (Fname, Minit, Name, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
DEPARTMENT (Dnumber, Name, Mgr_ssn, Mgr_start_date)
Retrieve the name and address of all employees who work for the ‘Research’
department
SELECT Fname, EMPLOYEE.Name, Address
FROM EMPLOYEE, DEPARTMENT
WHERE DEPARTMENT.Name = ‘Research’
AND DEPARTMENT. Dnumber = EMPLOYEE. Dno
Aliases
▪ Declare alternative relation names, attribute names: [AS] New_Name
EMPLOYEE (Fname, Minit, LName, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
DEPARTMENT (Dnumber, DName, Mgr_ssn, Mgr_start_date)
Retrieve the name and address of all employees who work for the ‘Research’
department
SELECT Fname, E.Lname, Address
FROM EMPLOYEE E, DEPARTMENT D
WHERE D.Name = ‘Research’ AND D. Dnumber = E. Dno
SELECT Fname + ’ ’ + E.Lname as FullName , Address
FROM EMPLOYEE E, DEPARTMENT D
WHERE D.Name = ‘Research’ AND D. Dnumber = E. Dno
Use of the Asterisk (*)
▪ Retrieve all the attribute values of the selected tuples: *
EMPLOYEE (Fname, Minit, LName, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
DEPARTMENT (Dnumber, DName, Mgr_ssn, Mgr_start_date)
Retrieve information of all employees who work for the ‘Research’ department
SELECT *
FROM EMPLOYEE E, DEPARTMENT D
WHERE E.Name = ‘Research’ AND D. Dnumber = E. Dno
Retrieves all the attribute values of any EMPLOYEE who works in
DEPARTMENT number 5
SELECT *
FROM EMPLOYEE
WHERE Dno = 5
Substring Pattern Matching and Arithmetic
Operators
▪ LIKE comparison operator
o Used for string pattern matching
o % replaces an arbitrary number of zero or more characters
o underscore (_) replaces a single character
▪ BETWEEN comparison operator
▪ Standard arithmetic operators:
o Addition (+), subtraction (–), multiplication (*), and division (/)
Substring Pattern Matching and Arithmetic
Operators
▪ Retrieve all employees whose address is in Houston
EMPLOYEE (Fname, Minit, LName, Ssn, Bdate, Address, Sex, Salary, Super_ssn,
Dno)
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Address LIKE ‘%Houston%’;
▪ Retrieve all employees whose salary is from 30.000 USD to 40.000 USD
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Salary BETWEEN 30000 AND 40000;
Substring Pattern Matching and Arithmetic
Operators
▪ Show the resulting salaries if every employee working on the ‘ProductX’
project is given a 10% raise
EMPLOYEE (Fname, Minit, LName, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
PROJECT (Pnumber, Pname, Plocation, Dnum)
WORKS_ON (Essn, Pno, Hours)

SELECT Fname, Lname, Salary*1.1 as Increased_sal


FROM EMPLOYEE E, WORKS_ON W, PROJECT P
WHERE Ssn = Essn AND Pno = Pnumber AND Pname = ‘ProductX’
Ordering of Query Results
▪ Use ORDER BY clause
o Keyword DESC to see result in a descending order of values
o Keyword ASC to specify ascending order explicitly
▪ Show the resulting salaries if every employee working on the ‘ProductX’
project is given a 10% raise.
EMPLOYEE (Fname, Minit, LName, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
PROJECT (Pnumber, Pname, Plocation, Dnum); WORKS_ON (Essn, Pno, Hours)
SELECT Fname, Lname, Salary*1.1 as Increased_sal
FROM EMPLOYEE E, WORKS_ON W, PROJECT P
WHERE Ssn = Essn AND Pno = Pnumber AND Pname = ‘ProductX’
ORDER BY Lname ASC, Fname ASC
Tables as Sets in SQL
▪ SQL does not automatically eliminate duplicate tuples in query results
▪ Use the keyword DISTINCT in the SELECT clause
EMPLOYEE (Fname, Minit, LName, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
Retrieve the salary of every employee
SELECT Salary
FROM EMPLOYEE

SELECT DISTINCT Salary


FROM EMPLOYEE
Tables as Sets in SQL
▪ Set operations: UNION, EXCEPT (difference), INTERSECT
▪ Apply only to type- compatible relations, so we must make sure that the
two relations on which we apply the operation have the same attributes
and that the attributes appear in the same order in both relations.
Tables as Sets in SQL
▪ Set operations: UNION, EXCEPT (difference), INTERSECT
▪ Make a list of all employee that work for project number 1 or work for
project number 2
EMPLOYEE (Fname, Minit, Lname, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
PROJECT (Pnumber, Pname, Plocation, Dnum)
WORKS_ON (Essn, Pno, Hours)
(SELECT Essn FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno AND Pno = 1)
UNION
(SELECT Essn FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno AND Pno = 2)
Tables as Sets in SQL
▪ Set operations: UNION, EXCEPT (difference), INTERSECT
▪ Make a list of all employee that work for project number 1 and do not work
for project number 2
EMPLOYEE (Fname, Minit, Lname, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
PROJECT (Pnumber, Pname, Plocation, Dnum)
WORKS_ON (Essn, Pno, Hours)
(SELECT Essn FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno AND Pno = 1)
EXCEPT
(SELECT Essn FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno AND Pno = 2)
Tables as Sets in SQL
▪ Set operations: UNION, EXCEPT (difference), INTERSECT
▪ Make a list of all employee that work for both project number 1 and project
number 2
EMPLOYEE (Fname, Minit, Lname, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
PROJECT (Pnumber, Pname, Plocation, Dnum)
WORKS_ON (Essn, Pno, Hours)
(SELECT Essn FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno AND Pno = 1)
INTERSECT
(SELECT Essn FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno AND Pno = 2)
Tables as Sets in SQL
▪ Set operations: UNION, EXCEPT (difference), INTERSECT
▪ Make a list of all project numbers for projects that involve an employee
whose last name is ‘Smith’, either as a worker or as a manager of the
department that controls the project
EMPLOYEE (Fname, Minit, Lname, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
DEPARTMENT (Dnumber, Dname, Mgr_ssn, Mgr_start_date)
PROJECT (Pnumber, Pname, Plocation, Dnum)
WORKS_ON (Essn, Pno, Hours)
(SELECT DISTINCT Pnumber FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnumber = Dno AND Mgr_ssn = Ssn AND Lname = ‘Smith’) UNION
(SELECT DISTINCT Pnumber FROM PROJECT, WORKS_ON, EMPLOYEE
WHERE Pnumber = Pno AND Essn = Ssn AND Lname = ‘Smith’)
More complex SQL
▪ Nested queries, joined tables, outer joins, aggregate functions, and
grouping
Comparisons Involving NULL
and Three-Valued Logic
▪ Meanings of NULL
o Unknown value
o Unavailable or withheld value
o Not applicable attribute
▪ Each individual NULL value considered to be different from every other
NULL value
▪ SQL uses a three-valued logic:
o TRUE, FALSE, and UNKNOWN
Comparisons Involving NULL
and Three-Valued Logic
Comparisons Involving NULL
and Three-Valued Logic
▪ SQL allows queries that check whether an attribute value is NULL
o IS or IS NOT NULL
More complex SQL
▪ Nested queries
o Complete select-from-where blocks within WHERE clause of another
query
o Outer query
▪ Comparison operator IN
o Compares value v with a set (or multiset) of values V
o Evaluates to TRUE if v is one of the elements in V
More complex SQL
▪ Nested queries
o Complete select-from-where blocks within WHERE clause of another
query
o Outer query
More complex SQL
Use tuples of values in comparisons
Place them within parentheses
More complex SQL
▪ Use other comparison operators to compare a single value v
o = ANY (or = SOME) operator
➢ Returns TRUE if the value v is equal to some value in the set V and is
hence equivalent to IN
o Other operators that can be combined with ANY (or SOME): >, >=, <, <=,
and <>
More complex SQL
▪ Use other comparison operators to compare a single value v
o = ANY (or = SOME) operator
➢ Returns TRUE if the value v is equal to some value in the set V and is
hence equivalent to IN
o Other operators that can be combined with ANY (or SOME): >, >=, <, <=,
and <>
More complex SQL
▪ Avoid potential errors and ambiguities
o Create tuple variables (aliases) for all tables referenced in SQL query
More complex SQL
▪ EXISTS function
o Check whether the result of a correlated nested query is empty or not
▪ EXISTS and NOT EXISTS
o Typically used in conjunction with a correlated nested query
▪ SQL function UNIQUE(Q)
o Returns TRUE if there are no duplicate tuples in the result of query Q
More complex SQL
▪ Retrieve employees who work on all the projects
EMPLOYEE (Fname, Minit, Lname, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
PROJECT (Pnumber, Pname, Plocation, Dnum)
WORKS_ON (Essn, Pno, Hours)
SELECT *
FROM EMPLOYEE e
WHERE NOT EXITST (SELECT *
FROM PROJECT p
WHERE NOT EXITST (SELECT *
FROM WORKS_ON w
WHERE w.Essn = e.Ssn and w.Pno = Pnumber))
Joined Tables in SQL and Outer Joins
▪ Joined table
o Permits users to specify a table resulting from a join operation in the
FROM clause of a query
▪ The FROM clause in Q1A
o Contains a single joined table
Joined Tables in SQL and Outer Joins
▪ Inner join
o Default type of join in a joined table
o Tuple is included in the result only if a matching tuple exists in the other
relation
▪ LEFT OUTER JOIN
o Every tuple in left table must appear in result
o If no matching tuple: Padded with NULL values for attributes of right table
▪ RIGHT OUTER JOIN
o Every tuple in right table must appear in result
o If no matching tuple: Padded with NULL values for the attributes of left table
▪ FULL OUTER JOIN
Joined Tables in SQL and Outer Joins
▪ Retrieve employees (Ssn, Fname) that do not work on any project
EMPLOYEE (Fname, Minit, Lname, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
WORKS_ON (Essn, Pno, Hours)

SELECT Ssn, Fname


FROM EMPLOYEE e left outer join WORKS_ON w on e.Ssn = w.Essn
WHERE Pno IS NULL
Aggregate Functions in SQL
▪ Used to summarize information from multiple tuples into a single-tuple
summary
▪ Grouping
o Create subgroups of tuples before summarizing
▪ Built-in aggregate functions
o COUNT, SUM, MAX, MIN, and AVG
▪ Functions can be used in the SELECT clause or in a HAVING clause
Aggregate Functions in SQL
▪ NULL values discarded when aggregate functions are applied to a particular
column
Aggregate Functions in SQL
▪ NULL values discarded when aggregate functions are applied to a particular
column
Group by
▪ Partition relation into subsets of tuples
o Based on grouping attribute(s)
o Apply function to each such group independently
▪ GROUP BY clause
o Specifies grouping attributes
▪ If NULLs exist in grouping attribute
o Separate group created for all tuples with a NULL value in grouping
attribute
Group by
▪ For each department, retrieve the department number and the number of
its employees
EMPLOYEE (Fname, Minit, LName, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno)
DEPARTMENT (Dnumber, Dname, Mgr_ssn, Mgr_start_date)
SELECT Dno, count (Ssn) FROM EMPLOYEE
GROUP BY Dno
▪ For each department, retrieve the department number, department name
and the number of its employees
SELECT Dno, Dname, count (Ssn)
FROM EMPLOYEE e join DEPARTMENT d on e.Dno = d.Dnumber
GROUP BY Dno, Dname
Having
▪ Provides a condition on the summary information
▪ For each department that has more than 5 employees , retrieve the
department number, department name and the number of its employees
SELECT Dno, Dname, count (Ssn)
FROM EMPLOYEE e join DEPARTMENT d on e.Dno = d.Dnumber
GROUP BY Dno, Dname
HAVING count(Ssn)>5
View (Virtual Tables) in SQL
▪ Concept of a view in SQL
o Single table derived from other tables called the defining tables
o Considered to be a virtual table that is not necessarily populated
Specification of Views in SQL
CREATE VIEW command
o Give table name, list of attribute names, and a query to specify the
contents of the view
o In V1, attributes retain the names from base tables. In V2, attributes are
assigned names
Specification of Views in SQL
▪ Once a View is defined, SQL queries can use the View relation in the
FROM clause
▪ View is always up-to-date
o Responsibility of the DBMS and not the user
▪ DROP VIEW command
o Dispose of a view
View update
▪ Update on a view defined on a single table without any aggregate
functions
o Can be mapped to an update on underlying base table- possible if the
primary key is preserved in the view
▪ Update not permitted on aggregate views. E.g.,
UV2: UPDATE DEPT_INFO
SET Total_sal=100000
WHERE Dname=‘Research’;

cannot be processed because Total_sal is a computed value in the view


definition
References
1. Ramez Elmasri, and Shamkant B. Navathe, Fundamentals of
Database Systems (7th Ed.), Addison-Wesley, 2016.

2. Carlos Coronel, Steven Morris, Database Systems: Design,


Implementation, and Management (12th Edition), Cengage
Learning Publisher, 2016

3. Richard T. Watson, Data Management: Databases and


Organizations (6th Edition), Prospect Press, 2015.
Q A

You might also like