Week3-Basic SQL
Week3-Basic SQL
Week 03
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
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’
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
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
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
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