T03 SQL
T03 SQL
T03 SQL
Example Tables
SELECT Definition
Selecting Columns
Selecting Rows
Sorting
Aggregation
Grouping
Restricting Groups
Aliasing Table Names
Nested Queries
Join
Set Operations
September 18, 2023 DB: SQL 2
September 18, 2023 ICS324 3
FIGURE 7.2
Result of mapping the COMPANY ER schema into a relational schema.
SQL has only one statement for retrieving information from a database called the
SELECT statement, and it consists of six main clauses or components.
Renaming Columns
Select ssn, salary*1.1 as new_salary
from employee
September 18, 2023 DB: SQL 6
Selecting Rows
Null Search
Select * from employee where super_ssn is NULL;
Sorting Rows
Select * from employee
order by fname;
COUNT, MIN, and MAX apply to numeric and non-numeric fields, but SUM
and AVG may be used on numeric fields only.
Apart from COUNT(*), each function eliminates nulls first and operates
only on remaining non-null values.
Inner join
Full join
Inner select
SELECT *
FROM employee
WHERE salary > (
select avg(salary)
from employee
);
Outer select
List the names of all employees who are in the Research department
Nested Query
Find employee whose salary higher than the salary of at least one employee in
Research department.
SELECT *
FROM employee
WHERE salary > (
SELECT min(salary)
FROM employee
WHERE dno = (
SELECT dnumber
FROM department
WHERE dname = "Research"
)
);
SELECT *
FROM employee
WHERE salary > (
SELECT max(salary)
FROM employee
WHERE dno = (
SELECT dnumber
FROM department
WHERE dname = "Research"
)
);
Can use normal set operations of union, intersection, and difference to combine
results of two or more queries into a single result table.
Union of two tables, A and B, is table containing all rows in either A or B or both.
SELECT salary
FROM employee
WHERE dno =
( SELECT dnumber
FROM department
WHERE dname = "Research"
)
UNION
SELECT salary
FROM employee
WHERE dno =
( SELECT dnumber
FROM department
WHERE dname = "Administration"
)
SELECT salary
FROM employee
WHERE dno =
( SELECT dnumber
FROM department
WHERE dname = "Research"
)
UNION ALL
SELECT salary
FROM employee
WHERE dno =
( SELECT dnumber
FROM department
WHERE dname = "Administration"
)
DIFFERENCE
List salaries that are taken by Research and not Administration employees.
SELECT salary
FROM employee
WHERE dno = (
SELECT dnumber
FROM department
where dname = "Research"
)
MINUS
SELECT salary
FROM employee
WHERE dno = (
SELECT dnumber
FROM department
WHERE dname= "Administration“
)
INTESECTION
List salaries that are taken by Research and not Administration employees.
SELECT salary
FROM employee
WHERE dno = (
SELECT dnumber
FROM department
where dname = "Research"
)
INTERSECT
SELECT salary
FROM employee
WHERE dno = (
SELECT dnumber
FROM department
WHERE dname= "Administration"
)
https://www.w3schools.com/
https://www.db-fiddle.com/
http://sqlfiddle.com/ sql/