Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Introduction to Structured Query Language (SQL).

Similar presentations


Presentation on theme: "1 Introduction to Structured Query Language (SQL)."— Presentation transcript:

1 1 Introduction to Structured Query Language (SQL)

2 2 RA Exercise uSALESPERSON(SSN, Name, Start_Year, Dept_No) uTRIP(SSN, From_City, Departure_Date, Return_Date, Trip_ID) uEXPENSE(Trip_ID, Account#, Amount) wGive the details (all attributes of TRIP relation) for trips that exceeded $2000 in expense wPrint the SSN of salesman who took trips to Honolulu wSearch the Name & Dept_No of salesman who took trips from ‘Jakarta’ and expensed no more than $1000

3 3 Join Example Sells(barbeerprice )Bars(baraddr ) Joe’sBud2.50Joe’sMaple St. Joe’sMiller2.75Sue’sRiver Rd. Sue’sBud2.50 Sue’sCoors3.00 BarInfo := Sells JOIN Bars BarInfo(barbeerpriceaddr ) Joe’sBud2.50Maple St. Joe’sMilller2.75Maple St. Sue’sBud2.50River Rd. Sue’sCoors3.00River Rd.

4 4 Database

5 5 Why SQL? uSQL is a very-high-level language, in which the programmer is able to avoid specifying a lot of data-manipulation details that would be necessary in languages like C++. uWhat makes SQL viable is that its queries are “optimized” quite well, yielding efficient query executions.

6 6 SQL Components uDDL – Data definition language wDefining the relational schema – relations, attributes, domains (the meta-data) wDropping/altering the relational schema u DML – Data manipulation language wDefining the queries against the schema wInserting, deleting and modifying data uOthers wIntegrity (allowable values/referential) wCatalog and dictionary facilities wTransaction control (long-duration and batch) wAuthorization (who can do what when)

7 7 Our Running Example uAll our SQL queries will be based on the following database schema. wUnderline indicates key attributes. SCHEMA BeerWorld Beers(name, manf) Bars(name, addr, license) Drinkers(name, addr, phone) Likes(drinker, beer) Sells(bar, beer, price) Frequents(drinker, bar)

8 8 Data Definition Language - DDL uA Pre-Defined set of Primitive Types wNumeric wCharacter-string wBit-string wAdditional Types uDefining Domains uDefining Schema uDefining Tables uDefining Views uNote: Each DBMS May have their Own DBMS Specific Data Types

9 9 Primitive Types uNumeric wINTEGER (or INT), SMALLINT wREAL, DOUBLE PRECISION wFLOAT(N) Floating Point with at Least N Digits wDECIMAL(P,D) (DEC(P,D) or NUMERIC(P,D)) have P Total Digits with D to Right of Decimal uNote that INTs and REALs are Machine Dependent (Based on Hardware/OS Platform)

10 10 Primitive Types uCharacter-String wCHAR(N) or CHARACTER(N) - Fixed wVARCHAR(N), CHAR VARYING(N), or CHARACTER VARYING(N) Variable with at Most N Characters uBit-Strings wBIT(N) Fixed wVARBIT(N) or BIT VARYING(N) Variable with at Most N Bits

11 11 Primitive Types uThese Specialized Primitive Types are Used to: wSimplify Modeling Process wInclude “Popular” Types wReduce Composite Attributes/Programming uDATE : YYYY-MM-DD uTIME: HH-MM-SS

12 12 What are Domains? uDomains are Similar in Concepts to Programming Language Type Definitions uA Domain can be Defined as Follows: CREATE DOMAIN DrinkerName CHAR(25) DEFAULT ‘Joe’; CREATE DOMAIN BeerName CHAR(20); uAdvantage of Using Domains wChanging a Domain Definition in One Place Changes it Consistently Everywhere it is Used wDefault Values Can Be Defined for Domains wConstraints Can Be Defined for Domains

13 13 Dropping a Domain uA Domain is Dropped As Follows: DROP DOMAIN DrinkerName RESTRICT; DROP DOMAIN BeerName CASCADE; uRestrict: wDrop Operation Fails If the Domain is Used in Column Definitions uCascade: wDrop Operation Causes Columns to be Defined Directly on the Underlying Data Type

14 14 What is a SQL Schema? uA Schema in SQL is the Major Meta-Data Construct uSupports the Definition of: wRelation - Table with Name wAttributes - Columns and their Types wIdentification - Primary Key wConstraints - Referential Integrity (FK) uTwo Part Definition wCREATE Schema - Named Database or Conceptually Related Tables wCREATE Table - Individual Tables of the Schema

15 15 Create/Drop Schema uFor schema BeerWorld SQL: CREATE SCHEMA BeerWorld Authorization Indra; uDrop schema BeerWorld SQL: DROP SCHEMA BeerWorld RESTRICT; DROP SCHEMA BeerWorld CASCADE; wRestrict: Drop Operation Fails If Schema is Not Empty wCascade: Drop Operation Removes Everything in the Schema

16 16 Create Table u Create table Drinkers Drinkers(name, addr, phone) CREATE TABLE Drinkers( nameVARCHAR(25), addrVARCHAR(40), phoneCHAR(10), PRIMARY KEY(name) );

17 17 Create Table uDefault value: gives the default value for a column/attribute Example: name VARCHAR(25) DEFAULT ‘Joe’ uConstraint: gives the constraint to the column/attribute. It can be used for: wSpecifying the primary key/foreign key wSpecifying column that can’t have the null value wPreserving the integrity of the database Deleting the record Modifying the value of primary key SET DEFAULT, SET NULL, CASCADE

18 18 Create Table uCreate table Drinkers(name, addr, phone) CREATE TABLE Drinkers( name VARCHAR(25) NOT NULL, …, CONSTRAINT pkDrinkers PRIMARY KEY(name) ); uCreate table Sells(bar, beer, price) CREATE TABLE Sells( barVARCHAR(25) NOT NULL, beer VARCHAR(25) NOT NULL, priceDECIMAL(10,2) NOT NULL, CONSTRAINT pkBar FOREIGN KEY(bar) REFERENCES Bars(name) ON UPDATE CASCADE, CONSTRAINT pkBeer FOREIGN KEY(beer) REFERENCES Beers(name) ON UPDATE CASCADE ); Constraint name

19 19 Drop Tables uCommand: DROP TABLE Drinkers RESTRICT; DROP TABLE Sells CASCADE; uRestrict: wDrop Operation fails if the Table is Referenced by View and/or Constraint Definitions uCascade: wDrop Operation Removes Referencing View and Constraint Definitions

20 20 Alter Table uChange the table structures: wAdding or dropping column wChanging column definition wAdding or dropping table constraint uAdding column “job” in table “Drinkers”: ALTER TABLE Drinkers ADD job VARCHAR(20); uDropping column “job” in table “Drinkers”: ALTER TABLE Drinkers DROP job CASCADE; ALTER TABLE Drinkers DROP job RESTRICT; wRestrict: Drop Operation Fails if Column is Referenced wCascade: Drop Operation Removes Referencing View and Constraint Definitions

21 21 Basic Query In SQL

22 22 Basic Query in SQL uThe principal form of a query is: SELECT desired attributes FROM one or more tables WHERE condition about tuples of the tables GROUP BY attribute list HAVING condition ORDER BY attribute list Basic Query

23 23 Example uUsing Beers(name, manf), what beers are made by Anheuser-Busch? SELECT name FROM Beers WHERE manf = ‘Anheuser-Busch’;

24 24 Result of Query name ‘Bud’ ‘Bud Lite’ ‘Michelob’ The answer is a relation with a single attribute, name, and tuples with the name of each beer by Anheuser-Busch, such as Bud.

25 25 Meaning of Single-Relation Query uBegin with the relation in the FROM clause. uApply the selection indicated by the WHERE clause. uApply the extended projection indicated by the SELECT clause.

26 26 Operational Semantics uTo implement this algorithm think of a tuple variable ranging over each tuple of the relation mentioned in FROM. uCheck if the “current” tuple satisfies the WHERE clause. uIf so, compute the attributes or expressions of the SELECT clause using the components of this tuple.

27 27 * In SELECT clauses uWhen there is one relation in the FROM clause, * in the SELECT clause stands for “all attributes of this relation.” uExample using Beers(name, manf): SELECT * FROM Beers WHERE manf = ‘ Anheuser-Busch ’;

28 28 Result of Query: namemanf ‘Bud’‘Anheuser-Busch’ ‘Bud Lite’‘Anheuser-Busch’ ‘Michelob’‘Anheuser-Busch’ Now, the result has each of the attributes of Beers.

29 29 Renaming Attributes uIf you want the result to have different attribute names, use “AS ” to rename an attribute. uExample based on Beers(name, manf): SELECT name AS beer, manf FROM Beers WHERE manf = ‘Anheuser-Busch’

30 30 Result of Query: beermanf ‘Bud’‘Anheuser-Busch’ ‘Bud Lite’‘Anheuser-Busch’ ‘Michelob’‘Anheuser-Busch’

31 31 Expressions in SELECT Clauses uAny expression that makes sense can appear as an element of a SELECT clause. uExample: from Sells(bar, beer, price): SELECT bar, beer, price*8000 AS prcInRupiah FROM Sells;

32 32 Result of Query barbeerprcInRupiah Joe’sBud40000 Sue’sMiller56000 … … …

33 33 Another Example: Constant Expressions uFrom Likes(drinker, beer): SELECT drinker, ‘likes Bud’ AS whoLikesBud FROM Likes WHERE beer = ‘Bud’;

34 34 Result of Query drinkerwhoLikesBud ‘Sally’‘likes Bud’ ‘Fred’‘likes Bud’ …

35 35 Complex Conditions in WHERE Clause uFrom Sells(bar, beer, price), find the price Joe’s Bar charges for Bud: SELECT price FROM Sells WHERE bar = ‘Joe’’s Bar’ AND beer = ‘Bud’;

36 36 Important Points uTwo single quotes inside a string represent the single-quote (apostrophe). uConditions in the WHERE clause can use AND, OR, NOT, and parentheses in the usual way boolean conditions are built. uSQL is case-insensitive. In general, upper and lower case characters are the same, except inside quoted strings.

37 37 Patterns uWHERE clauses can have conditions in which a string is compared with a pattern, to see if it matches. uGeneral form: LIKE or NOT LIKE uPattern is a quoted string with % = “any string”; _ = “any character.”

38 38 Example uFrom Drinkers(name, addr, phone) find the drinkers with exchange 555: SELECT name FROM Drinkers WHERE phone LIKE ‘%555-_ _ _ _’;

39 39 NULL Values uTuples in SQL relations can have NULL as a value for one or more components. uMeaning depends on context. Two common cases: wMissing value : e.g., we know Joe’s Bar has some address, but we don’t know what it is. wInapplicable : e.g., the value of attribute spouse for an unmarried person.

40 40 Comparing NULL’s to Values uThe logic of conditions in SQL is really 3- valued logic: TRUE, FALSE, UNKNOWN. uWhen any value is compared with NULL, the truth value is UNKNOWN. uBut a query only produces a tuple in the answer if its truth value for the WHERE clause is TRUE (not FALSE or UNKNOWN).

41 41 Surprising Example uFrom the following Sells relation: barbeerprice Joe’s BarBudNULL SELECT bar FROM Sells WHERE price = 2.00; UNKNOWN

42 42 Exercise uList the name of all drinkers uList the name of beers started by ‘Bin’ uIs the syntax of this query correct or not? Select 1 as tag, drinker From Likes Where beer <> ‘Anheuser-Busch’ Select name From Drinkers Select name From Beers Where name Like ‘Bin%’

43 43 Exercise uFind the name of bars selling ‘Anheuser- Busch’ with price less than $5 uFind the name of bars started with ‘Zanz’ selling ‘Bir Bintang’ Select bar From Sells Where beer = ‘Anheuser-Busch’ and price < 5 Select bar From Sells Where bar like ‘Zanz%’ and beer = ‘Bir Bintang’


Download ppt "1 Introduction to Structured Query Language (SQL)."

Similar presentations


Ads by Google