database system concepts - fenix.tecnico.ulisboa.pt · chapter 3: sql departamento de engenharia...

87
Database System Concepts Data Definition Language Querying the Database Views Modification of the Database Joined Relations Examples Database System Concepts Chapter 3: SQL Departamento de Engenharia Inform´ atica Instituto Superior T´ ecnico 1 st Semester 2010/2011 Slides (fortemente) baseados nos slides oficiais do livro “Database System Concepts” c Silberschatz, Korth and Sudarshan.

Upload: nguyentram

Post on 26-Dec-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Database System ConceptsChapter 3: SQL

Departamento de Engenharia InformaticaInstituto Superior Tecnico

1st Semester2010/2011

Slides (fortemente) baseados nos slides oficiais do livro“Database System Concepts”c©Silberschatz, Korth and Sudarshan.

Page 2: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Outline

1 Data Definition Language

2 Querying the DatabaseBasic SQL QueriesAggregation and Set OperationsNull ValuesComplex Queries

3 Views

4 Modification of the Database

5 Joined Relations

6 Examples

Page 3: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Outline

1 Data Definition Language

2 Querying the Database

3 Views

4 Modification of the Database

5 Joined Relations

6 Examples

Page 4: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Data Definition Language

Allows the specification of not only a set of relations but alsoinformation about each relation, including:

The schema for each relation.

The domain of values associated with each attribute.

Integrity constraints

The set of indices to be maintained for each relations.

Security and authorization information for each relation.

The physical storage structure of each relation on disk.

Page 5: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Domain Types in SQL

char(n) - Fixed length character string, with user-specifiedlength n.varchar(n) - Variable length character strings, withuser-specified maximum length n.int - Integer (a finite subset of the integers that ismachine-dependent).smallint - Small integer (a machine-dependent subset ofthe integer domain type).numeric(p,d) - Fixed point number, with user-specifiedprecision of p digits, with n digits to the right of decimalpoint.real, double - Floating point and double-precision floatingpoint numbers, with machine-dependent precision.float(n) - Floating point number, with user-specifiedprecision of at least n digits.More are covered in the book...

Page 6: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Creating Tables

An SQL relation is defined using the create table

command:

create table r ((A1 D1,A2 D2, . . . ,An Dn)constraint1, . . . , constraintk

)

r is the name of the relationeach Ai is an attribute name in the schema of relation rDi is the data type of values in the domain of attribute Ai

Example:

create table branch (branch name char(15),branch city char(30),assets integer )

Page 7: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Integrity Constraints

Ensuring non-null values: not null

Defining the identifier: primary key (A1, . . . ,An)

Example:

create table branch (branch name char(15),branch city char(30),assets integer not null,primary key (branch name)

)

Note: primary key also ensures that the attribute is not null

Page 8: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Deleting and Altering Tables

The drop table command deletes all information aboutthe dropped relation from the database.

drop table r

The alter table command is used to add/removeattributes to/from an existing relation:

alter table r add A Dalter table r drop A

where A is the name of the attribute to be added torelation r and D is the domain of A.

All tuples in the relation are assigned null as the value forthe new attribute.Dropping of attributes is not supported by many databases

Page 9: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Outline

1 Data Definition Language

2 Querying the DatabaseBasic SQL QueriesAggregation and Set OperationsNull ValuesComplex Queries

3 Views

4 Modification of the Database

5 Joined Relations

6 Examples

Page 10: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Basic Query Structure

SQL is based on set and relational operations with certainmodifications and enhancements

A typical SQL query has the form:

select A1,A2, . . . ,An

from r1, r2, . . . , rmwhere P

Ai represents an attributeri represents a relationP is a predicate.

This query is equivalent to the relational algebra expression

πA1,A2,...,An

(σP(r1 × r2 × · · · × rm)

)The result of an SQL query is a relation

Page 11: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

The select Clause

