Anda di halaman 1dari 50

SQL

Oleh:
Syaiful Anam, S.Si, MT
Jurusan Matematika Universitas Brawijaya
Email : syaiful@brawijaya.ac.id

Tabel-Tabel

Skema Yang Digunakan


Dalam contoh

Struktur Dasar

SQL query mempunyai bentuk:


select A1, A2, ..., An
from r1, r2, ..., rm
where P
Ai : atribut
ri

: relasi

: predicate.
Query ini setara dengan ungkapan aljabar
relasional.
A1, A2, ..., An(P (r1 x r2 x ... x rm))
Hasil dari SQL query adalah sebuah relasi.

Select

Klausa select menampilkan atribut yang diinginkan


dalam hasil query
Contoh:
menemukan nama-nama dari semua cabang dalam
relasi pinjaman
select namacabang
from loan
Dalam sintaks "murni" aljabar relational, pertanyaan
akan:
namacabangloan)

Select

Menghapus duplikat,memasukkan kata distinct


setelah select.
Cari nama-nama dari semua cabang dalam
hubungan pinjaman, dan hapus duplikat
select distinct namacabang
from loan
Kata Kunci all menetapkan bahwa duplikat tidak
dihapus.
select all namacabang
from loan

Select

Asterisk dalam select menotasikan all attributes


select *
from loan
Klausa select dapat berisi ekspresi matematika melibatkan
operasi +, , , and /, dan operasi pada konstanta atau atribut
dari tuple.
Query:
select nomorpeminjam, namacabang, jumlah
100
from loan
Hasil :relasi yang sama dengan relasi loan kecuali attribute
jumlah dikalikan 100.

Klausa where

Klausa where menentukan kondisi yang hasilnya


harus memenuhi.
sesuai dengan predikat seleksi dari aljabar relasional.
Untuk mencari semua nomor pinjaman untuk pinjaman
yang dilakukan di cabang Ngawi dengan jumlah
pinjaman lebih besar dari 100.
select nomorpinjaman
from loan
where namacabang= Ngawi and jumlah > 100
Perbandingan dapat dikombinasikan menggunakan
koneksi logika and, or, dan not.
Perbandingan dapat diaplikasikan untuk arithmetic

expressions.

Klausa where

SQL mencakup antara operator perbandingan


Cari jumlah pinjaman kredit tersebut dengan
jumlah pinjaman antara 100 dan 1000
(yaitu100 dan 1000)
select nomorpinjaman from loan where jumlah between
100 and 1000

Klausa from

Klausa from mendaftar relasi yang memenuhi query


Berkorespondesi dengan operasi Cartesian product dari
relational algebra.
Temukan Cartesian product borrower x loan
select
from borrower, loan

Cari nama, Nomor pinjaman dan jumlah pinjaman semua pelanggan

yang memiliki pinjaman di cabang Ngawi.


select namapelanggan, borrower.nomorpinjaman, jumlah from
borrower, loan where borrower.nomorpinjaman =
loan.nomorpinjaman and namacabang = 'Ngawi'

Operasi Rename

SQL memungkinkan mengubah nama hubungan dan atribut


menggunakan klausa sebagai:
old-name as new-name

Cari nama, jumlah pinjaman dan jumlah pinjaman semua


pelanggan; mengubah nama kolom nomorpinjaman
sebagai pinjaman_id.

select namapelanggan, borrower.nomorpinjaman as loan_id,


jumlah from borrower, loan where borrower.nomorpinjaman=
loan.nomorpinjaman

Tuple Variables

Cari nama pelanggan dan nomor pinjaman


mereka untuk semua pelanggan yang
memiliki pinjaman pada beberapa cabang.

select namapelanggan, T.nomorpinjaman, S.jumlah from borrower as


T, loan as S where T.nomorpinjaman = S.nomorpinjaman

Cari nama-nama dari semua cabang yang memiliki asset


lebih besar dari beberapa cabang berlokasi di Malang

select distinct T.namacabang, T.Kotacabang from


branch as T, branch as S where T.asset > S.asset and S.kotacabang =
'Malang'

String Operations

SQL memasukkan operator pencocokan string untuk


perbandingan pada karakter string.

Cari nama semua pelanggan yang nama jalannya


mengandung substring krajan".
select namapelanggan
from customer
where jalanpelanggan like '%krajan%'
SQL mendukung berbagai operasi string seperti

concatenation (using ||)


