1 Introduction to Structured Query Language (SQL).

43
1 Introduction to Structured Query Language (SQL)

Transcript of 1 Introduction to Structured Query Language (SQL).

Page 1: 1 Introduction to Structured Query Language (SQL).

1

Introduction to Structured Query Language (SQL)

Page 2: 1 Introduction to Structured Query Language (SQL).

2

RA Exercise SALESPERSON(SSN, Name, Start_Year,

Dept_No) TRIP(SSN, From_City, Departure_Date,

Return_Date, Trip_ID) EXPENSE(Trip_ID, Account#, Amount)

Give the details (all attributes of TRIP relation) for trips that exceeded $2000 in expense

Print the SSN of salesman who took trips to Honolulu

Search the Name & Dept_No of salesman who took trips from ‘Jakarta’ and expensed no more than $1000

Page 3: 1 Introduction to Structured Query Language (SQL).

3

Join ExampleSells( bar beer price ) Bars( bar addr )

Joe’s Bud 2.50 Joe’s Maple St.Joe’s Miller 2.75 Sue’s River Rd.Sue’s Bud 2.50Sue’s Coors3.00

BarInfo := Sells JOIN Bars

BarInfo( bar beer price addr )Joe’s Bud 2.50 Maple St.Joe’s Milller 2.75 Maple St.Sue’s Bud 2.50 River Rd.Sue’s Coors3.00 River Rd.

Page 4: 1 Introduction to Structured Query Language (SQL).

4

Database

Page 5: 1 Introduction to Structured Query Language (SQL).

5

Why SQL?

SQL 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++.

What makes SQL viable is that its queries are “optimized” quite well, yielding efficient query executions.

Page 6: 1 Introduction to Structured Query Language (SQL).

6

SQL Components DDL – Data definition language

Defining the relational schema – relations, attributes, domains (the meta-data)

Dropping/altering the relational schema DML – Data manipulation language

Defining the queries against the schema Inserting, deleting and modifying data

Others Integrity (allowable values/referential) Catalog and dictionary facilities Transaction control (long-duration and batch) Authorization (who can do what when)

Page 7: 1 Introduction to Structured Query Language (SQL).

7

Our Running Example

All our SQL queries will be based on the following database schema. Underline 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)

Page 8: 1 Introduction to Structured Query Language (SQL).

8

Data Definition Language - DDL

A Pre-Defined set of Primitive Types Numeric Character-string Bit-string Additional Types

Defining Domains Defining Schema Defining Tables Defining Views Note: Each DBMS May have their Own

DBMS Specific Data Types

Page 9: 1 Introduction to Structured Query Language (SQL).

9

Primitive Types Numeric

INTEGER (or INT), SMALLINT REAL, DOUBLE PRECISION FLOAT(N) Floating Point with at Least N Digits DECIMAL(P,D) (DEC(P,D) or NUMERIC(P,D))

have P Total Digits with D to Right of Decimal

Note that INTs and REALs are Machine Dependent (Based on Hardware/OS Platform)

Page 10: 1 Introduction to Structured Query Language (SQL).

10

Primitive Types Character-String

CHAR(N) or CHARACTER(N) - Fixed VARCHAR(N), CHAR VARYING(N), or

CHARACTER VARYING(N) Variable with at Most N Characters

Bit-Strings BIT(N) Fixed VARBIT(N) or BIT VARYING(N)

Variable with at Most N Bits

Page 11: 1 Introduction to Structured Query Language (SQL).

11

Primitive Types

These Specialized Primitive Types are Used to: Simplify Modeling Process Include “Popular” Types Reduce Composite

Attributes/Programming DATE : YYYY-MM-DD TIME: HH-MM-SS

Page 12: 1 Introduction to Structured Query Language (SQL).

12

What are Domains?

Domains are Similar in Concepts to Programming Language Type Definitions

A Domain can be Defined as Follows:CREATE DOMAIN DrinkerName CHAR(25) DEFAULT

‘Joe’;CREATE DOMAIN BeerName CHAR(20);

Advantage of Using Domains Changing a Domain Definition in One Place

Changes it Consistently Everywhere it is Used Default Values Can Be Defined for Domains Constraints Can Be Defined for Domains

Page 13: 1 Introduction to Structured Query Language (SQL).

13

Dropping a Domain

A Domain is Dropped As Follows:DROP DOMAIN DrinkerName RESTRICT;DROP DOMAIN BeerName CASCADE;

Restrict: Drop Operation Fails If the Domain is Used in

Column Definitions

Cascade: Drop Operation Causes Columns to be

Defined Directly on the Underlying Data Type

Page 14: 1 Introduction to Structured Query Language (SQL).