The select clause list the attributes desired in the result ofa query

Corresponds to the projection operation of the relationalalgebra

Example: find the names of all branches in the loanrelation:

select branch namefrom loan

In the relational algebra, the query would be:

πbranch name(loan)

Note : SQL names are case insensitive (i.e., you may use upper- orlower-case letters.)

Page 12: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

The select Clause (cont.)

SQL allows duplicates in relations as well as in queryresults

To force the elimination of duplicates, insert the keyworddistinct after select

Example: find the names of all branches in the loanrelations, and remove duplicates

select distinct branch namefrom loan

The keyword all specifies that duplicates not be removed

select all branch namefrom loan

Page 13: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

The select Clause (cont.)

An asterisk in the select clause denotes “all attributes”

select ∗from loan

The select clause can contain arithmetic expressionsinvolving the operation, +, −, ∗, and /, and operating onconstants or attributes of tuples

select loan number , branch name, amount ∗ 100from loan

would return a relation that is the same as the loan relation,except that the value of the attribute amount is multiplied by100.

Page 14: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

The where Clause

The where clause specifies conditions that the result mustsatisfy

Corresponds to the selection predicate of the relationalalgebra

Example: to find all loan number for loans made at thePerryridge branch with loan amounts greater than $1200

select loan numberfrom loanwhere branch name = ’Perryridge’ and amount > 1200

Comparison results can be combined using the logicalconnectives and, or, and not

Comparisons can be applied to results of arithmeticexpressions

Page 15: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

The where Clause (cont.)

SQL includes a between comparison operator

Example: Find the loan number of those loans with loanamounts between $90 000 and $100 000 (that is,≥ $90 000 and ≤ $100 000)

select loan numberfrom loanwhere amount between 90000 and 100000

Page 16: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

The from Clause

The from clause lists the relations involved in the query

Corresponds to the Cartesian product operation of therelational algebra

Example: find the Cartesian product borrower × loan

select ∗from borrower , loan

Example: find the name, loan number and loan amount ofall customers having a loan at the Perryridge branch

Page 17: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

The from Clause

The from clause lists the relations involved in the query

Corresponds to the Cartesian product operation of therelational algebra

Example: find the Cartesian product borrower × loan

select ∗from borrower , loan

Example: find the name, loan number and loan amount ofall customers having a loan at the Perryridge branch

loan(loan number , branch name, amount)borrower(customer name, loan number)

Page 18: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

The from Clause

The from clause lists the relations involved in the query

Corresponds to the Cartesian product operation of therelational algebra

Example: find the Cartesian product borrower × loan

select ∗from borrower , loan

Example: find the name, loan number and loan amount ofall customers having a loan at the Perryridge branch

select customer name, loan.loan number , amountfrom loan, borrowerwhere loan.loan number = borrower .loan number

and branch name = ’Perryridge’

Page 19: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Renaming

SQL allows renaming relations and attributes using the as

clause:

old-name as new-name

Example: find the name, loan number and loan amount ofall customers; rename the column loan number as loan id

select customer name, borrower .loan number as loan id ,amount

from borrower , loanwhere borrower .loan number = loan.loan number

Page 20: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Tuple Variables

Tuple variables are defined in the from clause via the useof the as clause.

Example: find the customer names and their loan numbersfor all customers having a loan

select customer name, B.loan number , L.amountfrom borrower as B, loan as Lwhere B.loan number = L.loan number

Example: find the names of all branches that have greaterassets than some branch located in Brooklyn

Page 21: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Tuple Variables

Tuple variables are defined in the from clause via the useof the as clause.

Example: find the customer names and their loan numbersfor all customers having a loan

select customer name, B.loan number , L.amountfrom borrower as B, loan as Lwhere B.loan number = L.loan number

Example: find the names of all branches that have greaterassets than some branch located in Brooklyn

branch(branch name, branch city , assets)

Page 22: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Tuple Variables

