COMP163: Database Management Systems September 18, 2008
COMP163: Database Management Systems September 18, 2008
48 commands listed in
SQL in a Nutshell
SQL Queries
Queries in SQL are variations
of the SELECT command
project
select
Single Table Queries ( and )
Ssn (Salary > 60000 (EMPLOYEE) )
SELECT Ssn
FROM EMPLOYEE
WHERE Salary > 60000;
SELECT *
FROM EMPLOYEE
WHERE DNO=5
SELECT *
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND
DNO=DNUMBER
Tables as Sets DISTINCT
SQL does not treat a relation as a set;
duplicate tuples can appear
To eliminate duplicate tuples in a query result,
the keyword DISTINCT is used
SELECT SALARY
may contain duplicates
FROM EMPLOYEE
(SELECT PNAME
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith')
UNION
(SELECT PNAME
FROM PROJECT, WORKS_ON, EMPLOYEE
WHERE PNUMBER=PNO AND ESSN=SSN AND NAME='Smith')
Multiset Operations
UNION ALL, INTERSECT ALL, EXCEPT ALL
Multiset operation results are multisets of
tuples
duplicate tuples are not eliminated
(SELECT PNAME
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith')
UNION ALL
(SELECT PNAME
FROM PROJECT, WORKS_ON, EMPLOYEE
WHERE PNUMBER=PNO AND ESSN=SSN AND NAME='Smith')
WHERE Clause
WHERE clause is a general boolean expression
Boolean operators:
AND, OR, NOT
Comparison operators:
=, <, <=, >, >=, <>
String comparison operators:
LIKE
zero or more
characters, before
and after substring
String Comparison Example
Retrieve all employees who were born during the
1960s.
example:
for each project that has more than two employees,
get the project name, project number and
the number of employees working on that project
SELECT Pnumber, Pname, COUNT(*)
FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno
GROUP BY Pnumber, Pname
HAVING COUNT(*) > 2
GROUP BY Examples
SELECT COUNT(*) FROM e
GROUP BY dept;
+----------+
SELECT * FROM e; | count(*) |
+-----+--------+-------+ +----------+
| eid | salary | dept | | 3 |
+-----+--------+-------+ | 3 | SELECT dept, COUNT(*)
| E01 | 65000 | ADMIN | | 1 | FROM e GROUP BY dept;
| E12 | 58400 | ENGR | +----------+ +-------+----------+
| E08 | 76900 | ENGR | | dept | count(*) |
| E23 | 63800 | ADMIN | +-------+----------+
| E07 | 56900 | ADMIN | | ADMIN | 3 |
| E27 | 76400 | ENGR | | ENGR | 3 |
| E14 | 48000 | TEST | | TEST | 1 |
+-----+--------+-------+ +-------+----------+
GROUP BY Examples
SELECT dept, COUNT(*) SELECT dept, AVG(salary)
FROM e FROM e
GROUP BY dept GROUP BY dept
HAVING COUNT(*) > 1; HAVING COUNT(*) > 1;
+-------+----------+ +-------+-------------+
| dept | count(*) | | dept | AVG(salary) |
+-------+----------+ +-------+-------------+
| ADMIN | 3 | | ADMIN | 61900 |
| ENGR | 3 | | ENGR | 70566.66667 |
+-------+----------+ +-------+-------------+
Nested Queries
Nested queries can be used as set values
in the WHERE clause