<<

Standard : Current standard

Logical Schema Design: 1999: SQL:1999 standard (ANSI SQL-3) Schema Definition with SQL (DDL) ƒ about 2200 pages as full standard

Various parts (not finished): ƒ Framework (SQL/Framework), introduction ƒ Foundation (SQL/Foundation), core SQL ƒ Call-Level Interface (SQL/CLI), ODBC 3 ƒ Persistent Stored Modules (SQL/PSM), stored procedures SQL history and standards ƒ Host Language Bindings (SQL/ Bindings), embedded SQL SQL type system ƒ Temporal data (SQL/Temporal) FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, Specifying constraints with SQL ƒ Management of external data (SQL/MED) ƒ Object Language Bindings (SQL/OLB), embedded SQL- Java ƒ Multimedia (SQL/MM), full-text and spatial data ƒ SQL and XML 4

Standard Query Language: Introduction Standard Query Language: Standards

 SQL-92 compliance levels: No pure relations in DBMS but tables (1) Entry SQL: basically SQL-89, essential ƒ Duplicate data not deleted (2) Intermediate SQL, ƒ Tuples – rows, Attributes – columns (3) Full SQL ƒ No implementation of SQL-92 on level 2 or3 Standard Query Language (SQL) Core ƒ Declarative language for DB  SQL:1999 levels: SQL:1999 ƒ Available in all relational DBMS ƒ Core SQL: essential for standard compliance enhanced ƒ Additional Features, e.g. multimedia SQL:1999

FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, Support of two interfaces: / Scholz Hinze 2006, DBS I FU-Berlin, ƒ Interactive Interface: User friendly Interface (UFI)  New standards replace old ones ƒ Application-program Interface: “embedded SQL”  In DBMS implementations much added / left out

2 5

Standard Query Language: History Standard Query Language: Course Information

1974 Prototype “System R” (IBM, San Jose)  Within the course: First relational DBMS ƒ Basic concepts of SQL:1999 based on Codd’s ƒ Oracle10i (commercial) Structured English Query Language (SEQUEL) Core SQL:1999 compliant + additional features 1975 SEQUEL renamed SQL (pronounced “Sequel” in US) ƒ PostgreSQL (open source) Core SQL:1999 compliant 1986 First standardization attempt based on system R ƒ MySQL (open source) traditionally not SQL compliant 1989 SQL standard (no subqueries, foreign keys,…) ANSI SQL-1 , SQL-89 FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, about 120 pages / Scholz Hinze 2006, DBS I FU-Berlin,

1992 SQL2 standard  Self study of further SQL concepts ANSI SQL-2, SQL-92 about 600 pages

3 6

1 Standard Query Language: Components SQL / DDL: Namespaces

 (DDL) Confusing terminology implemented ƒ Definition and change of data structures on all three levels: Namespaces, relations with attributes, domains, data types, integrity constraints, triggers, Oracle functions on the database,views, placement of data, space ƒ Database = set of physical storage areas ("tablespaces") needed, access structures,… ƒ Schema name = dbUsername ƒ Object names prefixed with Data manipulation language (DML) ƒ Create, change, data PostgreSQL ƒ Interactive query formulation ƒ Database = schema

FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, ƒ Embedding of SQL commands in host language / Scholz Hinze 2006, DBS I FU-Berlin, ƒ Schema name = database name ƒ Specification of begin, abort, and end of transaction MySQL Data Administration language ƒ Database = directory in File system data reside ƒ Access rights, authorization ƒ Schema not defined in MySQL 7 10

SQL / DDL: SQL Objects SQL / DDL: Predefined data types

Examples: Catalog, schema, , trigger,… Descriptor = Object identificator (e.g., name) Basic data types: Object hierarchy: ƒ Numbers ƒ catalog Characters, strings ƒ Date and time schema ƒ Binary objects

table Type systems of different DBS very different

FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, / Scholz Hinze 2006, DBS I FU-Berlin, Use standard compatible types if possible Catalog: ƒ Named group of schemas ƒ Created implicitly

8 11

SQL / DDL: Schema SQL / DDL: Predefined data types Core  Numeric data types Named group of SQL-objects by particular user SQL:1999 ƒ NUMERIC(p,s) e.g. 300.00 ƒ DECIMAL(p,s) Creates namespace ƒ INTEGER (: INT) e.g. 32767 ƒ Unambiguous object names ƒ SMALLINT small integers ƒ FLOAT(p,s) e.g. -1E+03 ..