Tuple variables are defined in the from clause via the useof the as clause.

Example: find the customer names and their loan numbersfor all customers having a loan

select customer name, B.loan number , L.amountfrom borrower as B, loan as Lwhere B.loan number = L.loan number

Example: find the names of all branches that have greaterassets than some branch located in Brooklyn

select distinct T .branch namefrom branch as T , branch as Swhere T .assets > S .assets and S .branch city = ’Brooklyn’

Page 23: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

String Operations

The operator like uses patterns that are described usingtwo special characters:

percent (%) - matches any substring.underscore ( ) - matches any character.

Example: find the names of all customers whose streetincludes the substring “Main”

select customer namefrom customerwhere customer street like ’%Main%’

To match the name “Main%”

like ’Main\%’ escape ’\’

SQL supports many other string operations

Page 24: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Ordering the Display of Tuples

List in alphabetic order the names of all customers havinga loan in Perryridge branch

select distinct customer namefrom borrower B, loan Lwhere B.loan number = L.loan number

and branch name = ’Perryridge’order by customer name

We may specify desc for descending order or asc forascending order (the default)

order by customer name desc

Page 25: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Set Operations

Find all customers who have a loan, an account, or both

(select customer name from depositor)union(select customer name from borrower)

Find all customers who have both a loan and an account

(select customer name from depositor)intersect(select customer name from borrower)

Find all customers who have an account but no loan

(select customer name from depositor)except(select customer name from borrower)

Each of the above operations automatically eliminates duplicates; to retainall duplicates use the corresponding multiset versions: union all,intersect all and except all

Page 26: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Aggregate Functions

Operate on the multiset of values of a column of a relation, andreturn a value

avg, min, max, sum, count

Find the average account balance at the Perryridge branch

select avg(balance)from accountwhere branch name = ’Perryridge’

Find the number of tuples in the customer relation

select count(∗) from customer

Find the number of depositors in the bank

select count(distinct customer name)from depositor

Page 27: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Aggregate Functions - group by

Find the number of depositors for each branch

select branch name, count(distinct customer name)from depositor , accountwhere depositor .account number = account.account numbergroup by branch name

Note: attributes in select clause outside of aggregate functionsmust appear in group by list

Page 28: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Aggregate Functions - having

Find the names of all branches where the average accountbalance is more than $1 200

select branch name, avg(balance)from accountgroup by branch namehaving avg(balance) > 1200

Note: predicates in the having clause are applied after the formation

of groups whereas predicates in the where clause are applied before

forming groups

Page 29: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Null Values

It is possible for tuples to have the null value

The result of any arithmetic expression involving null isnull

Any comparison with null returns unknownThe predicates is null and is unknown can be used tocheck for null values and unknown results

select loan numberfrom loanwhere amount is null

select loan numberfrom loanwhere amount > 1000 is unknown

Note: result of where clause predicate is treated as false if itevaluates to unknown

Page 30: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Null Values and Aggregates

Total all loan amounts

select sum(amount)from loan

Above statement ignores null amounts

Result is null if there is no non-null amount

All aggregate operations except count(∗) ignore tupleswith null values on the aggregated attributes.

Page 31: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Nested Subqueries

A common use of nested subqueries is to perform tests forset membership, set comparisons, and set cardinality

Find all customers who have both an account and a loanat the bank

select distinct customer namefrom borrowerwhere customer name in (select customer name

from depositor)

Find all customers who have a loan at the bank but do nothave an account at the bank

select distinct customer namefrom borrowerwhere customer name not in (select customer name

from depositor)

Page 32: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Set Comparison

Find all branches that have greater assets than some branchlocated in Brooklyn

select branch namefrom branchwhere assets >some (select assets

from branchwhere branch city = ’Brooklyn’)

>some, <some, =some, <>some

Find the names of all branches that have greater assets than allbranches located in Brooklyn