14

What is a SQL Schema? A Schema in SQL is the Major Meta-Data

Construct Supports the Definition of:

Relation - Table with Name Attributes - Columns and their Types Identification - Primary Key Constraints - Referential Integrity (FK)

Two Part Definition CREATE Schema - Named Database or

Conceptually Related Tables CREATE Table - Individual Tables of the

Schema

Page 15: 1 Introduction to Structured Query Language (SQL).

15

Create/Drop Schema For schema BeerWorld

SQL: CREATE SCHEMA BeerWorld Authorization Indra;

Drop schema BeerWorldSQL: DROP SCHEMA BeerWorld RESTRICT;DROP SCHEMA BeerWorld CASCADE;

Restrict: • Drop Operation Fails If Schema is Not Empty

Cascade: • Drop Operation Removes Everything in the Schema

Page 16: 1 Introduction to Structured Query Language (SQL).

16

Create Table

Create table Drinkers Drinkers(name, addr, phone)

CREATE TABLE Drinkers(name VARCHAR(25),addr VARCHAR(40),phone CHAR(10),PRIMARY KEY(name)

);

Page 17: 1 Introduction to Structured Query Language (SQL).

17

Create Table Default value: gives the default value for a

column/attribute Example: name VARCHAR(25) DEFAULT ‘Joe’

Constraint: gives the constraint to the column/attribute. It can be used for: Specifying the primary key/foreign key Specifying column that can’t have the null value Preserving the integrity of the database

• Deleting the record• Modifying the value of primary key

SET DEFAULT, SET NULL, CASCADE

Page 18: 1 Introduction to Structured Query Language (SQL).

18

Create Table Create table Drinkers(name, addr, phone)

CREATE TABLE Drinkers(name VARCHAR(25) NOT NULL,

…,CONSTRAINT pkDrinkers PRIMARY KEY(name)

);