. ƒ REAL (for short floats) .. ƒ DOUBLE (for long floats)

ƒ Not supported by all systems  Examples: ƒ Always supported:

. ƒ Oracle: NUMBER(precision, scale) ƒ PostgreSQL: SMALLINT, INTEGER, BIGINT, REAL,

FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, / Scholz Hinze 2006, DBS I FU-Berlin, NUMERIC(precision,scale), DECIMAL(precision, Syntax: CREATE SCHEMA ; scale), MONEY, SERIAL (=autoincrement!) ƒ MySQL: TINYINT[(M)], SMALLINT[(M)], MEDIUMINT[(M)], INT[(M)], BIGINT[(M)], FLOAT(precision), FLOAT[(M,D)], DOUBLE[(M,D)], DOUBLE PRECISION[(M,D)], REAL[(M,D)], DECIMAL[(M[,D])], NUMERIC[(M[,D])] 9 12

2 SQL / DDL: Predefined data types SQL / DDL: Domain definition, Type definition Core Core Some string data types SQL:1999 User-created domains SQL:1999 ƒ CHARACTER(n) (fixed length) ƒ Named sets of values ƒ CHARACTER (variable lenght) ƒ Helps avoiding semantically meaningless operations, e.g., comparing money with length attributes ƒ CHARACTER VARYING(n) (alias: VARCHAR(n)) Syntax: ƒ CLOB (Character Large Object, e.g., for large text), CREATE DOMAIN [AS] ; ƒ NCLOB (National CLOB) CREATE TYPE as FINAL; Example: ƒ CREATE DOMAIN Money AS DECIMAL(10,2); Examples: ƒ CREATE TYPE Euro AS DECIMAL(8,2) FINAL; ƒ Oracle: VARCHAR2(size), CHAR(size), CLOB, RAW, FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, / Scholz Hinze 2006, DBS I FU-Berlin, LONG RAW ƒ Oracle: ƒ PostgreSQL: CHARACTER(size), CHAR(size), hDomain - not supp., Type – implemented differently VARYING(size), VARCHAR(size), TEXT ƒ PostgreSQL: ƒ MySQL: CHAR(M), VARCHAR(M), TINYTEXT, TEXT, hDomain – supp.,Type – implemented differently MEDIUMTEXT, LONGTEXT ƒ MySQL: 13 hDomain - not supp., Type – not supp. 16

SQL / DDL: Predefined data types SQL / DDL: Table definition Core Date data types SQL:1999 Syntax: ƒ DATE e.g. DATE '1993-01-02' CREATE TABLE ( ƒ TIME e.g. TIME '13:14:15' [] ƒ TIMESTAMP e.g. TIMESTAMP '1993-01-02 [, []] 13:14:15.000001' {, }); ƒ INTERVAL FirstUnitofTime [to LastUnitofTime] e.g. INTERVAL '01-01' YEAR TO MONTH Example: Examples: ƒ Oracle: DATE, INTERVAL DAY TO SECOND, INTERVAL CREATE TABLE Troll( YEAR TO MONTH, TIMESTAMP, TIMESTAMP WITH TIME Name CHAR(10) primary key, FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, ZONE, TIMESTAMP WITH LOCAL TIME ZONE / Scholz Hinze 2006, DBS I FU-Berlin, Height DECIMAL (3,2)); ƒ PostgreSQL: DATE, TIME, TIME WITH TIMEZONE, TIMESTAMP, INTERVAL ƒ MySQL: DATE, DATETIME, TIMESTAMP[(M)], TIME, YEAR[(2|4)] SQL is case-insensitive for restricted words

14 17

SQL / DDL: Predefined data types SQL / DDL: Integrity constraints

Core Important technique Binary data types SQL:1999 Syntax: ƒ BIT[(n)] e.g. B'01000100' [CONSTRAINT []] ƒ BLOB[(n)] e.g. X'49FE' (Binary Large Objects, e.g., for multimedia) Column constraints ƒ Example: “must not be NULL”, “larger than 1.50” Examples: ƒ Specified as part of column definition ƒ Oracle: BLOB, BFILE, RAW, LONG RAW, ROWID  ƒ PostgreSQL: TEXT, BYTEA, or in large object Cardinalities ƒ Column constraints on keys and foreign keys ƒ MySQL: TINYBLOB, BLOB, MEDIUMBLOB, LONGBLOB Complex “semantic” constraints ("business rules") FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, / Scholz Hinze 2006, DBS I FU-Berlin, ƒ Example: "The percentage of movies not older than one year must be 25% or more“ Additionally: ƒ More than one involved, specify after column definitions ƒ BOOLEAN (true, false or unknown) (table constraint)

