dbs06 05 DML SQL-1pp
dbs06 05 DML SQL-1pp
Query data
Interactively
(Embedded in host language)
2
SQL / DML: Insert data
Complete form:
Predefined order of values
Incomplete form:
Free order of values
FU-Berlin, DBS I 2006, Hinze / Scholz
3
SQL / DML: Insert data
Inserting dates
INSERT INTO movie
VALUES (95, 'Psycho', 'suspense',
TO_DATE('1969', 'yyyy'),
'Hitchcock', 2.00, NULL);
Conversion functions
String to date
TO_DATE(<string>[,<format>]) ORACLE/Postgres
FU-Berlin, DBS I 2006, Hinze / Scholz
Date to string
TO_CHAR(<date>[,<format>]) ORACLE/Postgres
4
SQL / DML: Insert data
Loading data from files
System dependent
Oracle:
INSERT INTO
Bulk load from file: SQL loader
Bulk load from other database: export / import tool
MySQL:
INSERT INTO
Bulk load: LOAD DATA
Bulk load from other database:
SELECT INTO OUTFILE, LOAD DATA
FU-Berlin, DBS I 2006, Hinze / Scholz
Postgres:
INSERT INTO
Bulk load: Copy
Bulk load from other database: Copy
5
SQL / DML: Implementations of bulk load
Oracle SQL loader
control file data file
SQL*Loader
rejected
field processing
rows
discarded
rows record selection
bad file
FU-Berlin, DBS I 2006, Hinze / Scholz
6
SQL / DML: Implementations of bulk load
loadtest.dat
Example: CREATE TABLE loadtest(
name varchar(20), 'four'
'four' ,, 44
num number(10,2)); 'five'
'five' ,, 55
'six'
'six' ,, 66
Oracle Syntax:
sqlldr <user>/<password> <controlfile>
<logfile> <badfile> <datafile>
loadtest.ctl
load
load data
data
infile
infile 'loadtest.dat'
'loadtest.dat'
badfile
badfile 'loadtest.bad'
'loadtest.bad'
FU-Berlin, DBS I 2006, Hinze / Scholz
discardfile
discardfile 'loadtest.dis'
'loadtest.dis'
APPEND
APPEND INTOINTO table
table loadtest
loadtest
fields
fields terminated
terminated byby "" ,, ""
optionally
optionally enclosed
enclosed by
by "" '' ""
(name
(name char,
char, numnum integer
integer external)
external)
7
SQL / DML: Implementations of bulk load
MySQL Example:
Mysql>
Mysql> LOAD
LOAD DATA
DATA INFILE
INFILE 'loadtest.dat'
'loadtest.dat'
->
-> IGNORE
IGNORE
->
-> INTO
INTO TABLE
TABLE loadtest
loadtest
->
-> FIELDS
FIELDS
->
-> TERMINATED
TERMINATED BYBY ","
","
->
-> OPTIONALLY
OPTIONALLY ENCLOSED
ENCLOSED BYBY ''
''
->
-> (name,
(name, num
num );
);
Query
Query OK,
OK, 33 rows
rows affected
affected (0.01
(0.01 sec)
sec)
Records:
Records: 33 Deleted:0
Deleted:0 Skipped:
Skipped: 00 Warnings:
Warnings: 00
FU-Berlin, DBS I 2006, Hinze / Scholz
8
SQL / DML: Insert unique data
For synthetic keys, e.g. tapeId,
10
SQL / DML: Insert unique data - sequence
Value Access
<seqName>.NEXTVAL = value of last call + increment
<seqName>.CURRVAL = value of last call
Example:
INSERT INTO tape
FU-Berlin, DBS I 2006, Hinze / Scholz
11
SQL / DML: Delete data
Syntax:
DELETE from <tableName>
[WHERE <predicate>];
Example:
DELETE from tape
FU-Berlin, DBS I 2006, Hinze / Scholz
12
SQL / DML: Update data
Syntax:
UPDATE <tableName>
SET <attr> = <value>
{,<attr> = <value> }
WHERE <predicate>
UPDATE Rental
SET until_date = SYSDATE
FU-Berlin, DBS I 2006, Hinze / Scholz
WHERE tape_ID = 3
AND mem_no = 200
AND TO_CHAR(from_date,'yyyy-mm-dd')='2002-05-01';
13
SQL / DML: Example database
insert into customer values (001, 'Mller', 'Tina', NULL,NULL);
insert into customer values (007, 'Katz', 'Anna', NULL,NULL);
insert into customer values (002, 'Maus', 'Carla', NULL,NULL);
....
15
SQL / DML: Querying Language
SQL is relational complete
Arithmetic in expressions,
e.g., number of tapes for each movie
e.g., total receipts of each movie within the last year
16
SQL / DML: Basics
Basic query pattern:
SELECT [DISTINCT] A1, A2,...,An
FROM R1, R2,...Rm
WHERE predicate P;
Mller
Katz
Katz
Maus
Maus
Hinz
Hinz
Kunz
Kunz
Mller
Mller
18
SQL / DML: Basics
Eliminating duplicates:
Targetlist contains KEY attribute
Targetlist constrains UNIQUE attribute
Targetliste defined with DISTINCT
Maus Kunz
11
11 Hinz
Hinz Maus
Maus
23
23 Kunz
Kunz Mller
Mller
111
111 Mller
Mller
19
SQL / DML: Basics
WHERE-clause structure:
20
SQL / DML: Simple queries
Example: All customers named Anna
SQL>
SQL> select
select mem_no,
mem_no, last_name,
last_name, first_name
first_name
22 from
from customer
customer
33 where
where first_name='Anna';
first_name='Anna';
MEM_NO
MEM_NO LAST_NAME
LAST_NAME FIRST_NAME
FIRST_NAME
----------
---------- ------------------------------
------------------------------ --------------
--------------
77 Katz
Katz Anna
Anna
23
23 Kunz
Kunz Anna
Anna
director='Lucas'
44 and
and to_char(year,'yyyy')>='1999';
to_char(year,'yyyy')>='1999';
ID
ID TITLE
TITLE
----------
---------- ---------------------------------------------
---------------------------------------------
345
345 Star
Star Wars
Wars II
21
SQL / DML: Simple queries
More examples:
FROM Rental
WHERE until_date IS NULL;
22
SQL / DML: Simple queries - expressions
Core
LIKE - expression SQL:1999
Simple form of regular expression
% : any sequence of characters
_ : exactly one character
Example:
All star wars movies
SQL>
SQL> select
select id,
id, title,
title, director
director
22 from movie
from movie
33 where
where title
title like
like 'Star
'Star Wars
Wars %';
%';
FU-Berlin, DBS I 2006, Hinze / Scholz
ID
ID TITLE
TITLE DIRECTOR
DIRECTOR
----------
---------- ------------
------------ ---------------
---------------
345 Star Wars I Lucas
345 Star Wars I Lucas
290
290 Star
Star Wars
Wars IV
IV Lucas
Lucas
23
SQL / DML: Simple queries - expressions
enhanced
SIMILAR - expression SQL:1999
Advanced form of regular expression
Example:
24
SQL / DML: Simple queries
Member in set: IN
FROM Movie
WHERE (director, year)
IN (('Lucas',to_date(1999,'yyyy')));
25
SQL / DML: Simple queries - expressions
Functions
Expressions may contain functions
Arithmetical and string built-in functions
User defined functions on user defined types
TITLE
TITLE DIRECTOR
DIRECTOR
----------------
---------------- ----------------
----------------
ET
ET Spielberg
Spielberg
Psycho
Psycho Spielberg
Spielberg
Jaws
Jaws Spielberg
Spielberg 26
SQL / DML: Simple queries - expressions
Arithmetic function examples
SQRT(<number>)
Basic arithmetic expressions
ID
ID PRICEPDAY
PRICEPDAY TAX
TAX
----------
---------- ----------
---------- ----------
----------
95 22 .32
FU-Berlin, DBS I 2006, Hinze / Scholz
95 .32
112
112 1.5
1.5 .24
.24
345
345 22 .32
.32
222
222 2.2
2.2 .352
.352
290
290 22 .32
.32
100
100 1.5
1.5 .24
.24 27
SQL / DML: Simple queries - expressions
Date function examples
differ heavily between systems
SQL>
SQL> SELECT
SELECT title,
title, to_char(year,'yyyy')
to_char(year,'yyyy') as
as year
year
22 FROM
FROM movie
movie
33 WHERE
WHERE months_BETWEEN(SYSDATE,year)>
months_BETWEEN(SYSDATE,year)> 120
120 ;;
TITLE
TITLE YEAR
YEAR
------------------------
------------------------ ----
----
Psycho 1969
FU-Berlin, DBS I 2006, Hinze / Scholz
Psycho 1969
ET
ET 1982
1982
Jaws
Jaws 1975
1975
28
SQL / DML: Simple queries
Core
Combination of relations SQL:1999
Schema compatible relations
UNION, INTERSECT, EXCEPT
Syntax:
UNION | INTERSECT | EXCEPT
[DISTINCT | ALL]
[CORRESPONDING [BY <attributes>]]
Default DISTINCT
FU-Berlin, DBS I 2006, Hinze / Scholz
30
SQL / DML: Simple queries
More examples:
All movies not by Lucas
(SELECT *
FROM Movie)
EXCEPT
(SELECT * from Movie
WHERE director='Lucas');
FROM Movie)
UNION DISTINCT
(SELECT stage_name as celebrity
FROM Actor);
31
SQL / DML: Implementations combinations
Oracle:
UNION
MINUS implements EXCEPT
INTERSECT
CORRESPONDING [BY] not implemented
PostgreSQL:
UNION
EXCEPT
INTERSECT
CORRESPONDING [BY] not implemented
FU-Berlin, DBS I 2006, Hinze / Scholz
MySQL:
UNION, EXCEPT, INTERSECT not implemented
32
SQL / DML: Simple queries with joins
Core
Simple joins SQL:1999
Search predicates and join conditions mixed
SQL>
SQL> SELECT
SELECT t.id,
t.id, t.format,
t.format, m.id,
m.id, m.title
m.title
22 FROM
FROM Tape
Tape t,
t, Movie
Movie mm
33 WHERE
WHERE m.id
m.id == t.movie_id;
t.movie_id;
ID
ID FORMAT
FORMAT ID
ID TITLE
TITLE
----------
---------- -----
----- ----------
---------- ----------------------------
----------------------------
11 DVD
DVD 95
95 Psycho
Psycho
FU-Berlin, DBS I 2006, Hinze / Scholz
22 DVD
DVD 112 ET
112 ET
33 VHS
VHS 222
222 Psycho
Psycho
44 DVD
DVD 345
345 Star
Star Wars
Wars II
55 VHS
VHS 345
345 Star
Star Wars
Wars II
99 VHS
VHS 345
345 Star
Star Wars
Wars II
33
SQL / DML: Simple queries with joins
enhanced
Cross join (cross product) SQL:1999
Example:
FU-Berlin, DBS I 2006, Hinze / Scholz
SELECT *
FROM Rental NATURAL INNER JOIN Customer;
34
SQL / DML: Simple queries with joins
enhanced
Inner join with attribute list SQL:1999
Example:
SELECT *
FROM Rental r JOIN Customer c
FU-Berlin, DBS I 2006, Hinze / Scholz
USING (mem_no);
35
SQL / DML: Simple queries with joins
enhanced
Inner join with condition SQL:1999
<tableName> [INNER] JOIN <tableName>
ON <condition>
Examples:
SELECT *
FROM Tape t JOIN Movie m
ON t.movie_id = m.id;
SELECT *
FU-Berlin, DBS I 2006, Hinze / Scholz
36
SQL / DML: Simple queries with joins
All Customers who have rented at least one science fiction film
WHERE c.mem_no=r.mem_no
AND t.id = r.tape_id
AND t.movie_id = m.id
AND m.category='Scifi';
37
SQL / DML: Simple queries with joins
enhanced
Natural outer join SQL:1999
<tableName> LEFT|RIGHT|FULL
NATURAL [OUTER] JOIN <tableName>
Example:
FU-Berlin, DBS I 2006, Hinze / Scholz
SELECT *
FROM Rental r RIGHT OUTER JOIN Customer c
ON r.mem_no = c.mem_no;
38
SQL / DML: Simple queries with joins
Example (extended)
SQL>
SQL> SELECT
SELECT r.tape_id,
r.tape_id, r.from_date,
r.from_date, c.mem_no,c.first_name
c.mem_no,c.first_name
22 FROM
FROM Rental
Rental rr RIGHT
RIGHT OUTER
OUTER JOIN
JOIN Customer
Customer cc
33 ONON r.mem_no
r.mem_no == c.mem_no;
c.mem_no;
TAPE_ID
TAPE_ID FROM_DATE
FROM_DATE MEM_NO
MEM_NO FIRST_NAME
FIRST_NAME
----------
---------- ---------
--------- ----------
---------- --------------------
--------------------
33 01-MAY-02
01-MAY-02 11 Tina
Tina
44 01-MAY-02
01-MAY-02 11 Tina
Tina
55 01-MAY-02
01-MAY-02 22 Carla
Carla
23
23 Anna
Anna
111
111 Bert
Bert
11
11 Fritz
Fritz
FU-Berlin, DBS I 2006, Hinze / Scholz
77 Anna
Anna
39
SQL / DML: Implementations of joins
Oracle/Postgres:
Simple join
Cross join
(natural) inner join with attribute list, with condition
(natural) Right, left, full outer join with condition
MySQL:
Simple join
Cross join
FU-Berlin, DBS I 2006, Hinze / Scholz
SQL>
SQL> SELECT
SELECT m.title
m.title asas Movies,
Movies, t.id,
t.id, t.format
t.format
22 FROM
FROM Movie
Movie m,
m, Tape
Tape tt
33 WHERE
WHERE m.id
m.id == t.movie_id
t.movie_id
44 ORDER
ORDER BY
BY title;
title;
MOVIES
MOVIES ID
ID FORMAT
FORMAT
------------------------------------
------------------------------------ --------
-------- ------
------
ET 22 DVD
FU-Berlin, DBS I 2006, Hinze / Scholz
ET DVD
Psycho
Psycho 11 DVD
DVD
Psycho
Psycho 33 VHS
VHS
Star
Star Wars
Wars II 44 DVD
DVD
Star
Star Wars
Wars II 55 VHS
VHS
Star
Star Wars
Wars II 99 VHS
VHS
41
SQL / DML: Improving the output
Syntax:
ORDER BY <orderexpression> ASC|DESC
Ordering expression
No advanced expressions (no sub-query, no grouping)
At least one attribute reference
References in order expression result attributes
SQL>
SQL> SELECT
SELECT m.title,
m.title, t.id,
t.id, t.format
t.format
22 FROM
FROM Movie
Movie m,
m, Tape
Tape tt
33 WHERE
WHERE m.id
m.id == t.movie_id;
t.movie_id;
Movies
Movies ID
ID FORMAT
FORMAT
FU-Berlin, DBS I 2006, Hinze / Scholz
---------------
--------------- ----------
---------- ------
------
Psycho
Psycho 11 DVD
DVD
ET
ET 22 DVD
DVD
Psycho
Psycho 33 VHS
VHS
Star
Star Wars
Wars II 44 DVD
DVD
55 VHS
VHS
99 VHS 43
VHS
SQL / DML: Sub-queries
Core
Sub-queries with single results SQL:1999
Operators {=, , , , <, >}
Expressible without sub-query
Example:
Movies shorter than 'Star Wars I (id 345)
SELECT m.id
FROM Movie m
WHERE m.length <
FU-Berlin, DBS I 2006, Hinze / Scholz
(SELECT m1.length
FROM Movie m1
WHERE m1.id = 345);
44
SQL / DML: Sub-queries
Core
Set Operator IN SQL:1999
45
SQL / DML: Sub-queries
Core
Set Operator IN SQL:1999
SELECT m.director
FROM Movie m
WHERE m.director IN
(SELECT p.actor_name
FROM Play p
FU-Berlin, DBS I 2006, Hinze / Scholz
46
SQL / DML: Sub-queries
Core
Alternative syntax: EXISTS SQL:1999
Example:
SELECT t.id, t.format
FROM Tape t
WHERE EXISTS (SELECT *
FROM Movie m
WHERE t.movie_id = m.id
AND m.title like 'Star Wars %');
SELECT m.director
FU-Berlin, DBS I 2006, Hinze / Scholz
FROM Movie m
WHERE EXISTS (SELECT *
FROM Play p
WHERE p.movie_id = m.id
AND m.director like p.actor_name);
47
SQL / DML: Query rewriting
Rewriting possible for IN, EXISTS
Examples:
SELECT t.id, t.format
FROM Tape t, Movie m
WHERE m.id = t.movie_id
AND m.title like 'Star Wars %';
SELECT m.director
FU-Berlin, DBS I 2006, Hinze / Scholz
48
SQL / DML: Sub-queries
Core
Negation NOT EXISTS, NOT IN SQL:1999
Quantification All
Sub-query true if true for all tuples
FROM Movie m
WHERE m.pricepday >= ALL
(SELECT m1.pricepday
FROM MOVIE m1);
50
SQL / DML: Quantified sub-queries
enhanced
Quantification: SOME SQL:1999
Sub-query true if true for at least one tuple
= SOME equivalent IN
SELECT m.director
FU-Berlin, DBS I 2006, Hinze / Scholz
FROM Movie m
WHERE m.director = SOME
(SELECT p.actor_name
FROM Play p
WHERE p.movie_id = m.id);
51
SQL / DML: Implementations of sub-queries
Oracle:
Sub-queries with single results
Sub-queries with [NOT] IN, [NOT] EXISTS
Quantified comparison ALL, SOME, ANY
PostgreSQL
Similar to Oracle
FU-Berlin, DBS I 2006, Hinze / Scholz
MySQL:
No sub-queries supported
52
SQL / DML: Universal quantifiers
Quantification
- Quantification (exactly one)
Describe counterexample
Combine with NOT EXISTS
53
SQL / DML: Universal quantifiers
SELECT c.mem_no
FROM Customer c
WHERE NOT EXISTS
(SELECT m.id
FROM Movie m, Rental r, Tape t
WHERE m.id = t.movie_id
AND r.tape_id = t.id
AND c.mem_no = r.mem_no
AND m.category <> 'suspense');
FU-Berlin, DBS I 2006, Hinze / Scholz
54
SQL / DML: Universal quantifiers
SELECT c.mem_no
FROM Customer c
WHERE NOT EXISTS
(SELECT m.id
FROM Movie m
WHERE NOT EXISTS
(SELECT *
FROM Rental r, Tape t
WHERE m.id = t.movie_id
AND r.tape_id = t.id
FU-Berlin, DBS I 2006, Hinze / Scholz
55
SQL / DML: Universal quantifiers
SELECT c.mem_no
FROM Customer c, Rental r, Tape t, Movie m
WHERE c.mem_no = r.mem_no
AND r.tape_id = t.id
AND t.movie_id = m.id
AND NOT EXISTS
(SELECT m1.id
FROM Rental r1, Tape t1, Movie m1
WHERE r1.tape_id = t1.id
AND t1.movie_id = m1.id
FU-Berlin, DBS I 2006, Hinze / Scholz
56
SQL / DML: Aggregate functions
Mathematical aggregate functions on data sets
Example: SUM, AVG, MIN, MAX, COUNT
Not in relational algebra
SQL>
SQL> SELECT
SELECT MIN(pricePDay)
MIN(pricePDay) as
as MIN,
MIN,
22 MAX(pricePDay)
MAX(pricePDay) as
as MAX,
MAX, AVG(pricePDay)
AVG(pricePDay)
33 FROM
FROM Movie;
Movie;
MIN
MIN MAX
MAX AVG(PRICEPDAY)
AVG(PRICEPDAY)
----------
---------- ----------
---------- --------------
--------------
1.5
1.5 2.2
2.2 1.86666667
1.86666667
FU-Berlin, DBS I 2006, Hinze / Scholz
57
SQL / DML: Aggregate functions
Comparison using aggregates: sub-queries
ID
ID TITLE
TITLE PRICEPDAY
PRICEPDAY
------
------ ---------------------------------
--------------------------------- ---------
---------
95
95 Psycho
Psycho 22
FU-Berlin, DBS I 2006, Hinze / Scholz
345
345 Star
Star Wars
Wars II 22
222
222 Psycho
Psycho 2.2
2.2
290
290 Star
Star Wars
Wars IV
IV 22
58
SQL / DML: Aggregate functions
Examples:
FROM Movie m
WHERE 2 < (SELECT count(t.id)
FROM tape t
WHERE t.movie_id = m.id)
59
SQL / DML: Aggregate functions
More examples:
60
SQL / DML: Aggregate functions
Additional qualification with DISTINCT | ALL
Example:
Movies that are available in all formats
SELECT DISTINCT t1.movie_id
FROM Tape t1
WHERE
(SELECT COUNT(DISTINCT format)
FROM Tape t2
WHERE t2.movie_id = t1.movie_id)
FU-Berlin, DBS I 2006, Hinze / Scholz
=
(SELECT COUNT(*)
FROM Format);
61
SQL / DML: Grouping
Syntax: SELECT <targetlist>
FROM <tablelist>
[WHERE <predicate>]
GROUP BY <attributelist>
Example:
Number of tapes in each format
FU-Berlin, DBS I 2006, Hinze / Scholz
62
SQL / DML: Grouping
Aggregates evaluated over groups
MOVIE_ID
MOVIE_ID COUNT(*)
COUNT(*)
----------
---------- ----------
----------
95
95 11
100
100 11
112 11
FU-Berlin, DBS I 2006, Hinze / Scholz
112
222
222 11
290
290 11
345
345 44
63
SQL / DML: Grouping
Movie
id title cat. year director price leng.
095 Psycho ... ... Hitchcock 2.00 ...
112 ET ... ... Spielberg 1.50 ...
345 Star Wars I ... ... Lucas 2.00 ...
222 Psycho ... ... Van Sant 2.20 ...
290 Star Wars IV ... ... Lucas 2.00 ...
100 Jaws ... ... Spielberg 1.50 ...
... ... ... ... ... ... ...
FROM movie;
Movie
id title cat. year director price leng.
095 Psycho ... ... Hitchcock 2.00 ...
112 ET ... ... Spielberg 1.50 ...
345 Star Wars I ... ... Lucas 2.00 ...
222 Psycho ... ... Van Sant 2.20 ...
290 Star Wars IV ... ... Lucas 2.00 ...
100 Jaws ... ... Spielberg 1.50 ...
... ... ... ... ... ... ...
Hitchcock 2.0
SELECT director, sum(price) Spielberg 3.0
FU-Berlin, DBS I 2006, Hinze / Scholz
65
SQL / DML: Grouping
ID
ID COUNT(*)
COUNT(*)
----------
---------- ----------
----------
11 11
22 11
33 22
FU-Berlin, DBS I 2006, Hinze / Scholz
44 22
55 11
11
11 11
12
12 11
66
SQL / DML: Grouping
MOVIE_ID
MOVIE_ID COUNT(*)
COUNT(*)
----------
---------- ----------
----------
95
95 11
100
100 11
112
112 11
FU-Berlin, DBS I 2006, Hinze / Scholz
222
222 22
290
290 11
345
345 33
67
SQL / DML: Grouping + Having
Qualifying predicate for groups
SQL>
SQL> SELECT
SELECT f.name,
f.name, sum(charge)
sum(charge)
22 FROM
FROM Rental
Rental r,
r, Tape
Tape t,
t, format
format ff
33 WHERE
WHERE t.id
t.id == r.tape_id
r.tape_id
44 AND
AND t.format=f.name
t.format=f.name
55 GROUP
GROUP BY
BY f.name;
f.name;
SQL>
SQL> SELECT
SELECT f.name,
f.name, sum(charge)
sum(charge)
NAME
NAME SUM(CHARGE)
SUM(CHARGE)
22 FROM
FROM Rental
Rental r,
r, Tape
Tape t,
t, format
format ff
-----
----- -----------
-----------
33 WHERE
WHERE t.id
t.id == r.tape_id
r.tape_id
Beta
Beta 00
44 AND
AND t.format=f.name
t.format=f.name
DVD
DVD 88
55 GROUP
GROUP BY
BY f.name
f.name
VHS
VHS 00
66 having
having count(f.name)>2;
FU-Berlin, DBS I 2006, Hinze / Scholz
count(f.name)>2;
NAME
NAME SUM(CHARGE)
SUM(CHARGE)
-----
----- -----------
-----------
DVD
DVD 88
VHS
VHS 00 68
SQL / DML: Grouping + Having
Movie
id title cat. year director price leng.
095 Psycho ... ... Hitchcock 2.00 ...
112 ET ... ... Spielberg 1.50 ...
345 Star Wars I ... ... Lucas 2.00 ...
222 Psycho ... ... Van Sant 2.20 ...
290 Star Wars IV ... ... Lucas 2.00 ...
100 Jaws ... ... Spielberg 1.50 ...
... ... ... ... ... ... ...
Hitchcock 2.0
SELECT director, sum(price) Spielberg 3.0
FU-Berlin, DBS I 2006, Hinze / Scholz
69
SQL / DML: Grouping + Having
Movie
id title cat. year director price leng.
095 Psycho ... ... Hitchcock 2.00 ...
112 ET ... ... Spielberg 1.50 ...
345 Star Wars I ... ... Lucas 2.00 ...
222 Psycho ... ... Van Sant 2.20 ...
290 Star Wars IV ... ... Lucas 2.00 ...
100 Jaws ... ... Spielberg 1.50 ...
... ... ... ... ... ... ...
max
Hitchcock 2.0 2.0
SELECT director, sum(price) Spielberg 3.0 1.5
FU-Berlin, DBS I 2006, Hinze / Scholz
70
SQL / DML: Grouping + Having
Movie
id title cat. year director price leng.
095 Psycho ... ... Hitchcock 2.00 ...
112 ET ... ... Spielberg 1.50 ...
345 Star Wars I ... ... Lucas 2.00 ...
222 Psycho ... ... Van Sant 2.20 ...
290 Star Wars IV ... ... Lucas 2.00 ...
100 Jaws ... ... Spielberg 1.50 ...
... ... ... ... ... ... ...
max
Hitchcock, Psycho 2.0 2.0
SELECT director,title, sum(price) Spielberg, ET 1.5 1.5
FU-Berlin, DBS I 2006, Hinze / Scholz
SQL>
SQL> SELECT
SELECT sum(charge)
sum(charge)
22 FROM
FROM Rental
Rental r,
r, Tape
Tape t,
t, format
format ff
33 WHERE
WHERE t.id
t.id == r.tape_id
r.tape_id
44 AND
AND t.format=f.name
t.format=f.name
55 having
having count(f.name)>2;
count(f.name)>2;
SUM(CHARGE)
SUM(CHARGE)
-----------
-----------
88
FU-Berlin, DBS I 2006, Hinze / Scholz
72
SQL / DML: Grouping + Having
Query evaluation order:
1.FROM-clause
2.WHERE-clause
3.GROUP BYclause
4.HAVING-clause
5.SELECT-clause
Group BY t1.movie_id);
74
SQL / DML: Nested aggregation with groups
75
SQL / DML: Output improvement
Core
Select values depending an condition SQL:1999
Complete CASE form:
CASE
WHEN <condition1> THEN <result1>
[ WHEN <condition2> THEN <result2>
[ WHEN <condition3> THEN <result3> ]]
[ ELSE <elseresult>]
END
Example:
SELECT length,
FU-Berlin, DBS I 2006, Hinze / Scholz
Example:
select f.name,
case f.name
when 'DVD' then 'DISC'
FU-Berlin, DBS I 2006, Hinze / Scholz
SYNTAX:
WITH RECURSIVE
<queryname1> AS <query1>[,
<queryname2> AS <query2>,...]
SELECT ...
FROM <queryname1>[,<queryname2>...]
WHERE...
FU-Berlin, DBS I 2006, Hinze / Scholz
78
SQL / DML: Transitive closure
enhanced
Example: All lectures required for lecture XYZ SQL:1999
create table lecture(
lnr integer primary key,
name varchar(20));
create table requires(
pre integer references lecture(lnr),
suc integer references lecture(lnr),
constraint req_pk primary key(pre, suc));
SQL>
SQL> SELECT
SELECT r.pre
r.pre
22 FROM
FROM requires
requires r,r, lecture
lecture ll
33 WHERE
WHERE l.name=
l.name= 'databases'
'databases'
44 START
START WITH
WITH r.suc
r.suc == l.lnr
l.lnr
55 CONNECT
CONNECT BY
BY PRIOR
PRIOR pre
pre == suc;
suc;
FU-Berlin, DBS I 2006, Hinze / Scholz
PRE
PRE
----------
----------
33
22
80
SQL / DML: Structuring
enhanced
Difficult structuring of complex queries SQL:1999
No naming of commands / relations for re-use
Temporary table
CREATE TABLE <tablename>
{global temporary | local temporary }
<table structure>
[ON COMMIT {PRESERVE ROWS | DELETE ROWS}]
81
SQL / DML: Temporary table
Example: Test1:
CREATE TABLE testsource(id integer);
CREATE GLOBAL TEMPORARY TABLE
test1(id integer)
ON COMMIT PRESERVE ROWS; No rows
COMMIT;
1
82
SQL / DML: Temporary table
Example: Test2:
CREATE TABLE testsource(id integer);
CREATE GLOBAL TEMPORARY TABLE
test2(id integer)
ON COMMIT DELETE ROWS; No rows
COMMIT; No rows
83
SQL / DML: View
SQL-object (virtual relation) Important concept
Important for
Tailoring database schema for different applications
Access protection, Privacy
Structuring complex queries
Relational concept for external schema
Syntax:
CREATE VIEW <viewname> AS <query>;
Example:
FU-Berlin, DBS I 2006, Hinze / Scholz
Formal:
u (V(B)) = V (cu (B) )
FU-Berlin, DBS I 2006, Hinze / Scholz
Updateable:
CREATE VIEW movies (movie, name)
AS SELECT id, title
FROM Movie
FU-Berlin, DBS I 2006, Hinze / Scholz
87
SQL / DML: View updates
Views with check option
CHECK OPTION prevent side effects on base tables
Enhanced SQL:
1999 additional complex conditions for view update
88
SQL / DML: Remarks about NULL
NULL treated as "unknown"
Predicates:
NULL AND TRUE = NULL
NULL OR TRUE = TRUE
predicate evaluates to NULL for row r r not returned
Arithmetical expression:
If NULL involved expression evaluates to NULL
Aggregates:
FU-Berlin, DBS I 2006, Hinze / Scholz
89
SQL / DML: Summary
SQL as Data manipulation language
Declarative language
Relational complete query language
Aggregate functions
GROUP BY, HAVING
View, view updates
90