View stunning SlideShares in full-screen with the new iOS app!Introducing SlideShare for AndroidExplore all your favorite topics in the SlideShare appGet the SlideShare app to Save for Later — even offline
View stunning SlideShares in full-screen with the new Android app!View stunning SlideShares in full-screen with the new iOS app!
Introduction to SQL1Fall 2001 Database Systems 1SQL• A simple “logical” and “declarative” language forcommunicating with a DBMS to carry out different tasks– querying data (select statements)– inserting, updating and deleting rows in a table– creating, replacing, altering, and dropping objects– controlling access to the database and its objects– guaranteeing database consistency and integrity• DDL: data definition language• DML: data manipulation language• Most DBMSs “speak” SQLFall 2001 Database Systems 2SQL• SQL developed by IBM and first implemented byRelational Software Inc. (now Oracle) in 1979• The last published standard (ANSI and ISO) calledSQL92 (or SQL2) sets four levels of compliance:entry, transitional, intermediate and full• All DBMSs should have at least entry levelcompliance• Most DBMSs support various advanced features aswell as vendor specific features• SQL3 (also called SQL99) is the next targetstandard which is still being developed
Introduction to SQL2Fall 2001 Database Systems 3SQL - DDL• A database installation is usually called adatabase instance (for example ora8 for rcs).– For a specific instance, there are multiple users• Created by CREATE USER command by the DBA• A user is considered to own his/her own schema (user =schema)• Each user has the ability to– Change his/her own passwordALTER USER suppiluliumas IDENTIFIED BY greatking;– Perform operations that he/she is allowed to! (accessrights/security)Fall 2001 Database Systems 4SQL - DDL• To create a table (relation), we use the followingcommand:• General formCREATE TABLE <Table_Name>(Attribute_1 <Type>[DEFAULT <value>][<Nullconstraint>],Attribute_2 <Type>[DEFAULT <value>][<Nullconstraint>],…Attribute_n <Type>[DEFAULT <value>][<Nullconstraint>],[<Constraints>])
Introduction to SQL3Fall 2001 Database Systems 5SQL – DDL• There is an undo for most operations: CREATE TABLE tablename,DROP TABLE tablename• Bids tables:CREATE TABLE BUYERS (BUYID INT,NAME CHAR(20) NOT NULL,EMAIL VARCHAR2(20),PRIMARY KEY (BUYID)) ;When writing commands in Sqlplus, use a “;” to end each command.Fall 2001 Database Systems 6SQL – DDL Data types• Numeric– INT, SHORTINT– REAL (FLOAT), DOUBLE PRECISION– DECIMAL(i,j)• Character-string– CHAR(n), VARCHAR(n)• Bit-string– BIT(n), BIT VARYING(n)• Date– YYYY-MM-DD• Time– HH:MM:SS• Timestamp– both DATE and TIME fields plus a minimum of six positions forfractions of seconds
Introduction to SQL4Fall 2001 Database Systems 7Attribute constraints• Not null– Specifies that an attribute cannot contain null values• Unique– Specifies that an attribute cannot contain duplicates• Primary key– Designates a set of columns as the table’s primary key– Implies UNIQUE and NOT NULL• Foreign key– Designates a set of columns as the foreign key in a referentialconstraintFall 2001 Database Systems 8SQL – DDLCREATE TABLE BIDS (BID INT,BIDDATE DATE NOT NULL,IID INT NOT NULL,BUYID INT NOT NULL,AMOUNT INT NOT NULL,PRIMARY KEY (BID),FOREIGN KEY (IID) REFERENCES ITEMS(IID),FOREIGN KEY (BUYID) REFERENCESBUYERS(BUYID)) ;
Introduction to SQL5Fall 2001 Database Systems 9SQL – DDL Insert• Insert tuples into tables:INSERT INTO OWNERSVALUES(1, ‘Smith’, ‘Smith@aol.com’) ;INSERT INTOITEMS(IID, OID, NAME, LOCATION)VALUES(1, 1, ‘Scales’, ‘Boston’) ;Fall 2001 Database Systems 10SQL - Select• The main body of an SQL select statement is:SELECT projection columnsFROM relationsWHERE selection and join conditions• SQL statements produce a “bag” of tuples, i.e. duplicatesare not removed automatically unless a “DISTINCT”statement precedes the column name!• Any relational algebra query involving only selection,projection and join operations can be translated to a singleSQL query of the above form
Introduction to SQL6Fall 2001 Database Systems 11Find the names and identifiers of all items located in “Boston”SELECT Name, IidFROM ItemsWHERE Location = ‘Boston’Find all buyersSELECT *FROM BuyersFind the identifier of all bids of $20 or higher placed on Date 9/2SELECT BidFROM BidsWHERE Amount > 20 AND Date= ‘9/2’Fall 2001 Database Systems 12[BAGS] Find the identifier of all buyers who placed a bidSELECT BuyId SELECT DISTINCT BuyIdFROM Bids FROM Bids[JOIN and ALIAS] Find the names of owners and the names of productsthat they ownSELECT O.name, I.nameFROM Owners O, Items IWHERE O.Oid = I.OidFind the name and email of owners of items located in BostonSELECT O.name, O.emailFROM Owners O, Items IWHERE O.Oid = I.Oid AND I.Location = ‘Boston’AliasesJoin conditionDo we need touse “DISTINCT”in this query?
Introduction to SQL7Fall 2001 Database Systems 13SQLExecute an SQL body of the formSELECT A1…AnFROM R1…RmWHERE Cas follows:for all combinations of tuples r1…rm from relations R1…Rm doif the tuple combination r1…rm together satisfy C theninclude the attributes A1…An from r1…rm in theresulting bag of tuplesend-forIf keyword “distinct” is used, remove duplicatesFall 2001 Database Systems 14SQL - Set Operations• The set membership conditions “IN” and “NOT IN” areused for any sets:SELECT NameFROM ItemsWHERE Location IN (‘Dallas’, ‘Boston’)• SQL statements return a set of tuples as well. We cansubstitute an SQL statement for a set as long as it iscompatible with the compared attribute!
Introduction to SQL8Fall 2001 Database Systems 15SQL - Nested Statements• Find the name of all buyers who have a bidSELECT NameFROM BuyersWHERE BuyId IN ( SELECT BuyIDFROM Bids )• Find the name of buyers who did not bid on an item locatedin “Boston”SELECT B.NameFROM Buyers BWHERE B.BuyId NOT IN ( SELECT B2.BuyIDFROM BIDS B2, Items IWHERE I.Location = ‘Boston’AND B2.buyid = I.buyid )Fall 2001 Database Systems 16SQL - Nested StatementsSELECT A1…AnFROM R1…RmWHERE C op (SELECT A’1…A’m FROM R’1…R’k WHERE C’)is executed as follows:for all combinations of tuples r1…rm from relations R1…Rm doexecute subquery Temp = ( SELECT A’1…A’m FROM R’1…R’kWHERE C’) using values of r1…rmif C op Temp is true for the tuple combination r1…rm theninclude the attributes A1…An from r1…rm in the resulting bag of tuplesend-for
Introduction to SQL9Fall 2001 Database Systems 17Subselect comparisons• Find the buyers who placed the highest bidsSELECT B.buyidFROM Bids BWHERE B.Amount >=ALL (SELECT B2.AmountFROM Bids B2)Fall 2001 Database Systems 18Subselect comparisons• Find all items with a bidSELECT I.NameFROM Items IWHERE I.Iid =ANY (SELECT B.Iid FROM BidsB)• Subselect comparisonsΘANYΘALLwhere Θ is one of <, =, >, <=, >=, <>
Introduction to SQL10Fall 2001 Database Systems 19Union• Find the name and email of all owners and buyers(SELECT O.Name, O.EmailFROM Owners O )UNION(SELECT B.Name, B.EmailFROM Buyers B)• Like in the algebra, a union can only be performed amongcompatible sub-expressions.• Union removes duplicates!• To retain duplicates use “UNION ALL”!Fall 2001 Database Systems 20More on WHERE• Find all buyers whose name starts with “G”SELECT B.*FROM Buyers BWHERE B.Name LIKE ‘G%’• Find all bids between $20 and $40SELECT B.*FROM Bids BWHERE B.Amount BETWEEN 20 AND 40• Find all buyers who name starts with a letterbetween A and GSELECT B.*FROM Buyers BWHERE B.Name BETWEEN ‘A%’ AND ‘G%’Regular expression
Introduction to SQL11Fall 2001 Database Systems 21SQL – selection conditions• An expression (produces a value)– Any attribute name– Any constant– Any function over these– Examples: ITEMS.IID 4 ITEMS.IID+10BIDS.AMOUNT*5/20GREATER(BIDS.AMOUNT, 20)‘Sibel’ || ‘Adali’– Regular expressions:• An underscore (_) in the pattern matches exactly one character (asopposed to one byte in a multibyte character set) in the value.• A percent sign (%) in the pattern can match zero or more characters(as opposed to bytes in a multibyte character set) in the value. Notethat the pattern % cannot match a null.Fall 2001 Database Systems 22SQL - conditions• Unary conditions– Expression IS NULL (5 IS NULL) ?– EXISTS SQL-Expression• Binary conditions– Expression > Expression (10 < Bids.amount)?– Expression LIKE Expression– Expression (NOT) IN Expression (5 IN (5,10,25))?• Combination of these conditions with AND, OR,NOT
Introduction to SQL12Fall 2001 Database Systems 23SQL – functions• Functions can be used in both SELECT andWHERE statements. Examples:– Math functions: ABS, FLOOR, LOG, MOD– String functions: Concatenation (||), UPPER, LOWER,SUBSTR– Date functions: ADD_MONTHS, SYSDATE,MONTHS_BETWEEN– Conversion functions: TO_DATE, TO_CHAR– Example:• TO_CHAR(SYSDATE, ‘MM/DD/YYYY HH:MI:SS’)Fall 2001 Database Systems 24Conditions and Null• If a column has a null value, then this columncannot make a condition in the WHERE clauseevaluate to true or false.• A selection condition A and B evaluates to true ifand only if both A and B evaluate to true.• A selection condition A or B evaluates to true if andonly if either one of A or B evaluate to true.• A selection condition not (A) evaluates to true if andonly if A evaluates to false.