select branch namefrom branchwhere assets >all (select assets

from branchwhere branch city = ’Brooklyn’)

>all, <all, =all, <>all

Page 33: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Test for Empty Relations

The exists construct returns the value true if theargument subquery is nonempty

exists r ⇔ r 6= ∅Example: find all customers who do not have an accountat the Perryridge branch

select D.customer namefrom depositor Dwhere not exists (

select T .customer namefrom account A, depositor Twhere D.customer name = T .customer name and

T .account number = A.account number andA.branch name = ’Perryridge’)

Page 34: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Division

Find all customers who have an account at all brancheslocated in Brooklyn

select distinct S .customer namefrom depositor Swhere not exists (

(select branch namefrom branchwhere branch city = ’Brooklyn’)except(select R.branch namefrom depositor T , account Rwhere T .account number = R.account number andS .customer name = T .customer name ))

Page 35: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Division

Find all customers who have an account at all brancheslocated in Brooklyn

select distinct S .customer namefrom depositor Swhere not exists (

(select branch namefrom branchwhere branch city = ’Brooklyn’)except(select R.branch namefrom depositor T , account Rwhere T .account number = R.account number andS .customer name = T .customer name ))

Page 36: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Test for Absence of Duplicate Tuples

The unique construct tests whether a subquery has anyduplicate tuples in its result

Example: find all customers who have at most oneaccount at the Perryridge branch

select D.customer namefrom depositor Dwhere unique (

select T .customer namefrom account A, depositor Twhere D.customer name = T .customer name and

T .account number = A.account number andA.branch name = ’Perryridge’)

What about all customers who have at least two accountsat the Perryridge branch?

Page 37: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

Derived Relations

SQL allows a subquery expression to be used in the fromclause

Find the average account balance of those branches wherethe average account balance is greater than $1200

select branch name, avg balancefrom (select branch name, avg(balance)

from accountgroup by branch name)

as branch avg(branch name, avg balance)where avg balance > 1200

Page 38: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Basic SQLQueries

Aggregation andSet Operations

Null Values

Complex Queries

Views

Modificationof theDatabase

JoinedRelations

Examples

The with Clause

The with clause provides a way of defining a temporaryview whose definition is available only to the query inwhich the with clause occurs

Example: find all accounts with the maximum balance

with max balance(value) asselect max(balance)from account

select account numberfrom account, max balancewhere account.balance = max balance.value

Page 39: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Outline

1 Data Definition Language

2 Querying the Database

3 Views

4 Modification of the Database

5 Joined Relations

6 Examples

Page 40: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Views

In some cases, it is not desirable for all users to see theentire logical model

Consider a person who needs to know a customer’s loannumber but has no need to see the loan amount

select customer name, loan numberfrom borrower , loanwhere borrower .loan number = loan.loan number

A view provides a mechanism to hide certain data fromthe view of certain users.

Page 41: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

View Definition

A view is defined using the create view statement whichhas the form

create view v as <query expression>

where <query expression> is any legal SQL expression.The view name is represented by v .

Once a view is defined, the view name can be used to referto the virtual relation that the view generates.

View definition is not the same as creating a new relationby evaluating the query expressionRather, a view definition causes the saving of anexpression; the expression is substituted into queries usingthe view.

Page 42: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

View Examples

A view consisting of branches and their customers

create view all customer as(select branch name, customer namefrom depositor D, account Awhere D.account number = A.account number)

union(select branch name, customer namefrom borrower B, loan Lwhere B.loan number = L.loan number)

Find all customers of the Perryridge branch

select customer namefrom all customerwhere branch name = ’Perryridge’

Page 43: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Outline

1 Data Definition Language

2 Querying the Database

3 Views

4 Modification of the Database

5 Joined Relations

6 Examples

Page 44: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Deleting Tuples

Delete all account tuples at the Perryridge branch

delete from accountwhere branch name = ’Perryridge’

