CS486 – Introduction to Databases
Week 03
Basic SQL Queries
Lecturer: Lê Thị Nhàn, PhD.
TA: Vũ Thị Mỹ Hằng, PhD.
Hồ Thị Hoàng Vy, MSc.
Phan Thị Phương Uyên, MS
CS486 – Introduction to Databases
W03 – Basic SQL queries
1 Notes
Put ALL SQL statements to ONE text (SQL) document names student ID 1651xxx_W03.sql:
● Comment Student ID and Full name on top of file
● Run ALL lines in the file without any error
● USE the RIGHT database
This lab helps students to use SQL statement to write some queries:
- Understanding basic syntax of SQL (Structure Query Language)
- Order By clause
- Using operators in WHERE clause: AND OR NOT, >, <, = , IS NULL , IN, BETWEEN, LIKE
- Using function in WHERE clause (String functions, Date time functions, Math functions)
- Using operators and functions in SELECT clause
- Naming for a output column
- Using JOIN operators to retrieve information in tables (ALIAS, JOIN, LEFT JOIN, RIGHT JOIN,
FULL JOIN)
2
CS486 – Introduction to Databases
W03 – Basic SQL queries
1. Basis SQL Syntax
SELECT [ALL | DISTINCT | TOP(n)] <attributes_list 1>
FROM <table1, table2, table3, …>
[WHERE <search_condition_1> ]
[GROUP BY <attributes_list_2> ]
[HAVING < search_condition_2> ]
[ORDER BY <atribute1 ASC|DESC, atribute2 ASC|DESC, …> ]
SQL conditions can be simple comparison: >, <, = (not ==), >=, <=, <> (not !=) or check IS NULL or IS
NOT NULL or set operation IN, NOT IN, EXISTS, NOT EXISTS or pattern matching LIKE. SQL
conditions can be combined by logical operators AND, OR, and NOT.
1. Retrieve all data of a table
Ex: Retrieve the information of instructors
Select *
From instructors
2. Retrieve some specific columns
Ex: Retrieve (instructor_id, instructor_name) of instructors
Select instructor_id, instructor_name
From Instructors
3. Retrieve data with condition in WHERE clause
Ex: Retrieve (student_name, gender) of Students belonging to class 21CTT1.
Select student_name, gender
From Student
Where class = ‘21CTT1’
4. Retrieve (student_name, student_id) of the female students belonging to class 21CTT1
Select student_name, gender
From Student
Where gender = ‘F’ and class = ‘21CTT1’
5. Retrieve the students whose name start with letter ‘H’
Select *
From student
Where student_name like ‘H%’
6. Retrieve the students belonging to department 4 or department 1
3
CS486 – Introduction to Databases
W03 – Basic SQL queries
Select *
From student
Where department_id IN (1,4)
OR:
Select *
From student
Where department_id = 2 OR department_id = 4
7. Retrieve the instructors having no phone
Select *
From instructors
Where phone IS NULL
8. Retrieve the instructor_id of instructors who have taught in the role of "lecturer."
Select distinct instructor_id
From instructors
Where role = ‘Lecturer’
Some datetime functions:
- year: get the year value of a datetime input
- month: get the month value of a datetime input
- day: get the day value of a datetime input
- datepart: get part values of datetime value
- datediff: calculate the distance (by day, month or year, …) of 2 datetime inputs
- getdate: return the current date
9. Retrieve the Students born in 2000
Select *
From student
Where year(birthdate) = 2000
10. Retrieve (student_name, Age) of the Students belonging in class 21CTT1. The result should be
sorted in ascending order by their age
Select student_name, datediff(yyyy, birthdate, getdate()) as Age
From student
Where class = ‘21CTT1’
Order by Age
4
CS486 – Introduction to Databases
W03 – Basic SQL queries
SQL UNION, INTERSECT, EXCEPT
- The SQL UNION operator combines the results of two SELECT statements which have the same
columns and same data-type in each column. UNION operator will return all different values.
However, if you want to list all values, using UNION ALL instead of UNION.
- EXCEPT return rows from data set 1 what doesn’t exists in data set 2 and eliminates duplicates
rows
- INTERSECT returns rows that appear in both data sets and eliminate duplicate rows
Example:
11. Retrieve instructor_name of instructors who have a salary greater than 2000 or instructors with the
name ‘John’
Select instructor_name From instructor where salary >2000
Union - - union All
Select instructor_name from instructor where name like ‘%John’
12. Retrieve instructor_id of instructors who have not participated in teaching in the role of "lecturer".
Select instructor_id From instructor
Except
Select instructor_id From Teaching where role = ‘Lecturer’
SQL JOIN
Join condition in WHERE clause
13. Retrieve the student’s name and their department’ name.
Select *
From student, Department
Where student.Department_id = Department.department_id
OR:
Select *
From student s, Department d -- alias
Where s.Department_id = d.department_id
If a SQL join condition (s.Department_id = d.department_id) is omitted, the join operation will result in
a Cartesian product. The Cartesian product returns a number of rows equal to the product of all rows in
all the joined tables. For example, if the first table has 20 rows and the second table has 10 rows, the
result will be 20 * 10 or 200 rows
5
CS486 – Introduction to Databases
W03 – Basic SQL queries
JOIN operators (Inner JOIN, Left JOIN, Right JOIN)
- Inner JOIN
Select *
From student s inner join Department d ON s.Department_id = d.department_id
- Left JOIN
Select *
From student s left join Department d ON s.Department_id = d.department_id
- Right JOIN
Select *
From student s right join Department d ON s.Department_id = d.department_id
GROUP BY
- Count the number of instructors for each department_ID
Select department_ID, count (instructor_ID)
From Instructor
Group by department_ID
GROUP BY + HAVING
- Count the number of instructors for each department_ID and only display the departments that
have more than 3 instructors.
Select department_ID, count (instructor_ID)
From Instructor
Group by department_ID
Having count (instructor_ID) >3