basic sql

Download Basic  SQL

Post on 23-Feb-2016




0 download

Embed Size (px)


Basic SQL. Chapter 4 (6/E) Chapter 8 (5/E). Lecture Outline. SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries in SQL Set Operations in SQL. Basic SQL. Structured Query Language - PowerPoint PPT Presentation


Slide 1

Basic SQLChapter 4 (6/E)Chapter 8 (5/E)

1Lecture OutlineSQL Data Definition and Data TypesSpecifying Constraints in SQLBasic Retrieval Queries in SQLSet Operations in SQL2Basic SQLStructured Query LanguageConsidered one of the major reasons for the commercial success of relational databasesStatements for data definitions, queries, and updates Both DDL and DMLCore specification plus specialized extensionsTerminology:

3Relational ModelSQLrelationtabletuplerowattributecolumnSyntax notes:Some interfaces require each statement to end with a semicolon.SQL is not case-sensitive.

SQL Data DefinitionCREATE statementMain SQL command for data definitionSQL schema Identified by a schema nameIncludes an authorization identifier (owner) Components are descriptors for each schema element Tables, constraints, views, domains, and other constructsCREATE SCHEMA statementCREATE SCHEMA COMPANY AUTHORIZATION Jsmith;

4CREATE TABLE CommandSpecify a new relation Provide nameSpecify attributes and initial constraintsBase tables (base relations)Relation and its tuples are physically stored and managed by DBMSCan optionally specify schema:CREATE TABLE COMPANY.EMPLOYEE ...orCREATE TABLE EMPLOYEE ...Include information for each column (attribute) plus constraintsColumn nameColumn type (domain)Key, uniqueness, and null constraints5BASIC Data TypesNumeric data types Integer numbers: INT, INTEGER, SMALLINT, BIGINTFloating-point (real) numbers: REAL, DOUBLE , FLOATFixed-point numbers: DECIMAL(n,m), DEC(n,m), NUMERIC(n,m), NUM(n,m)Character-string data types Fixed length: CHAR(n), CHARACTER(n)Varying length: VARCHAR(n), CHAR VARYING(n), CHARACTER VARYING(n), LONG VARCHARLarge object data types Characters: CLOB, CHAR LARGE OBJECT , CHARACTER LARGE OBJECTBits: BLOB, BINARY LARGE OBJECTBoolean data type Values of TRUE or FALSE or NULLDATE data type Ten positionsComponents are YEAR, MONTH, and DAY in the form YYYY-MM-DD

6MORE Data TypesAdditional data typesTIMESTAMP data typeIncludes the DATE and TIME fieldsPlus a minimum of six positions for decimal fractions of secondsOptional WITH TIME ZONE qualifierINTERVAL data typeSpecifies a relative value that can be used to increment or decrement an absolute value of a date, time, or timestampColumns can be declared to be NOT NULL Columns can be declared to have a default valueAssigned to column in any tuple for which a value is not specifiedExampleCREATE TABLE EMPLOYEE (NICKNAME VARCHAR(20) DEFAULT NULL,Province CHAR(2) NOT NULL DEFAULT 'ON',);78

) ; ) ;

Domains in SQLName used in place of built-in data typeMakes it easier to change the data type used by numerous columnsImproves schema readabilityExample:CREATE DOMAIN SIN_TYPE AS CHAR(9);9Specifying Key ConstraintsPRIMARY KEY clause Specifies one or more attributes that make up the primary key of a relationDnumber INT NOT NULL PRIMARY KEY,Primary key attributes must be declared NOT NULLUNIQUE clause Specifies alternate (candidate) keysDname VARCHAR(15) UNIQUE;May or may not allow null values, depending on declarationIf no key constraints, two or more tuples may be identical in all columns.SQL deviates from pure relational model!Multiset (bag) behaviour10Referential ConstraintsFOREIGN KEY clauseFOREIGN KEY (Dept) REFERENCES DEPARTMENT (Dnum),Default operation: reject update on violationAttach referential triggered action clause in case referenced tuple is deletedOptions include SET NULL, CASCADE, and SET DEFAULTForeign key declaration must refer to a table already created