Delete all accounts at every branch located in the city’Needham’

delete from accountwhere branch name in (select branch name

from branchwhere branch city = ’Needham’)

Page 45: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Insertion

Add a new tuple to account

insert into accountvalues (’A-9732’, ’Perryridge’, 1200)

or equivalently

insert into account(branch name, balance, account number)values (’Perryridge’, 1200, ’A-9732’)

Add a new tuple to account with balance set to null

insert into accountvalues (’A-777’, ’Perryridge’, null)

Page 46: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Insertion (cont.)

Provide as a gift for all loan customers of the Perryridgebranch, a $200 savings account. Let the loan numberserve as the account number for the new savings account

insert into accountselect loan number , branch name, 200from loanwhere branch name = ’Perryridge’

insert into depositorselect customer name, loan numberfrom loan, borrowerwhere branch name = ’Perryridge’ and

loan.account number = borrower .account number

Page 47: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Updates

Increase all accounts with balances over $10,000 by 6%,all other accounts receive 5%

update accountset balance = balance ∗ 1.06where balance > 10000

update accountset balance = balance ∗ 1.05where balance <= 10000

update accountset balance =

casewhen balance <= 10000 then balance ∗ 1.05else balance ∗ 1.06

end

Page 48: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Updates

Increase all accounts with balances over $10,000 by 6%,all other accounts receive 5%

update accountset balance = balance ∗ 1.06where balance > 10000

update accountset balance = balance ∗ 1.05where balance <= 10000

update accountset balance =

casewhen balance <= 10000 then balance ∗ 1.05else balance ∗ 1.06

end

Page 49: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Update of a View

Create a view of all loan data in the loan relation, hidingthe amount attribute

create view branch loan asselect branch name, loan numberfrom loan

Add a new tuple to branch loan

insert into branch loanvalues (’Perryridge’, ’L-307’)

This insertion must be represented by the insertion of thetuple

(’L-307’, ’Perryridge’, null)

into the loan relation

Page 50: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Update of a View (cont.)

Some updates through views are impossible to translateinto updates on the database relations

create view avg bal asselect branch name, avg(balance)from accountgroup by branch name

insert into avg balvalues (’Downtown’, 300)

Most SQL implementations allow updates only on simpleviews (without aggregates) defined on a single relation

Page 51: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Outline

1 Data Definition Language

2 Querying the Database

3 Views

4 Modification of the Database

5 Joined Relations

6 Examples

Page 52: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Join Operations

Join types

inner join

left outer join

right outer join

full outer join

Join conditions

natural

on <predicate>

using (A1,A2, . . . ,An)

Page 53: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Join Operations (cont.)

loan

loan number branch name amount

L-170 Downtown 3000L-230 Redwood 4000L-260 Perryridge 1700

borrower

customer name loan number

Jones L-170Smith L-230Hayes L-155

select ∗ fromloan inner join borrower

on loan.loan number = borrower .loan number

loan number branch name amount customer name loan number

L-170 Downtown 3000 Jones L-170L-230 Redwood 4000 Smith L-230

Page 54: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Join Operations (cont.)

loan

loan number branch name amount

L-170 Downtown 3000L-230 Redwood 4000L-260 Perryridge 1700

borrower

customer name loan number

Jones L-170Smith L-230Hayes L-155

select ∗ fromloan natural join borrower

loan number branch name amount customer name

L-170 Downtown 3000 JonesL-230 Redwood 4000 Smith

Page 55: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Join Operations (cont.)

loan

loan number branch name amount

L-170 Downtown 3000L-230 Redwood 4000L-260 Perryridge 1700

borrower

customer name loan number

Jones L-170Smith L-230Hayes L-155

select ∗ fromloan left outer join borrower

on loan.loan number = borrower .loan number

loan number branch name amount customer name loan number

L-170 Downtown 3000 Jones L-170L-230 Redwood 4000 Smith L-230L-260 Perryridge 1700 null null

