0% found this document useful (0 votes)
3 views46 pages

SQL Introduction-Part2

IT3290 - Database LAB HUST Slides (Lâm ĐB)

Uploaded by

Giang
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
0% found this document useful (0 votes)
3 views46 pages

SQL Introduction-Part2

IT3290 - Database LAB HUST Slides (Lâm ĐB)

Uploaded by

Giang
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

SQL Language

Contents

• Part 1. SQL Language – Basic


• Part 2. SQL Language – Advanced

Reference:
[Link]
[Link]

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

2
Part 2. SQL LANGUAGE - ADVANCED

• ALTER TABLE
• CONSTRAINTS
• JOIN
• UNION, MINUS, INTERSECT
• ALIAS
• Sub Queries
• Functions

3
Alter Table

• ALTER TABLE command is used to


add, delete or modify columns in an
existing table.

• Add new column:


ALTER TABLE CUSTOMERS
ADD COLUMN SEX char(1);

• Delete a column:
ALTER TABLE CUSTOMERS
DROP COLUMN SEX;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

4
Alter Table

• Modify data type


ALTER TABLE table_name
ALTER COLUMN column_name TYPE datatype;

• Example
ALTER TABLE CUSTOMERS
ALTER COLUMN SEX TYPE VARCHAR(5);

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

5
Alter Table

• Rename column
ALTER TABLE table_name
RENAME COLUMN old_column_name TO
new_column_name

• Example
ALTER TABLE CUSTOMERS
RENAME COLUMN SEX TO Gioitinh;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

6
Alter Table

• Rename table
ALTER TABLE old_table_name
RENAME TO new_table_name

• Example
ALTER TABLE CUSTOMERS
RENAME TO KhachHang;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

7
Constraint

• Constraints are the rules enforced on the data columns of a table.


These are used to limit the type of data that can go into a table
1. NOT NULL Constraint − Ensures that a column cannot have NULL
value.
2. DEFAULT Constraint − Provides a default value for a column
3. UNIQUE Constraint − Ensures that all values in a column are
different.
4. PRIMARY Key − Uniquely identifies each row/record in a table.
5. FOREIGN Key − a column (or set of columns) that references the
PRIMARY KEY or UNIQUE key of another table.
6. CHECK Constraint − The CHECK constraint ensures that all the
values in a column satisfies certain conditions.
7. INDEX − Used to create and retrieve data from the database very
quickly

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

8
NULL

• NULL is the term used to represent a missing


value. A NULL value in a table is a value in a
field that appears to be blank.
• Define the constraint in a new table
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS VARCHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

9
NULL

• Example
SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
WHERE SALARY IS NOT NULL;
• Try with: WHERE SALARY IS NULL;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

10
NULL

• SET NOT NULL


ALTER TABLE CUSTOMERS
ALTER COLUMN AGE SET NOT NULL;

• DROP NOT NULL


ALTER TABLE CUSTOMERS
ALTER COLUMN AGE DROP NOT NULL;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

11
DEFAULT

• Define the constraint in a new table


CREATE TABLE Persons (
ID int NOT NULL,
Name varchar(30),
City varchar(255) DEFAULT 'Sandnes'
);
• Alter an existing table
ALTER TABLE CUSTOMERS
ALTER COLUMN AGE SET DEFAULT 30;
• Drop a DEFAULT constraint
ALTER TABLE CUSTOMERS
ALTER COLUMN AGE DROP DEFAULT;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

12
UNIQUE

• Define the constraint in a new table


CREATE TABLE Persons (
ID int NOT NULL,
Name varchar(30) NOT NULL,
UNIQUE (ID)
);

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

13
UNIQUE

• Alter an existing table


ALTER TABLE CUSTOMERS
ADD UNIQUE(Name);

INSERT INTO CUSTOMERS (Name, Age)


VALUES(‘Muffy’, 30);

ERROR: duplicate key value


violates unique constraint
"customers_name_key"
DETAIL: Key (name)=(Muffy)
already exists

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

14
UNIQUE