11Specifying Tuple ConstraintsSome constraints involve several columnsCHECK clause at the end of a CREATE TABLE statementApply to each tuple individuallyExampleCHECK (Dept_create_date 1990;Omitting WHERE clause implies all tuples selected.16Semantics for 1 RelationStart with the relation named in the FROM clauseConsider each tuple one after the other, eliminating those that do not satisfy the WHERE clause.Boolean condition that must be true for any retrieved tupleLogical comparison operators=, =, and For each remaining tuple, create a return tuple with columns for each expression (column name) in the SELECT clause.Use SELECT * to select all columns.17Filmtitlegenreyeardirectorminutes budget gross The Company Mendrama2010John Wells104 15,000,000 4,439,063 Lincolnbiography2012Steven Spielberg150 65,000,000 181,408,467 War Horsedrama2011Steven Spielberg146 66,000,000 79,883,359 Argodrama2012Ben Affleck120 44,500,000 135,178,251 SELECT-FROM-WHERE SemanticsWhat if there are several relations in the FROM clause?Start with cross-product of all relation(s) listed in the FROM clause.Every tuple in R1 paired up with every tuple in R2 paired up with Consider each tuple one after the other, eliminating those that do not satisfy the WHERE clause.For each remaining tuple, create a return tuple with columns for each expression (column name) in the SELECT clause.Steps 2 and 3 are just the same as before.

SELECT actor, birth, movieFROM Role, PersonWHERE actor = name and birth > 1940;18RoleactormoviepersonaBen AffleckArgoTony MendezAlan ArkinArgoLester SiegelBen AffleckThe Company MenBobby WalkerTommy Lee JonesThe Company MenGene McClaryPersonnamebirthcityBen Affleck1972BerkeleyAlan Arkin1934New YorkTommy Lee Jones1946San SabaAmbiguous Column Names Same name may be used for two (or more) columns (in different relations)Must qualify the column name with the relation name to prevent ambiguity19SELECT name, date, product, quantityFROM Customer, Sale, LineItemWHERE price > 100 AND Customer.custid = Sale.custid AND Sale.saleid = LineItem.saleid;NoteIf SELECT clause includes custid, it must specify whether to use Customer.custid or Sale.custid even though the values are guaranteed to be identical. CustomercustidnameaddressphoneSalesaleiddatecustidLineItemsaleidproductquantityprice2-Relation Select-From-Where20RoleactormoviepersonaBen AffleckArgoTony MendezTommy Lee JonesLincolnThaddeus StevensDaniel Day-LewisThe BoxerDanny FlynnDaniel Day-LewisLincolnAbraham LincolnSELECT award, actor, persona, Role.movieFROM Honours, RoleWHERE category = 'actor' AND winner = actorAND = Role.movieHonoursmovieawardcategorywinnerLincolnCritic's ChoiceactorDaniel Day-LewisArgoCritic's ChoicedirectorBen AffleckLincolnSAGsupporting actorTommy Lee JonesLincolnCritic's ChoicescreenplayTony KushnerWar HorseBMI FlimmusicJohn WilliamsHonours.movieawardcategorywinneractorRole.moviepersonaLincolnCritic's ChoiceactorDaniel Day-LewisBen AffleckArgoTony MendezLincolnCritic's ChoiceactorDaniel Day-LewisTommy Lee JonesLincolnThaddeus StevensLincolnCritic's ChoiceactorDaniel Day-LewisDaniel Day-LewisThe BoxerDanny FlynnLincolnCritic's ChoiceactorDaniel Day-LewisDaniel Day-LewisLincolnAbraham LincolnArgoCritic's ChoicedirectorBen AffleckBen AffleckArgoTony MendezArgoCritic's ChoicedirectorBen AffleckTommy Lee JonesLincolnThaddeus StevensArgoCritic's ChoicedirectorBen AffleckDaniel Day-LewisThe BoxerDanny FlynnArgoCritic's ChoicedirectorBen AffleckDaniel Day-LewisLincolnAbraham LincolnLincolnSAGsupporting actorTommy Lee JonesBen AffleckArgoTony MendezLincolnSAGsupporting actorTommy Lee JonesTommy Lee JonesLincolnThaddeus StevensLincolnSAGsupporting actorTommy Lee JonesDaniel Day-LewisThe BoxerDanny Flynn

Recall Sample Tables21



24Tables as Sets in SQLDuplicate tuples may appear in query resultsFrom duplicates in base tablesFrom projecting out distinguishing columns Keyword DISTINCT in the SELECT clause eliminates duplicates25

Set OperationsResult treated as a set (no duplicates)UNION, EXCEPT (difference), INTERSECTCorresponding multiset (bag) operations: UNION ALL, EXCEPT ALL, INTERSECT ALLArguments must be union-compatibleSame number of columnsCorresponding columns of same type26

Other OperatorsStandard arithmetic operators:Addition (+), subtraction (), multiplication (*), and division (/) [NOT] LIKE comparison operatorUsed for string pattern matchingPercent sign (%) matches zero or more charactersUnderscore (_) matches a single charactere.g., to also match Tommy Lee Jones as supporting actor:SELECT award, actor, persona, Role.movieFROM Honours, RoleWHERE category LIKE '%actor' AND winner = actorAND =;[NOT] BETWEEN comparison operatorWHERE year BETWEEN 1990 AND 2010equivalent to WHERE year >= 1990 AND YEAR