Page 56: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Join Operations (cont.)

loan

loan number branch name amount

L-170 Downtown 3000L-230 Redwood 4000L-260 Perryridge 1700

borrower

customer name loan number

Jones L-170Smith L-230Hayes L-155

select ∗ fromloan natural right outer join borrower

loan number branch name amount customer name

L-170 Downtown 3000 JonesL-230 Redwood 4000 SmithL-155 null null Hayes

Page 57: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Join Operations (cont.)

loan

loan number branch name amount

L-170 Downtown 3000L-230 Redwood 4000L-260 Perryridge 1700

borrower

customer name loan number

Jones L-170Smith L-230Hayes L-155

select ∗ fromloan full outer join borrower using(loan number)

loan number branch name amount customer name

L-170 Downtown 3000 JonesL-230 Redwood 4000 SmithL-260 Perryridge 1700 nullL-155 null null Hayes

Page 58: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Outline

1 Data Definition Language

2 Querying the Database

3 Views

4 Modification of the Database

5 Joined Relations

6 Examples

Page 59: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get data from all customers

account(account number , branch name, balance)branch(branch name, branch city , assets)

customer(customer name, customer street, customer city)loan(loan number , branch name, amount)

depositor(customer name, account number)borrower(customer name, loan number)

Page 60: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get data from all customers

select ∗ from customer

Page 61: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name and city of all customers with a loan

account(account number , branch name, balance)branch(branch name, branch city , assets)

customer(customer name, customer street, customer city)loan(loan number , branch name, amount)

depositor(customer name, account number)borrower(customer name, loan number)

Page 62: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name and city of all customers with a loan

select distinct c .customer name, customer cityfrom borrower b, customer cwhere b.customer name = c .customer name

Page 63: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name and city of all customers with a loan at thePerryridge branch

account(account number , branch name, balance)branch(branch name, branch city , assets)

customer(customer name, customer street, customer city)loan(loan number , branch name, amount)

depositor(customer name, account number)borrower(customer name, loan number)

Page 64: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name and city of all customers with a loan at thePerryridge branch

select distinct c .customer name, customer cityfrom borrower b, customer c, loan lwhere b.customer name = c .customer name

and b.loan number = l .loan numberand branch name = ’Perryridge’

Page 65: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the number of all accounts with a balance between $700and $900

account(account number , branch name, balance)branch(branch name, branch city , assets)

customer(customer name, customer street, customer city)loan(loan number , branch name, amount)

depositor(customer name, account number)borrower(customer name, loan number)

Page 66: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the number of all accounts with a balance between $700and $900

select account numberfrom accountwhere balance between 700 and 900

Page 67: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name of all customers whose street name ends in ’Hill’

account(account number , branch name, balance)branch(branch name, branch city , assets)

customer(customer name, customer street, customer city)loan(loan number , branch name, amount)

depositor(customer name, account number)borrower(customer name, loan number)

Page 68: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name of all customers whose street name ends in ’Hill’

select customer namefrom customerwhere customer street like ’%Hill’

Page 69: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name of all customers with both an account and a loanat the Perryridge branch

account(account number , branch name, balance)branch(branch name, branch city , assets)

customer(customer name, customer street, customer city)loan(loan number , branch name, amount)

depositor(customer name, account number)borrower(customer name, loan number)

Page 70: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name of all customers with both an account and a loanat the Perryridge branch

select distinct b.customer namefrom borrower b, loan l , depositor d , account awhere b.loan number = l .loan number

and b.customer name = d .customer nameand d .account number = a.account numberand a.branch name = ’Perryridge’and l .branch name = ’Perryridge’

Page 71: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name of all customers with an account at any branchwhere customer Hayes has an account

account(account number , branch name, balance)branch(branch name, branch city , assets)

customer(customer name, customer street, customer city)loan(loan number , branch name, amount)