• Show Constraints
\d+ CUSTOMERS
• Drop a UNIQUE Constraint
ALTER TABLE CUSTOMERS
DROP CONSTRAINT customers_name_not_null;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

15
UNIQUE

• Alter an existing table


ALTER TABLE CUSTOMERS
ADD CONSTRAINT name_age UNIQUE(Name, Age);

• Show all Constraints


\d+ CUSTOMERS

• Drop a UNIQUE Constraint


ALTER TABLE CUSTOMERS
DROP CONSTRAINT name_age;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

16
Primary Key

• The PRIMARY KEY constraint uniquely identifies each


record in a table.
• Primary keys must contain UNIQUE values, and cannot
contain NULL values.
• A table can have only ONE primary key; and in the
table, this primary key can consist of single or multiple
columns (fields).
• Define the constraint in a new table
CREATE TABLE Persons ( CREATE TABLE Persons (
ID int NOT NULL, ID int PRIMARY KEY,
Name varchar(30), Name varchar(30)
PRIMARY KEY (ID) );
);

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

17
Primary Key

• Drop a Primay key constraint


ALTER TABLE table_name
DROP CONSTRAINT constraint_name;

ALTER TABLE persons


DROP CONSTRAINT pk_person;

• Alter an existing table


ALTER TABLE Persons
ADD PRIMARY KEY (ID);
OR
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID);
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Inform ation and Com m unication Technology

18
Foreign Key

A field (or collection of fields) in one table, that refers to


the Primary key in another table.

CREATE TABLE customers ( CREATE TABLE ORDERS (


id SERIAL PRIMARY KEY, id INT,
name TEXT NOT NULL, order_date TIMESTAMP,
age INT, customer_id INT,
address TEXT NOT NULL, amount INT,
salary NUMERIC(10,2) PRIMARY KEY (id)
); );

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

19
Foreign Key

• Define the constraint in a new table


CREATE TABLE Orders (
ID int NOT NULL,
ORDER_DATE timestamp,
CUSTOMER_ID int,
AMOUNT int,
PRIMARY KEY (ID),
CONSTRAINT FK_CustomerID FOREIGN KEY
(CUSTOMER_ID) REFERENCES Customers(ID));
• Drop a Foreign key constraint
ALTER TABLE Orders
DROP CONSTRAINT FK_CustomerID;
• Alter an existing table
ALTER TABLE Orders
ADD CONSTRAINT FK_CustomerID
FOREIGN KEY (CUSTOMER_ID) REFERENCES Customers(ID);
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Inform ation and Com m unication Technology

20
On Delete/Update Cascade

• Delete/update the rows from the child table automatically, when the
rows from the parent table are deleted/updated
• Define the constraint in a new table
CREATE TABLE Orders2 (
ID int NOT NULL,
ORDER_DATE timestamp,
CUSTOMER_ID int,
AMOUNT int,
PRIMARY KEY (ID),
CONSTRAINT FK_CustomerID FOREIGN KEY
(CUSTOMER_ID) REFERENCES Customers(ID)
ON DELETE CASCADE
ON UPDATE CASCADE
);
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Inform ation and Com m unication Technology

21
On Delete/Update Cascade

• Alter an existing table


• Drop the foreign key
• Add constraint

\d+ Orders2;

ALTER TABLE Orders2


DROP CONSTRAINT FK_CustomerID;

ALTER TABLE Orders2


ADD CONSTRAINT FK_CustomerID FOREIGN KEY
(CUSTOMER_ID) REFERENCES Customers(ID)
ON DELETE CASCADE
ON UPDATE CASCADE;
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Inform ation and Com m unication Technology

22
CHECK

• Define the constraint in a new table


CREATE TABLE Persons (
ID int PRIMARY KEY,
Name varchar(255) NOT NULL,
Age int,
CHECK (Age>=18)
);

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

23
CHECK

• Alter an existing table


ALTER TABLE CUSTOMERS
ADD CHECK(Age>=18);

• DROP a CHECK constraint


ALTER TABLE CUSTOMERS
DROP CONSTRAINT customers_age_check;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

24
Join

• Joins clause is used to combine records from