15 18

3 SQL / DDL: Integrity constraints SQL / DDL: Integrity constraints

PRIMARY KEY ƒ Only once per table ƒ Column constraint: ƒ Not necessary, but omission is very bad style CREATE TABLE BankAccount( ƒ Column constraint (single attribute) or table constraint accountno NUMBER(10) primary key, ƒ Examples: amount DECIMAL(9,2) CHECK (amount > 0), CREATE TABLE Troll( credit DECIMAL(7,2)); Name CHAR(10) primary key, Height DECIMAL (3,2)); ƒ Multicolumn constraint: CREATE TABLE BankAccount( CREATE TABLE Troll( accountno NUMBER(10) primary key, FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, Name CHAR(10) primary key, / Scholz Hinze 2006, DBS I FU-Berlin, amount DECIMAL(9,2), Height DECIMAL (3,2), credit DECIMAL(7,2), Weight INTEGER, CONSTRAINT account CHECK (amount+credit>0)); CONSTRAINT pk primary key(Name, Height));

19 22

SQL / DDL: Integrity constraints SQL / DDL:

NOT NULL  Important concept ƒ Value must not be NULL Consider R with key k and relation S ƒ Column constraint fk ⊂ S is foreign key if for all tuples s∈S holds: ƒ Example: 1. s.fk contains only NULL values or only values ≠ NULL CREATE TABLE Format ( 2. If s.fk contains no NULL values ∃ tuple r∈R: s.fk=r.k name CHAR(10) primary key, charge DECIMAL(3,2) not NULL);  Referential integrity: Foreign key constraint (above) holds UNIQUE ƒ Column contains only unique values FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, / Scholz Hinze 2006, DBS I FU-Berlin,  Referential Integrity in SQL ƒ Requires NOT NULL ƒ Candidate keys with UNIQUE ƒ Should be used for candidate keys ƒ Primary keys with PRIMARY KEY ƒ Column constraint, (table constraint) ƒ Foreign keys with REFERENCES

20 23

SQL / DDL: Integrity constraints SQL / DDL: Integrity constraints