depositor(customer name, account number)borrower(customer name, loan number)

Page 72: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name of all customers with an account at any branchwhere customer Hayes has an account

select distinct d .customer namefrom depositor d , account awhere d .account number = a.account number

and branch name in(select branch namefrom depositor d , account awhere d .account number = a.account number

and d .customer name = ’Hayes’)

Page 73: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name of all branches with higher assets than allbranches in Brooklyn

account(account number , branch name, balance)branch(branch name, branch city , assets)

customer(customer name, customer street, customer city)loan(loan number , branch name, amount)

depositor(customer name, account number)borrower(customer name, loan number)

Page 74: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name of all branches with higher assets than allbranches in Brooklyn

select branch namefrom branchwhere assets > all

(select assetsfrom branchwhere branch city = ’Brooklyn’)

Page 75: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name of all clients with a loan at the Perryridgebranch, sorted by customer name

account(account number , branch name, balance)branch(branch name, branch city , assets)

customer(customer name, customer street, customer city)loan(loan number , branch name, amount)

depositor(customer name, account number)borrower(customer name, loan number)

Page 76: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name of all clients with a loan at the Perryridgebranch, sorted by customer name

select distinct customer namefrom borrower b, loan lwhere b.loan number = l .loan number

and l .branch name = ’Perryridge’order by b.customer name

Page 77: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name and number of customers of all branches

account(account number , branch name, balance)branch(branch name, branch city , assets)

customer(customer name, customer street, customer city)loan(loan number , branch name, amount)

depositor(customer name, account number)borrower(customer name, loan number)

Page 78: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name and number of customers of all branches

select branch name, count(distinct customer name)from depositord , accountawhere d .account number = a.account numbergroup by branch name

Page 79: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name and average balance of all branches with anaverage balance above $700

account(account number , branch name, balance)branch(branch name, branch city , assets)

customer(customer name, customer street, customer city)loan(loan number , branch name, amount)

depositor(customer name, account number)borrower(customer name, loan number)

Page 80: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name and average balance of all branches with anaverage balance above $700

select branch name, avg(balance)from accountgroup by branch namehaving avg(balance) > 700

Page 81: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name of the branches with the highest average balance

account(account number , branch name, balance)branch(branch name, branch city , assets)

customer(customer name, customer street, customer city)loan(loan number , branch name, amount)

depositor(customer name, account number)borrower(customer name, loan number)

Page 82: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the name of the branches with the highest average balance

select branch namefrom accountgroup by branch namehaving avg(balance) >= all

(select avg(balance)from accountgroup by branch name)

Page 83: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the total number of customers in the database

account(account number , branch name, balance)branch(branch name, branch city , assets)

customer(customer name, customer street, customer city)loan(loan number , branch name, amount)

depositor(customer name, account number)borrower(customer name, loan number)

Page 84: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get the total number of customers in the database

select count(∗) from customer

Page 85: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get average balance of all customers who live in Harrison andhave, at least, two bank accounts

account(account number , branch name, balance)branch(branch name, branch city , assets)

customer(customer name, customer street, customer city)loan(loan number , branch name, amount)

depositor(customer name, account number)borrower(customer name, loan number)

Page 86: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

Example Queries

Get average balance of all customers who live in Harrison andhave, at least, two bank accounts

select avg(balance)from depositor d , account a, customer cwhere d .customer name = c.customer name

and d .account number = a.account numberand customer city = ’Harrison’

group by d .customer namehaving count(distinct a.account number) >= 2

Page 87: Database System Concepts - fenix.tecnico.ulisboa.pt · Chapter 3: SQL Departamento de Engenharia Inform atica Instituto Superior T ecnico 1st Semester 2010/2011 Slides (fortemente)

DatabaseSystem

Concepts

DataDefinitionLanguage

Querying theDatabase

Views

Modificationof theDatabase

JoinedRelations

Examples

End of Chapter 3