Introduction To Standard Query Language: Erik Zeitler Udbl Erik - Zeitler@it - Uu.se
Introduction To Standard Query Language: Erik Zeitler Udbl Erik - Zeitler@it - Uu.se
Erik Zeitler
UDBL
erik.zeitler@it.uu.se
Why a query language?
Given some data,
how should users
and computer programs
communicate with it?
Ex 2, projection!
> select x,y,z from vectors;
> select x,y from vectors;
The SQL SELECT clause
• Projection
• Arithmetic expressions
> select x/10, (y*z)/2, z+3 from vectors;
> select ssn, salary, salary*.327 from employee; #
Relational algebra selection
SELECT A1, A2, …, An
FROM r1, r2, …, rm
WHERE P;
• P is the selection predicate
• operates on attributes in relations r1, r2, …, rm
• Selects tuples to be returned
• selection filtering
• Ex 3, vector length!
> select x,y,z from vectors
where x > 10 and x*x+y*y+z*z < 200;
Rel. algebra Cartesian product
Similar to Cartesian product of two vectors
v1 w1 v1 wn
v1 v2 vn w1 w2 wn
v w vn wn
n 1
The Cartesian product forms
all possible pairs
of the elements
of the operands
The SQL FROM clause
Similarly, given two select *
from persons, cars;
database tables
Alex Audi
John Audi
persons cars
Mike Audi
Alex Audi Alex BMW
John
x BMW
=
John BMW
Mike Mercedes Mike BMW
Alex Mercedes
, this SQL query generates John Mercedes
all possible persons-cars Mike Mercedes
combinations.
More… #
Select … from … where
revisited
#
SQL and the relational data model
SELECT … FROM … WHERE … • Assignment operator
• Rename relations
projection,
• Join
cartesian product,
selection
join
• Equijoin
• Set operations • Natural join
• Union – union
• Difference – except
• Intersection – intersect
Rename, assignment
• Rename: as
> select distinct superssn
as ’manager social security number’
from employee;
• Equijoin
• of employee and department tables
• w.r.t. employee.dnumber and department.dno.
• Solution: NULL.
• What about logical operations involving NULL?
Need to extend logic…
3-valued logic
AND TRUE FALSE UNKNOWN
TRUE TRUE FALSE UNKNOWN
FALSE FALSE FALSE FALSE
UNKNOWN UNKNOWN FALSE UNKNOWN
• JOIN operations
• Tuples with NULL values in the join columns
Not included in result
• Exception: OUTER JOIN (E/N 8.5.6)
NULL
• Find out who is The Big Boss
select fname, lname
from employee
where superssn is NULL;
Aggregate functions
• Avg – average value
• Min – minimum value
• Max – maximum value
• Sum – sum of values
• Count – number of values
Aggregate functions – group by
• Average salary
select avg(salary)
from employee;
• Consequence:
underlying tables are changed
the view will change
Views
• Ex 1:
> update table employee
set salary = 1000000
where ssn = 123456;
• Ex 2:
We are removing one column!
> alter table employee drop salary;