Create table Sells(bar, beer, price)CREATE TABLE Sells(

bar VARCHAR(25) NOT NULL, beer VARCHAR(25) NOT NULL, price DECIMAL(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

Page 19: 1 Introduction to Structured Query Language (SQL).

19

Drop Tables

Command:DROP TABLE Drinkers RESTRICT;DROP TABLE Sells CASCADE;

Restrict: Drop Operation fails if the Table is Referenced

by View and/or Constraint Definitions

Cascade: Drop Operation Removes Referencing View

and Constraint Definitions

Page 20: 1 Introduction to Structured Query Language (SQL).

20

Alter Table Change the table structures:

Adding or dropping column Changing column definition Adding or dropping table constraint

Adding column “job” in table “Drinkers”: ALTER TABLE Drinkers ADD job VARCHAR(20);

Dropping column “job” in table “Drinkers”: ALTER TABLE Drinkers DROP job CASCADE; ALTER TABLE Drinkers DROP job RESTRICT; Restrict: Drop Operation Fails if Column is

Referenced Cascade: Drop Operation Removes Referencing

View and Constraint Definitions

Page 21: 1 Introduction to Structured Query Language (SQL).

21

Basic Query In SQL

Page 22: 1 Introduction to Structured Query Language (SQL).

22

Basic Query in SQL

The principal form of a query is:

SELECT desired attributesFROM one or more tablesWHERE condition about tuples of the tables

GROUP BY attribute list HAVING condition ORDER BY attribute list

Basic Query

Page 23: 1 Introduction to Structured Query Language (SQL).

23

Example

Using Beers(name, manf), what beers are made by Anheuser-Busch?

SELECT name

FROM Beers

WHERE manf = ‘Anheuser-Busch’;

Page 24: 1 Introduction to Structured Query Language (SQL).

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 beerby Anheuser-Busch, such as Bud.

Page 25: 1 Introduction to Structured Query Language (SQL).

25

Meaning of Single-Relation Query

Begin with the relation in the FROM clause.

Apply the selection indicated by the WHERE clause.

Apply the extended projection indicated by the SELECT clause.

Page 26: 1 Introduction to Structured Query Language (SQL).

26

Operational Semantics

To implement this algorithm think of a tuple variable ranging over each tuple of the relation mentioned in FROM.

Check if the “current” tuple satisfies the WHERE clause.

If so, compute the attributes or expressions of the SELECT clause using the components of this tuple.

Page 27: 1 Introduction to Structured Query Language (SQL).

27

* In SELECT clauses When there is one relation in the FROM

clause, * in the SELECT clause stands for “all attributes of this relation.”

Example using Beers(name, manf):SELECT *

FROM Beers

WHERE manf = ‘Anheuser-Busch’;

Page 28: 1 Introduction to Structured Query Language (SQL).

28

Result of Query:

name manf‘Bud’ ‘Anheuser-

Busch’‘Bud Lite’ ‘Anheuser-

Busch’‘Michelob’ ‘Anheuser-

Busch’

Now, the result has each of the attributesof Beers.

Page 29: 1 Introduction to Structured Query Language (SQL).

29

Renaming Attributes

If you want the result to have different attribute names, use “AS <new name>” to rename an attribute.

Example based on Beers(name, manf):SELECT name AS beer, manf

FROM Beers

WHERE manf = ‘Anheuser-Busch’

Page 30: 1 Introduction to Structured Query Language (SQL).

30

Result of Query:

beer manf‘Bud’ ‘Anheuser-

Busch’‘Bud Lite’ ‘Anheuser-

Busch’‘Michelob’ ‘Anheuser-

Busch’

Page 31: 1 Introduction to Structured Query Language (SQL).

31

Expressions in SELECT Clauses

Any expression that makes sense can appear as an element of a SELECT clause.

Example: from Sells(bar, beer, price):SELECT bar, beer,

price*8000 AS prcInRupiah

FROM Sells;

Page 32: 1 Introduction to Structured Query Language (SQL).

32

Result of Query

bar beerprcInRupiah

Joe’s Bud 40000Sue’s Miller 56000 … … …

Page 33: 1 Introduction to Structured Query Language (SQL).

33

Another Example: Constant Expressions

From Likes(drinker, beer):

SELECT drinker,

‘likes Bud’ AS whoLikesBud

FROM Likes

WHERE beer = ‘Bud’;

Page 34: 1 Introduction to Structured Query Language (SQL).

34

Result of Query

drinker whoLikesBud‘Sally’ ‘likes Bud’‘Fred’ ‘likes Bud’ … …

Page 35: 1 Introduction to Structured Query Language (SQL).

35

Complex Conditions in WHERE Clause

From 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’;

Page 36: 1 Introduction to Structured Query Language (SQL).

36

Important Points

Two single quotes inside a string represent the single-quote (apostrophe).

Conditions in the WHERE clause can use AND, OR, NOT, and parentheses in the usual way boolean conditions are built.

SQL is case-insensitive. In general, upper and lower case characters are the same, except inside quoted strings.

Page 37: 1 Introduction to Structured Query Language (SQL).

37

Patterns

WHERE clauses can have conditions in which a string is compared with a pattern, to see if it matches.

General form: <Attribute> LIKE <pattern> or <Attribute> NOT LIKE <pattern>

Pattern is a quoted string with % = “any string”; _ = “any character.”

Page 38: 1 Introduction to Structured Query Language (SQL).

38

Example

From Drinkers(name, addr, phone) find the drinkers with exchange 555:

SELECT name

FROM Drinkers

WHERE phone LIKE ‘%555-_ _ _ _’;

Page 39: 1 Introduction to Structured Query Language (SQL).

39

NULL Values

Tuples in SQL relations can have NULL as a value for one or more components.

Meaning depends on context. Two common cases: Missing value : e.g., we know Joe’s Bar has

some address, but we don’t know what it is. Inapplicable : e.g., the value of attribute

spouse for an unmarried person.

Page 40: 1 Introduction to Structured Query Language (SQL).

40

Comparing NULL’s to Values

The logic of conditions in SQL is really 3-valued logic: TRUE, FALSE, UNKNOWN.

When any value is compared with NULL, the truth value is UNKNOWN.

But a query only produces a tuple in the answer if its truth value for the WHERE clause is TRUE (not FALSE or UNKNOWN).

Page 41: 1 Introduction to Structured Query Language (SQL).

41

Surprising Example

From the following Sells relation:bar beer priceJoe’s BarBud NULL

SELECT barFROM SellsWHERE price < 2.00 OR price >= 2.00; UNKNOWN UNKNOWN

UNKNOWN

Page 42: 1 Introduction to Structured Query Language (SQL).

42

Exercise List the name of all drinkers

List the name of beers started by ‘Bin’

Is the syntax of this query correct or not?

Select 1 as tag, drinker From Likes Where beer <> ‘Anheuser-Busch’

Select name From Drinkers

Select nameFrom BeersWhere name Like ‘Bin%’

Page 43: 1 Introduction to Structured Query Language (SQL).

43

Exercise Find the name of bars selling ‘Anheuser-

Busch’ with price less than $5

Find the name of bars started with ‘Zanz’ selling ‘Bir Bintang’

Select barFrom SellsWhere beer = ‘Anheuser-Busch’ and price

< 5

Select barFrom SellsWhere bar like ‘Zanz%’ and beer = ‘Bir

Bintang’