SQL As Data Manipulation Language (DML)
Total Page:16
File Type:pdf, Size:1020Kb
SQLSQL asas DataData ManipulationManipulation LanguageLanguage (DML)(DML) Insert and update data Simple SQL queries Advanced SQL queries Views SQLSQL // DML:DML: OverviewOverview Insert, update, delete data Query data Interactively (Embedded in host language) Data presentation to users Output improvements FU-Berlin, DBS I 2006, Views Hinze / Scholz / Hinze 2 SQLSQL // DML:DML: InsertInsert datadata Complete form: Predefined order of values INSERT INTO Customer VALUES (001, 'Müller', 'Tina', NULL,NULL); Incomplete form: Free order of values FU-Berlin, DBS I 2006, INSERT INTO Customer (last_name, mem_no) VALUES ('Müller', 001); Hinze / Scholz / Hinze 3 SQLSQL // DML:DML: InsertInsert datadata Inserting dates INSERT INTO movie VALUES (95, 'Psycho', 'suspense', TO_DATE('1969', 'yyyy'), 'Hitchcock', 2.00, NULL); Conversion functions String to date FU-Berlin, DBS I 2006, TO_DATE(<string>[,<format>]) ORACLE/Postgres Date to string Hinze / Scholz / Hinze TO_CHAR(<date>[,<format>]) ORACLE/Postgres 4 SQLSQL // DML:DML: InsertInsert datadata 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: FU-Berlin, DBS I 2006, SELECT … INTO OUTFILE, LOAD DATA… Postgres: INSERT INTO … Hinze / Scholz / Hinze Bulk load: Copy … Bulk load from other database: Copy … 5 SQLSQL // DML:DML: ImplementationsImplementations ofof bulkbulk loadload Oracle SQL loader control file data file SQL*Loader rejected field processing rows discarded rows record selection bad file FU-Berlin, DBS I 2006, (discard file) log file Oracle server Hinze / Scholz / Hinze 6 SQLSQL // DML:DML: ImplementationsImplementations ofof bulkbulk loadload 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 loadload data data infileinfile 'loadtest.dat' 'loadtest.dat' FU-Berlin, DBS I 2006, badfilebadfile 'loadtest.bad' 'loadtest.bad' discardfilediscardfile 'loadtest.dis' 'loadtest.dis' APPENDAPPEND INTOINTO tabletable loadtest loadtest fieldsfields terminated terminated by by " " ,, "" Hinze / Scholz / Hinze optionallyoptionally enclosed enclosed by by " " '' "" (name(name char, char, numnum integer integer external)external) 7 SQLSQL // DML:DML: ImplementationsImplementations ofof bulkbulk loadload MySQL Example: Mysql>Mysql> LOADLOAD DATADATA INFILEINFILE 'loadtest.dat''loadtest.dat' ->-> IGNOREIGNORE ->-> INTOINTO TABLETABLE loadtestloadtest ->-> FIELDSFIELDS ->-> TERMINATEDTERMINATED BYBY ",""," ->-> OPTIONALLYOPTIONALLY ENCLOSEDENCLOSED BYBY '''' ->-> (name,(name, numnum ); ); QueryQuery OK,OK, 33 rowsrows affected affected (0.01 (0.01 sec)sec) Records:Records: 33 Deleted:0Deleted:0 Skipped:Skipped: 00 Warnings:Warnings: 00 FU-Berlin, DBS I 2006, Hinze / Scholz / Hinze 8 SQLSQL // DML:DML: InsertInsert uniqueunique datadata For synthetic keys, e.g. tapeId, … Counter-variables in application not sufficient Session dependent Concurrent access problematic Counter relation in database Expensive FU-Berlin, DBS I 2006, Proprietary solutions in existing DBMS MySQL: autoincrement keyword SQL-Server: identity keyword Hinze / Scholz / Hinze PostgreSQL: serial type and sequence Oracle: sequence-object 9 SQLSQL // DML:DML: InsertInsert uniqueunique datadata -- sequencesequence Abstract sequence-object (Oracle) Creates unique integer values Syntax: CREATE SEQUENCE <seqName> [START WITH <integer>] [INCREMENT BY <integer>] [MAXVALUE <integer> | NOMINVALUE] [MINVALUE <integer> | NOMAXVALUE] [CYCLE | NOCYCLE] [CACHE <integer> | NOCACHE] FU-Berlin, DBS I 2006, [ORDER | NOORDER]; Hinze / Scholz / Hinze Example: create sequence tape_sequence; 10 SQLSQL // DML:DML: InsertInsert uniqueunique datadata -- sequencesequence Value Access <seqName>.NEXTVAL = value of last call + increment <seqName>.CURRVAL = value of last call SELECT <seqName>.CURRVAL FROM DUAL; DUAL is Oracle pseudo-table Example: FU-Berlin, DBS I 2006, INSERT INTO tape VALUES(tape_sequence.nextval, 'DVD', 95); Hinze / Scholz / Hinze 11 SQLSQL // DML:DML: DeleteDelete datadata Syntax: DELETE from <tableName> [WHERE <predicate>]; Delete all rows : DELETE from <tableName>; Example: FU-Berlin, DBS I 2006, DELETE from tape WHERE format= 'Beta'; Hinze / Scholz / Hinze 12 SQLSQL // DML:DML: UpdateUpdate datadata Syntax: UPDATE <tableName> SET <attr> = <value> {,<attr> = <value> } WHERE <predicate> Examples: UPDATE Customer SET telephone = 456789 WHERE mem_no = 200; UPDATE Rental FU-Berlin, DBS I 2006, SET until_date = SYSDATE WHERE tape_ID = 3 AND mem_no = 200 AND TO_CHAR(from_date,'yyyy-mm-dd')='2002-05-01'; Hinze / Scholz / Hinze 13 SQLSQL // DML:DML: ExampleExample databasedatabase insert into customer values (001, 'Müller', 'Tina', NULL,NULL); insert into customer values (007, 'Katz', 'Anna', NULL,NULL); insert into customer values (002, 'Maus', 'Carla', NULL,NULL); .... insert into movie values (95, 'Psycho', 'suspense', to_date('1969', 'yyyy'), 'Hitchcock', 2.00, NULL); insert into movie values (112, 'ET', 'comedy', to_date('1982', 'yyyy'), 'Spielberg', 1.50, NULL); .... insert into format values('DVD', '2.00'); insert into format values('Beta', '0.00'); insert into format values('VHS', '0.00'); FU-Berlin, DBS I 2006, create sequence tape_sequence; insert into tape values (tape_sequence.nextval, 'DVD', 95); Hinze / Scholz / Hinze insert into tape values (tape_sequence.nextval, 'DVD', 112); insert into tape values (tape_sequence.nextval, 'VHS', 222); 14 SQLSQL // DML:DML: ExampleExample databasedatabase insert into rental values (3, 1, to_date('2002-05-01','yyyy-mm-dd'), NULL); insert into rental values (4, 1, to_date('2002-05-01','yyyy-mm-dd'), NULL); insert into rental values (5, 3, to_date('2002-05-01','yyyy-mm-dd'), to_date('2002-05-02','yyyy-mm-dd')); insert into actor values ('Hitchcock', 'Hitchcock', to_date(1899-08-13','yyyy-mm-dd')); insert into actor values ('Harrison Ford', 'Harrison Ford', to_date('1942-07-13','yyyy-mm-dd')); FU-Berlin, DBS I 2006, insert into play values(290,'Harrison Ford'); insert into play values(98,'Hitchcock'); Hinze / Scholz / Hinze 15 SQLSQL // DML:DML: QueryingQuerying LanguageLanguage SQL is relational complete Additional query concepts Advanced search expressions on strings e.g., find all movies starting with “star wars” Arithmetic in expressions, e.g., number of tapes for each movie FU-Berlin, DBS I 2006, Grouping and predicates over sets e.g., total receipts of each movie within the last year Hinze / Scholz / Hinze 16 SQLSQL // DML:DML: BasicsBasics Basic query pattern: SELECT [DISTINCT] A1, A2,...,An FROM R1, R2,...Rm WHERE predicate P; A1 , A2 , ..., An attribute names, R1 , R2 , ..., Rm relation names, P Boolean predicate on attributes and constants Equivalent to relational algebra expression: FU-Berlin, DBS I 2006, Π A1, A2, ..., An ( σP ( R1 X R2 X ... X Rm )) Projection (RA) → SELECT (SQL) Hinze / Scholz / Hinze Cartesian Product (RA) → FROM (SQL) Selection (RA) → WHERE (SQL) 17 SQLSQL // DML:DML: BasicsBasics Query result is relation Query evaluation order: 1.FROM-clause 2.WHERE-clause 3.SELECT-clause SQL>SQL> SELECTSELECT last_namelast_name 22 FROMFROM Customer;Customer; No duplicate removal LAST_NAME (performance!) LAST_NAME ------------------------------------------------------------ FU-Berlin, DBS I 2006, MüllerMüller KatzKatz MausMaus HinzHinz Hinze / Scholz / Hinze KunzKunz MüllerMüller 18 SQLSQL // DML:DML: BasicsBasics Eliminating duplicates: Targetlist contains KEY attribute Targetlist constrains UNIQUE attribute Targetliste defined with DISTINCT SELECT mem_no, last_name SELECT DISTINCT last_name FROM Customer FROM Customer MEM_NOMEM_NO LAST_NAMELAST_NAME LAST_NAMELAST_NAME -------------------- ---------------- ---------------- ---------------------------------- 11 MüllerMüller HinzHinz 77 KatzKatz KatzKatz FU-Berlin, DBS I 2006, 22 MausMaus KunzKunz 1111 HinzHinz MausMaus 2323 KunzKunz MüllerMüller 111111 MüllerMüller Hinze / Scholz / Hinze 19 SQLSQL // DML:DML: BasicsBasics WHERE-clause structure: Simple Boolean predicates similar to RA and Calculus Additional simple predicates: <attribute> BETWEEN <value1> AND <value2> <attribute> IS [NOT] NULL <attribute> LIKE <string> <attribute> SIMILAR TO <string> FU-Berlin, DBS I 2006, Advanced predicated with sub-queries Set-operators (IN, NOT IN, SOME, ALL, EXISTS) Hinze / Scholz / Hinze 20 SQLSQL // DML:DML: SimpleSimple queriesqueries Example: All customers named Anna SQL>SQL> selectselect mem_no, mem_no, last_name,last_name, first_namefirst_name 22 fromfrom customer customer 33 wherewhere first_name='Anna'; first_name='Anna'; MEM_NOMEM_NO LAST_NAMELAST_NAME FIRST_NAMEFIRST_NAME -------------------- ---------------- -------------------------------------------- -------------- -------------- 77 KatzKatz AnnaAnna 2323 KunzKunz AnnaAnna Example: All movies by Lucas from 1999 or later SQL>SQL> selectselect id,id, titletitle 2 from movie FU-Berlin, DBS I 2006, 2 from movie 33 wherewhere director='Lucas'director='Lucas' 44 andand to_char(year,'yyyy')>='1999';to_char(year,'yyyy')>='1999'; IDID TITLETITLE Hinze / Scholz / Hinze -------------------- ---------------- -------------------------------------------------------------------------- 345345 StarStar WarsWars II 21 SQLSQL // DML:DML: SimpleSimple queriesqueries More examples: All formats with extra