two or more tables in a database.
• A JOIN is a means for combining fields from
two tables by using values common to each.

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

25
Join Types

• (Inner) Join: return records that have matching values in both tables
• Left (Outer) Join: return all records from the left table, and the
matched records from the right table
• Right (Outer) Join: return all records from the right table, and the
matched records from the left table
• Full (Outer) Join: return all records when there is a match in either
left or right table

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

26
Inner Join

• Return records that have matching values in both tables


• Syntax
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field
• Example
SELECT [Link], NAME, AMOUNT, ORDER_DATE
FROM CUSTOMERS INNER JOIN ORDERS
ON [Link] = ORDERS.CUSTOMER_ID;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

27
Left Join

• Left (Outer) Join: return all records from the left table, and the
matched records from the right table
• Syntax
SELECT table1.column1, table2.column2...
FROM table1 LEFT JOIN table2
ON table1.common_field = table2.common_field;
• Example
SELECT [Link], NAME, AMOUNT, ORDER_DATE
FROM CUSTOMERS LEFT JOIN ORDERS
ON [Link] = ORDERS.CUSTOMER_ID;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

28
Right Join

• Right (Outer) Join: return all records from the right table, and the
matched records from the left table
• Syntax
SELECT table1.column1, table2.column2...
FROM table1 RIGHT JOIN table2
ON table1.common_field = table2.common_field;
• Example
SELECT [Link], NAME, AMOUNT, ORDER_DATE
FROM CUSTOMERS RIGHT JOIN ORDERS
ON [Link] = ORDERS.CUSTOMER_ID;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

29
Full Join

• Full (Outer) Join: return all records when there is a match in either left or right table
• Syntax
SELECT [Link], NAME, AMOUNT, ORDER_DATE
FROM CUSTOMERS FULL JOIN ORDERS
ON [Link] = ORDERS.CUSTOMER_ID;
• Or use UNION
SELECT [Link], NAME, AMOUNT, ORDER_DATE
FROM CUSTOMERS LEFT JOIN ORDERS
ON [Link] = ORDERS.CUSTOMER_ID
UNION
SELECT [Link], NAME, AMOUNT, ORDER_DATE
FROM CUSTOMERS RIGHT JOIN ORDERS
ON [Link] = ORDERS.CUSTOMER_ID;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

30
CARTESIAN JOIN

• Returns the Cartesian product of the set of


records from two or more tables.

• Syntax
SELECT table1.column1,
table2.column2...
FROM table1, table2 [, table3 ]

• Example
SELECT [Link], NAME,
AMOUNT, ORDER_DATE
FROM CUSTOMERS, ORDERS;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology
Join

• Example:
SELECT [Link], NAME,
AGE, AMOUNT
FROM CUSTOMERS, ORDERS
WHERE [Link] =
ORDERS.CUSTOMER_ID;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

32
Self Join

• Join a table to itself; temporarily renaming at least one


table in the SQL statement.
• Syntax
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_field = b.common_field;
• Example
SELECT [Link], [Link], [Link]
FROM CUSTOMERS a, CUSTOMERS b
WHERE [Link] < [Link];

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

33
Union

• UNION clause/operator is used to combine the results of


two or more SELECT statements without returning any
duplicate rows. To use this UNION clause, each SELECT
statement must have:
• The same number of columns selected
• The same data type and
• Have them in the same order
• UNION ALL: allows duplicate rows in the result
• Syntax
SELECT column1 [, column2 ]
FROM table1 [, table2 ] [WHERE condition]
UNION
SELECT column1 [, column2 ]
FROM table1 [, table2 ] [WHERE condition]
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Inform ation and Com m unication Technology

34
Union

SELECT ID, NAME FROM CUSTOMERS


WHERE AGE>=25
UNION
SELECT ID, NAME FROM CUSTOMERS
WHERE SALARY >=5000;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

35
MINUS, INTERSECT

• MINUS/EXCEPT returns all records/rows in the first SELECT