converting from upper to lower case (and

vice versa)
finding string length, extracting substrings,
etc.

Ordering

Daftar dalam urutan abjad nama semua pelanggan


yang memiliki pinjaman di cabang Bantur
select distinct namapelangganfrom borrower,
loan
where borrower.nomorpinjaman =
loan.nomorpinjaman and namacabang = 'ngawi'
order by namapelanggan
Kami dapat menetapkan desc untuk descending
urutan atau urutan AZ untuk, untuk setiap atribut,
urutan naik adalah default.
Contoh: order by customer-name desc

Duplicates

In relations with duplicates, SQL can define how


many copies of tuples appear in the result.
Multiset versions of some of the relational algebra
operators given multiset relations r1 and r2:
1. (r1): If there are c1 copies of tuple t1 in r1, and t1
satisfies selections ,, then there are c1 copies of t1 in
(r1).
2. A(r1): For each copy of tuple t1 in r1, there is a copy of
tuple A(t1) in A(r1) where A(t1) denotes the projection of
the single tuple t1.
3. r1 x r2 : If there are c1 copies of tuple t1 in r1 and c2
copies of tuple t2 in r2, there are c1 x c2 copies of the
tuple t1. t2 in r1 x r2

Duplicates (Cont.)

Example: Suppose multiset relations r1 (A, B) and r2


(C) are as follows:
r1 = {(1, a) (2,a)}
r2 = {(2), (3), (3)}

Then B(r1) would be {(a), (a)}, while B(r1) x r2


would be
{(a,2), (a,2), (a,3), (a,3), (a,3), (a,3)}
SQL duplicate semantics:
select A1,, A2, ..., An
from r1, r2, ..., rm
where P
is equivalent to the multiset version of the
expression:
A1,, A2, ..., An(P (r1 x r2 x ... x rm))

Set Operations

The set operations union, intersect, and except operate on


relations and correspond to the relational algebra operations

Each of the above operations automatically eliminates


duplicates; to retain all duplicates use the corresponding
multiset versions union all, intersect all and except all.
Suppose a tuple occurs m times in r and n times in s, then, it
occurs:
m + n times in r union all s
min(m,n) times in r intersect all s
max(0, m n) times in r except all s

Set Operations

Temukan nama pelanggan yang mempunyai loan, account, atau keduanya :

(select namapelanggan from depositor)


union
(select namapelanggan from borrower)

Cari semua pelanggan yang mempunyai pinjaman dan account.

select depositor.namapelanggan from


borrower,depositor where
depositor.namapelanggan=borrower.namapelanggan

Find all customers who have an account but no loan.