CHECK clause: FOREIGN KEY Important technique ƒ Defines predicates that must hold for each row ƒ References keys in other tables ƒ Ensures references to existing key values only Examples: CREATE TABLE Tape( id INTEGER PRIMARY KEY, ƒ Enumeration: format CHAR(5) NOT NULL, CHECK( VALUES IN ('comedy','suspense', movie_id INTEGER NOT NULL, 'drama','action',‘SciFi')) CONSTRAINT tapeNotEmpty FOREIGN KEY (movie_id) REFERENCES Movie(id),

FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, ƒ Interval restriction: / Scholz Hinze 2006, DBS I FU-Berlin, CONSTRAINT formatCheck FOREIGN KEY (format) REFERENCES Format(name) CHECK(Charge >= 0 AND Charge < 10) );

21 24

4 SQL / DDL: Integrity constraints SQL / DDL: Integrity constraints

Important technique Cardinality constraints id (1,1) (1,*) FOREIGN KEY prevents execution of SQL id statements which violate Referential Integrity Tape hold Movie Update and delete may cause violation ƒ NOT NULL ensures min = 1 Define actions: ƒ On delete cascade: delete all referencing tuples CREATE TABLE Tape( ƒ On delete set NULL id INTEGER PRIMARY KEY, ƒ On delete set default format CHAR(10) NOT NULL,

FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, ƒ / Scholz Hinze 2006, DBS I FU-Berlin, On cascade: update key in referencing table movie_id INTEGER NOT NULL, ƒ On update set NULL CONSTRAINT tapeNotEmpty ƒ On update set default FOREIGN KEY (movie_id) REFERENCES Movie(id), CONSTRAINT formatCheck FOREIGN KEY (format) REFERENCES Format(name)); 25 28

SQL / DDL: Integrity constraints SQL / DDL: Integrity constraints

Example: Cardinality constraints id CREATE TABLE Tape( (1,1) (0,1) id id INTEGER PRIMARY KEY, Country is_mayor Person format CHAR(5) NOT NULL, movie_id INTEGER NOT NULL, ƒ NOT NULL ensures min = 1 CONSTRAINT tapeNotEmpty FOREIGN KEY (movie_id) REFERENCES Movie(id) ƒ UNIQUE ensures max= 1 ON DELETE CASCADE, CREATE TABLE Country( CONSTRAINT formatCheck id INTEGER PRIMARY KEY, FOREIGN KEY (format) REFERENCES Format(name) mayor INTEGER UNIQUE NOT NULL, FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, ON DELETE SET NULL); / Scholz Hinze 2006, DBS I FU-Berlin, CONSTRAINT mayorFK Tape Movie FOREIGN KEY (mayor) REFERENCES Person(id)); id format movie_id id title 0001 DVD 095 095 Psycho 0004 DVD 345 345 Star Wars I 0005 VHS 345 ...... 0009 VHS 345 ...... 26 29

SQL / DDL: Integrity constraints SQL / DDL: Mandatory relationships

Example: Example: born_in (1,*) (1,1) Tape Movie Person id format movie_id id title Country 0001 DVD 095 095 Psycho 0004 DVD 345 345 Star Wars I (1,1) (0,1) 0005 VHS 345 ...... is_mayor 0009 VHS 345 ...... How to define “circular” constraints? Delete Movie ƒ Specify constraints after table definition Where id = 345; ALTER TABLE Person Tape Movie ADD (CONSTRAINT birthPlaceReference FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, / Scholz Hinze 2006, DBS I FU-Berlin, id format movie_id id title FOREIGN KEY (birthplace) 0001 DVD 095 095 Psycho REFERENCES country(id)); ...... ALTER TABLE Person MODIFY COLUMN( birthplace not );

27 30

5 SQL / DDL: Mandatory relationships SQL / DDL: Mandatory relationships The Chicken-Egg problem Trigger CREATE TABLE chicken(cID INT PRIMARY KEY, eID INT); CREATE TABLE egg(eID INT PRIMARY KEY, ƒ Specify trigger on table Movie: cID INT); CREATE TRIGGER alwaysTape -- Example by J. Widom et al. AFTER INSERT ON Movie ALTER TABLE chicken REFERENCING NEW ROW AS m ADD CONSTRAINT chickenREFegg FOR EACH ROW WHEN FOREIGN KEY (eID) REFERENCES egg(eID); NOT EXISTS ( SELECT * ALTER TABLE egg From Tape ADD CONSTRAINT eggREFchicken WHERE movie_id=m.id) FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, FOREIGN KEY (cID) REFERENCES chicken(cID) ; / Scholz Hinze 2006, DBS I FU-Berlin, ;

ƒ Very flexible and expressive What happens if an egg / chicken is inserted? ƒ Later more…

31 34

SQL / DDL: Mandatory relationships SQL / DDL: Alter table definitions

Insertion violates foreign key constraint Syntax: INSERT INTO chicken VALUES(1, 2); ALTER TABLE; ORA-02291: integrity constraint (chickenREFegg.SYS_C0067174) violated - parent key not found Add an attribute INSERT INTO egg VALUES(2, 1); ALTER TABLE Tape ORA-02291: integrity constraint ADD COLUMN (AquiredBy char(20)); (eggREFchicken.SYS_C0067174) violated - parent key not found Defer constraint checking Change an attribute ƒ Attribute names cannot be changed ALTER TABLE chicken FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, ADD CONSTRAINT chickenREFegg / Scholz Hinze 2006, DBS I FU-Berlin, ALTER TABLE Tape FOREIGN KEY (eID) REFERENCES egg(eID) MODIFY (AquiredBy char(30)); INITIALLY DEFERRED DEFERRABLE; Add constraints,…

32 35

SQL / DDL: Mandatory relationships SQL / DDL: More statements Deferred constraints checked at the end of a transaction. Delete table Transaction: unit of work consisting of one or more ƒ Delete table only if not referenced operations on the DB DROP TABLE restrict closes a transaction ƒ Delete table and reference DROP TABLE cascade; INSERT INTO chicken VALUES(1, 2); -- constraint not checked here Oracle: DROP TABLE INSERT INTO egg VALUES(2, 1); cascade constraints; COMMIT; -- but here

FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, Variants / Scholz Hinze 2006, DBS I FU-Berlin, INITIALLY DEFERRED DEFERRABLE INITIALLY IMMEDIATE DEFERRABLE Attributes can have default values SET CONSTRAINT [DEFERED|IMMEDIATE] DEFAULT

allow checking at arbitrary times 33 36

6 SQL / DDL: Example SQL / DDL: Example

CREATE TABLE Customer ( CREATE TABLE Movie ( mem_no INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY, last_name VARCHAR (30) NOT NULL, title VARCHAR(60) NOT NULL, first_name VARCHAR(20), category CHAR(10), address VARCHAR (60), year DATE, telephone VARCHAR (15)); director VARCHAR(30), pricePDay DECIMAL(4,2), CREATE TABLE Rental( tape_id INTEGER, length INTEGER, mem_no INTEGER, CONSTRAINT plausible_year from_date DATE NOT NULL, CHECK (year > TO_DATE('01.01.1900','DD.MM.YYYY')), until_date DATE, FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, CONSTRAINT allowedPrice / Scholz Hinze 2006, DBS I FU-Berlin, PRIMARY KEY (tape_id, mem_no, from_date), CHECK ( (pricePDay >= 0) AND (pricePDay < 100.0)) CONSTRAINT fk_Tape ); FOREIGN KEY (tape_id) REFERENCES Tape(id), CONSTRAINT fk_Customer FOREIGN KEY (mem_no)

37 REFERENCES Customer(mem_no)); 40

SQL / DDL: Example SQL / DDL: Implementations

CREATE TABLE Format( Oracle Name CHAR(5) primary key, ƒ PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN KEY, Charge DECIMAL (3,2) REFERENCES, CHECK supported ); ƒ Unique artificial key values: use sequence-object

CREATE TABLE Tape( PostgresSQL id INTEGER PRIMARY KEY, ƒ PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN KEY, format CHAR(5) NOT NULL, REFERENCES, CHECK supported movie_id INTEGER NOT NULL, ƒ Unique artificial key values: serial data type and sequences CONSTRAINT tapeNotEmpty FOREIGN KEY (movie_id) REFERENCES Movie(id) MySQL: FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, ON DELETE CASCADE, / Scholz Hinze 2006, DBS I FU-Berlin, ƒ PRIMARY KEY, NOT NULL, UNIQUE supported CONSTRAINT formatCheck ƒ FOREIGN KEY, REFERENCES, CHECK accepted (for FOREIGN KEY (format) REFERENCES Format(name) compatibility) but not supported ƒ Unique artificial key values: ON DELETE SET NULL AUTO_INCREMENT ƒ Many changes in new versions (!) ); 38 41

SQL / DDL: Example SQL / DDL: Metadata management

CREATE TABLE Actor ( Metadata: SQL object definitions stage_name VARCHAR(30)NOT NULL UNIQUE, real_name VARCHAR(30), Stored in system data structures ("the catalogue“) birthday DATE Mostly accessed as tables ); ƒ All user-tables: SELECT table_name FROM user_tables; CREATE TABLE Play ( movie_id INTEGER, ƒ All constraints: actor_name VARCHAR(30), CONSTRAINT pkStarr SELECT constraint_name,search_condition PRIMARY KEY (movie_id, actor_name), FROM user_constraints CONSTRAINT foreignKeyMovieID WHERE table_name = 'MOVIE'; FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, / Scholz Hinze 2006, DBS I FU-Berlin, FOREIGN KEY (movie_id) CONSTRAINT_NAME C SEARCH_CONDITION REFERENCES Movie (id), ------CONSTRAINT foreignKeyStagename SYS_C002723 C "TITLE" IS NOT NULL FOREIGN KEY (actor_name) PLAUSIBLE_YEAR C year > TO_DATE('01.01.1900','DD.MM.YYYY') ALLOWEDPRICE C (pricePDay >= 0) AND (pricePDay < 100.0) REFERENCES Actor(stage_name) SYS_C002726 P ); 39 42

7 SQL / DDL: Summary

Standard Query Language (SQL) ƒ Data definition language (DDL) ƒ Data manipulation language (DML) ƒ In almost all current DBMS ƒ All SQL implementations differ from standard

Important terms and concepts: ƒ Data types ƒ Create, change, delete tables FU-Berlin, DBS I 2006, Hinze / Scholz Hinze 2006, DBS I FU-Berlin, ƒ Referential integrity ƒ Integrity constraints

43

8