statement that are not returned by the second SELECT statement
• Oracle supports MINUS
• PostgreSQL support EXCEPT
• INTERSECT returns all records/rows in both SELECT statements
• Remove duplicate records/rows
• MySQL does not support INTERSECT

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

36
ALIAS

• We can rename a table or a column temporarily by


giving another name known as Alias. The actual table
name does not change in the database.
• Syntax
SELECT column_name AS alias_name
FROM table_name
WHERE [condition];
• Example
SELECT ID AS CUSTOMER_ID, NAME AS
CUSTOMER_NAME
FROM CUSTOMERS
WHERE SALARY IS NOT NULL;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

37
Sub Queries

• A Subquery or Inner query or a Nested query is a query


within another SQL query and embedded within the
WHERE clause.

• Syntax
SELECT column_name…
FROM table…
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table [WHERE])

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

38
Operators

• IN: is used to check whether a specific value matches


any value in a list
• Syntax:
SELECT column1, column2,…
FROM table1, table2,…
WHERE column1 IN (‘value1’,
‘value2’,…);
• NOT IN: is opposite IN
• EXISTS: is used to check whether the subquery returns
any record/row
WHERE EXISTS (subquery)
• NOT EXISTS: is opposite EXISTS

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

39
Functions

• Some aggregrate functions


• MAX/MIN
• SUM
• AVG
• COUNT
• Customers have the highest salary
SELECT Name FROM CUSTOMERS
WHERE Salary >= ALL(SELECT Salary FROM
CUSTOMERS);
• Count the number of Customers
SELECT COUNT(ID) FROM CUSTOMERS;
• Highest salary
SELECT MAX(Salary) FROM CUSTOMERS;
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Inform ation and Com m unication Technology

40
DATE

• CURRENT_TIME: the current time


• Example: SELECT CURRENT_TIME;
• Result: 06:44:17.155054+07
• NOW(): the current date + time
• Example: SELECT NOW();
• Result: 2026-03-12 06:43:38.414362+07
• The difference between expr1 and expr2.
• Example: SELECT DATE '2026-03-12' - DATE
'2026-03-01' as Result;
• Result: 11
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Inform ation and Com m unication Technology

41
Sub Queries - Example

SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500);

SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT CUSTOMER_ID
FROM ORDERS) ;

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

42
Structure of a query

SELECT [DISTINCT] <column 1>,


<column 2>, …
FROM <table 1>,<table 2>, …
[WHERE <condition>]
[GROUP BY <column 1>, <column 2>, …
[HAVING <condition>]]
[ORDER BY <column 1> [ASC|DESC]]

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

43
Excercise

• Give a relational database containing some tables:


• student(sid, firstname, lastname, address, city, dob,
gender)
• course(cid, name, credit, weight)
• registration(sid, cid, semester, midterm, finalterm)
• Write SQL queries to perform following requirements:
1. Define the database and tables above.
2. Insert data into tables. Each table should contain at
least 5 rows
Note: default format of date value is ‘YYYY-MM-DD’ e.g.,
‘2010-10-10’
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Inform ation and Com m unication Technology

44
Cơ bản
1. Liệt kê tất cả thông tin của sinh viên.
2. Liệt kê họ, tên và thành phố của sinh viên.
3. Tìm các sinh viên sống ở Hà Nội.
4. Tìm các sinh viên sinh sau ngày 01/01/2006.
5. Liệt kê thông tin từng sinh viên cùng danh
sách môn học mà họ đã đăng ký (kèm học kỳ
học)
6. Liệt kê thông tin các môn học được mở ở học
kỳ 20252

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

45
Tính toán & tổng hợp
1. Tìm điểm tổng kết cao nhất của môn học
IT3292 trong học kỳ 20252
2. Cho biết mỗi sinh viên đã đăng ký bao nhiêu
môn trong từng học kỳ
3. Hiển thị thông tin sinh viên, môn học, kỳ học
và điểm tổng kết của môn học đó
4. Hiển thị thông tin sinh viên và điểm trung
bình của học kỳ 20252
5. Tìm điểm trung bình GPA cao nhất trong học
kỳ 20252
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Inform ation and Com m unication Technology

50

You might also like