(select depositor.namapelanggan from depositor left join


borrower on
depositor.namapelanggan=borrower.namapelanggan where
borrower.namapelanggan is null

Temukan semua pelanggan yang hanya meminjam dan hanya deposiit

saja

(select depositor.namapelanggan from depositor left join


borrower on depositor.namapelanggan=borrower.namapelanggan
where borrower.namapelanggan is null)
union
(select borrower.namapelanggan from borrower left join
depositor on depositor.namapelanggan=borrower.namapelanggan
where depositor.namapelanggan is null)

Aggregate Functions

These functions operate on the multiset of


values of a column of a relation, and return a
value
avg: average value
min: minimum value
max: maximum value
sum: sum of values
count: number of values

Aggregate Functions (Cont.)

Find the average account balance at the bantur branch.

select avg (balance)


'bantur'

from account where namacabang =

Find the number of tuples in the customer relation.

select count (*)


from customer

Find the number of depositors in the bank.

select count (distinct namapelanggan)


from depositor

Aggregate Functions Group


By

Find the number of depositors for each branch.


select namacabang, count (distinct namapelanggan)from
depositor, account
where depositor.nomerrekening = account.nomorrekening
group by namacabang

Note: Attributes in select clause outside of aggregate functions must


appear in group by list

Aggregate Functions Having


Clause

Find the names of all branches where the average


account balance is more than $1,200.
select namacabang, avg (balance)from account
group by namacabang having 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

Null Values

It is possible for tuples to have a null value, denoted by


null, for some of their attributes
null signifies an unknown value or that a value does not
exist.
The predicate is null can be used to check for null values.
E.g. Find all loan number which appear in the loan
relation with null values for amount.
select loan-number
from loan
where amount is null
The result of any arithmetic expression involving null is null
E.g. 5 + null returns null
However, aggregate functions simply ignore nulls
more on this shortly

Null Values and Three Valued


Logic

Any comparison with null returns unknown


E.g. 5 < null or null <> null or null = null
Three-valued logic using the truth value unknown:
OR: (unknown or true) = true, (unknown or false) =
unknown
(unknown or unknown) = unknown
AND: (true and unknown) = unknown, (false and
unknown) = false,
(unknown and unknown) = unknown
NOT: (not unknown) = unknown
P is unknown evaluates to true if predicate P evaluates
to unknown
Result of where clause predicate is treated as false if it
evaluates to unknown

Null Values and Aggregates

Total all loan amounts


select sum (jumlah) from loan

Above statement ignores null amounts


result is null if there is no non-null amount
All aggregate operations except count(*) ignore

tuples with null values on the aggregated


attributes.

Nested Subqueries

SQL provides a mechanism for the nesting of


subqueries.
A subquery is a select-from-where
expression that is nested within another
query.
A common use of subqueries is to perform
tests for set membership, set comparisons,
and set cardinality.

Example Query

Find all customers who have both an


account and a loan at the bank.
select distinct namapelanggan from borrower
where namapelanggan in
(select namapelanggan from depositor)

Find all customers who have a loan at the bank but do not have

an account at the bank


select distinct namapelanggan from borrower
where namapelanggan not in
(select namapelanggan from depositor)

Set Comparison

Find all branches that have greater assets than


some branch located in malang.
select distinct T.namacabang
from branch as T, branch as S
where T.asset > S.asset and

S.kotacabang = 'malang'
Same query using > some clause
select namacabang
from branch
where asset > some
(select asset
from branch
where kotacabang= 'malang')

Definition of Some Clause

F <comp> some r t r s.t. (F <comp> t)


Where <comp> can be:

(5< some

0
5
6

) = true
(read: 5 < some tuple in the relation)

(5< some

0
5

) = false

(5 = some

0
5

) = true

0
(5 some 5 ) = true (since 0 5)
(= some) in
However, ( some) not in

Definition of all Clause

F <comp> all r t r (F <comp> t)


(5< all

0
5
6

) = false

(5< all

6
10

) = true

(5 = all

4
5

) = false

4
(5 all 6 ) = true (since 5 4 and 5 6)
( all) not in
However, (= all) in

Example Query

Find the names of all branches that have greater


assets than all branches located in Malang.
select namacabang
from branch
where asset > all
(select asset
from branch
where kotacabang = 'malang')

Test for Empty Relations

The exists construct returns the value true


if the argument subquery is nonempty.
exists r r
not exists r r =

Views

Provide a mechanism to hide certain data from the


view of certain users. To create a view we use the
command:
create view v as <query expression>
where:
<query expression> is any legal expression
The view name is represented by v

Example Queries

A view consisting of branches and their customers


create view allcustomer as
(select namacabang, namapelanggan
from depositor, account
where depositor.nomerrekening = account.nomorrekening )
union
(select namacabang, namapelanggan
from borrower, loan
where borrower.nomorpinjaman = loan.nomorpinjaman)

Find all customers of the Perryridge branch

select namapelanggan
from all_customer
where namacabang = 'bantur'

Derived Relations

Find the average account balance of those branches


where the average account balance is greater than $1200.
select namacabang, avg_balance
from (select namacabang, avg (balance) as
avg_balance
from account
group by namacabang)
as result (namacabang, avg_balance)
where avg_balance > 1200
Note that we do not need to use the having clause, since
we compute the temporary (view) relation result in the
from clause, and the attributes of result can be used
directly in the where clause.

Inner Join

select * from branch b inner join account a on


b.namacabang=a.namacabang inner join
depositor d on
d.nomerrekening=a.nomorrekening

Outer Join

An extension of the join operation that avoids loss of


information.
Computes the join and then adds tuples form one relation that
does not match tuples in the other relation to the result of the
join.
Uses null values:
null signifies that the value is unknown or does not exist
All comparisons involving null are (roughly speaking) false
by definition.
Will study precise meaning of comparisons with nulls
later

Left

select * from loan l left outer join borrower b on


b.nomorpinjaman=l.nomorpinjaman

Right

select * from borrower b right outer join loan l on


b.nomorpinjaman=l.nomorpinjaman

Full

select * from borrower b Full outer join loan l


on b.nomorpinjaman=l.nomorpinjaman

Anda mungkin juga menyukai