Upload
muhammad-faisal-rahman
View
217
Download
0
Embed Size (px)
Citation preview
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
1/97
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
2/97
SQL : Data Manipulation
Week 8-11
Course Name : Introduction of Database System
Year : 2012
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
3/97
Outline Material
Purpose and importance of SQL.
How to retrieve data from database using SELECT and:
Use compound WHERE conditions.
Sort query results using ORDER BY.
Use aggregate functions.
Group data using GROUP BY and HAVING.
Use subqueries.
Join tables together.
Perform set operations (UNION, INTERSECT, EXCEPT).
How to update database using INSERT, UPDATE, and DELETE.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
4/97
Objectives of SQL
Ideally, database language should allow user to: create the database and relation structures;
perform insertion, modification, deletion of data fromrelations;
perform simple and complex queries. Must perform these tasks with minimal user effort
and command structure/syntax must be easy tolearn.
It must be portable.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
5/97
Objectives of SQL
SQL is a transform-oriented language with 2 major
components:
A DDL for defining database structure and controlling
access data.
A DML for retrieving and updating data.
SQL is relatively easy to learn:
it is non-procedural - you specify whatinformation you
require, rather than howto get it;
it is essentially free-format.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
6/97
Objectives of SQL
Consists of standard English words:
1) CREATE TABLE Staff(staffNo VARCHAR(5),
lName VARCHAR(15),
salary DECIMAL(7,2));2) INSERT INTO Staff VALUES (SG16,Brown, 8300);
3) SELECT staffNo, lName, salary
FROM Staff
WHERE salary > 10000;
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
7/97
Objectives of SQL
Can be used by range of users including DBAs,
management, application developers, and other
types of end users.
An ISO standard now exists for SQL, making it boththe formal and de facto standard language for
relational databases.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
8/97
Writing SQL Commands
SQL statement consists ofreserved wordsand user-
def ined words.
Reserved words are a fixed part of SQL and must be
spelt exactly as required and cannot be split across
lines.
User-defined words are made up by user and
represent names of various database objects such
as relations, columns, views.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
9/97
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
10/97
Writing SQL Commands
Use extended form of BNF notation:
- Upper-case letters represent reserved words.
- Lower-case letters represent user-defined
words.- | indicates a cho iceamong alternatives.
- Curly braces indicate a required element.
- Square brackets indicate an op t ional element.
- indicates op t ional repet i t ion(0 or more).
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
11/97
Literals
Literals are constants used in SQL statements.
All non-numeric literals must be enclosed in single
quotes (e.g. London).
All numeric literals must not be enclosed in quotes
(e.g. 650.00).
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
12/97
SELECT Statement
SELECT [DISTINCT | ALL]
{* | [columnExpression [AS newName]] [,...] }
FROM TableName [alias] [, ...]
[WHERE condition]
[GROUP BY columnList][HAVING condition]
[ORDER BY columnList]
Order of the clauses cannot be changed.
Only SELECT and FROM are mandatory.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
13/97
SELECT Statement
SELECT Specifies which columns are to appear in output.
FROM Specifies table(s) to be used.
WHERE Filters rows or Join Condition.
GROUP BY Forms groups of rows with same column value.
HAVING Filters groups subject to some condition.
ORDER BY Specifies the order of the output.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
14/97
Entity Relationship Diagram
Bina Nusantara University
14
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
15/97
Example:
SELECT t.Kode_Pelanggan AS [Kode Pelanggan], Nama_Pelanggan, Jenis_Pembayaran,COUNT(*) AS Total_Jumlah_Transaksi
FROMPelanggan p, Transaksi t
WHEREp.Kode_Pelanggan=t.Kode_Pelanggan ANDMONTH(Tgl_Transaksi)=3 OR
MONTH(Tgl_Transaksi)=4 ANDYEAR(Tgl_Transaksi)=2013
GROUP BYt.Kode_Pelanggan, Nama_Pelanggan, Jenis_Pembayaran
HAVINGCOUNT(*)>=2ORDER BYt.Kode_Pelanggan, Jenis_Pembayaran DESC;
Menampilkan: Kode_Pelanggan (diberi alias [Kode Pelanggan] supaya dapat mengandung spasi
dan diawali dengan alias tabel Transaksi untuk mengatasi ambiguitas 1 atribut ada di 2 tabel yang
berbeda), Nama_Pelanggan, Jenis_Pembayaran, total jumlah transaksi yang dilakukan (diberi
alias Total_Jumlah_Transaksi).
Berasal dari tabel: Pelanggan (diberi alias p) dan Transaksi (diberi alias t)
Kondisi Filter/Join: Join antara tabel Pelanggan dan Transaksi, Filtertransaksi yang terjadi pada
bulan Maret 2013 sampai April 2013
Dikelompokkan berdasarkan: Kode_Pelanggan, Nama_Pelanggan, Jenis_Transaksi
Filter Group: yang memenuhi COUNT(*)>=2
Diurutkan berdasarkan: (1) Kode_Pelanggan secara menaik lalu (2) Jenis_Pembayaran secara
menurun
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
16/97
Kode_Pelanggan
Nama_Pelanggan
A001 Aditya
B001 Budiman
D001 Dani
Kode_Transaksi Tgl_Transaksi Jenis_Pembayaran Jenis_Transaksi
Kode_Pelanggan
0103130001 1 March 2013 Cash A001
0203130001 2 March 2013 Cash B001
0203130002 2 March 2013 Cash A001
0303130001 3 March 2013 Cash A001
0104130001 1 April 2013 Credit Card A001
0104130002 1 April 2013 Debit Card B001
0204130001 2 April 2013 Debit Card B001
0204130002 2 April 2013 Credit Card A001
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
17/97
Tgl_Transaksi Jenis_Pembayaran Kode_Pelanggan
1 March 2013 Cash A001
2 March 2013 Cash B001
2 March 2013 Cash A001
3 March 2013 Cash A001
1 April 2013 Credit Card A001
1 April 2013 Debit Card B001
2 April 2013 Debit Card B001
2 April 2013 Credit Card A001
Kode Pelanggan Nama_Pelanggan Jenis_Pembayaran Total_Ju
A001 Aditya Cash 3
A001 Aditya Credit Card 2
B001 2 Maret 2013 Cash 1
B001 3 Maret 2013 Debit Card 2
Kode Pelanggan Nama_Pelanggan Jenis_Pembayaran Total_Jumlah_Transaksi
A001 Aditya Cash 3
A001 Aditya Credit Card 2
B001 3 Maret 2013 Debit Card 2
Keterangan: Sebelum HAVING COUNT(*)>=2 diterapkan
Keterangan: Setelah HAVING COUNT(*)>=2 diterapkan
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
18/97
Example 1 All Columns, All RowsMenampilkan semua detail/atribut dari tabel Transaksi:
SELECT Kode_Transaksi, Tgl_Transaksi, Jenis_Pembayaran, Jenis_Transaksi, Kode_Pelanggan
FROM Transaksi;
Dapat menggunakan *sebagai
pengganti
penulisan semua
kolom/atribut:
SELECT *
FROM Transaksi;
Pearson Education 2009
Kode_Transaksi Tgl_Transaksi Jenis_Pembayaran Jenis_Transaksi Kode_Pelanggan
0103130001 1 March 2013 Cash A001
0203130001 2 March 2013 Cash B001
0203130002 2 March 2013 Cash A001
0303130001 3 March 2013 Cash A001
0104130001 1 April 2013 Credit Card A001
0104130002 1 April 2013 Debit Card B001
0204130001 2 April 2013 Debit Card B001
0204130002 2 April 2013 Credit Card A001
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
19/97
Example 2 Specific Columns, All RowsMenampilkan kode transaksi, tanggal transaksi dan jenis pembayaran dari tabel transaksi
SELECT Kode_Transaksi, Tgl_Transaksi, Jenis_Pembayaran FROM Transaksi;
Pearson Education 2009
Kode_Transaksi Tgl_Transaksi Jenis_Pembayaran
0103130001 1 March 2013 Cash
0203130001 2 March 2013 Cash
0203130002 2 March 2013 Cash
0303130001 3 March 2013 Cash
0104130001 1 April 2013 Credit Card
0104130002 1 April 2013 Debit Card
0204130001 2 April 2013 Debit Card
0204130002 2 April 2013 Credit Card
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
20/97
Example 3 Use of DISTINCTMenampilkan kode pelanggan pada
tabel transaksi:
SELECT Kode_Pelanggan
FROM Transaksi;
Menghapus duplikasi dengan
menggunakan DISTINCT:
SELECT DISTINCT Kode_Pelanggan
FROM Transaksi;
Pearson Education 2009
Kode_Pelanggan
A001
B001
A001
A001
A001
B001
B001
A001
Kode_Pelanggan
A001
B001
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
21/97
Example 4 Calculated Fields
Menghasilkan sub total barang yang dibeli padadetail transaksi yang menampilkan kode transaksi,
kode produk, jumlah dan harga satuan.
SELECT Kode_Transaksi, Kode_Produk, Jumlah,Harga_Satuan, Jumlah*Harga_Satuan AS Sub_Total
FROM Detail_Transaksi;
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
22/97
Kode_Transaksi Kode_Produk Jumlah Harga_Satuan Sub_Total
0103130001 P0001 2 1000 2000
0203130001 P0001 1 1000 1000
0203130001 P0002 3 5000 15000
0203130002 P0002 5 5000 25000
0203130002 P0003 4 25000 100000
0303130001 P0001 3 1000 3000
0303130001 P0002 5 5000 25000
0303130001 P0003 1 25000 25000
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
23/97
Example 5 Comparison Search Condition
Menampilkan detail transaksi yang membeli produk dengan harga satuan lebih
besar dari 4000.
SELECT * FROM Detail_Transaksi
WHERE Harga_Satuan > 4000;
Pearson Education 2009
Kode_Transaksi Kode_Produk Jumlah Harga_Satuan
0203130001 P0002 3 5000
0203130002 P0002 5 5000
0203130002 P0003 4 25000
0303130001 P0002 5 5000
0303130001 P0003 1 25000
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
24/97
Example 6 Compound Comparison Search
ConditionMenampilkan transaksi dengan jenis pembayaran yang menggunakan Credit
Card atau Debit Card:
SELECT *
FROM Transaksi
WHERE Jenis_Pembayaran = Credit CardOR Jenis_Pembayaran = Debit Card;
Pearson Education 2009
Kode_Transaksi Tgl_Transaksi Jenis_Pembayaran Jenis_Transaksi Kode_Pelanggan
0104130001 1 April 2013 Credit Card A001
0104130002 1 April 2013 Debit Card B001
0204130001 2 April 2013 Debit Card B001
0204130002 2 April 2013 Credit Card A001
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
25/97
Example 7 Set MembershipMenampilkan transaksi dengan jenis pembayaran yang menggunakan
Credit Card atau Debit Card:
SELECT *
FROM Transaksi
WHERE Jenis_Pembayaran IN (Credit Card, Debit Card);
IN is more efficient when set contains many values.
There is a negated version (NOT IN).
Menampilkan transaksi dengan jenis pembayaran SELAIN Credit Card
atau Debit Card (yakni Cash):
SELECT *
FROM Transaksi
WHERE Jenis_Pembayaran NOT IN (Credit Card, Debit Card);
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
26/97
Example 8 Range Search ConditionMenampilkan detail transaksi yang membeli produk dengan harga
satuan antara 5000 dan 30000:
SELECT *
FROM Detail_Transaksi
WHERE Harga_Satuan BETWEEN 5000 AND 30000;
Could also write:
SELECT *
FROM Detail_TransaksiWHERE Harga_Satuan >=5000 AND Harga_Satuan
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
27/97
Example 8 Range Search ConditionMenampilkan detail transaksi yang membeli produk dengan harga
satuan diluar range 5000 dan 30000:
SELECT *
FROM Detail_Transaksi
WHERE Harga_Satuan NOT BETWEEN 5000 AND 30000;
Could also write:
SELECT *
FROM Detail_TransaksiWHERE Harga_Satuan 30000;
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
28/97
Example 9 Pattern Matching
SQL has two special pattern matching symbols:
%: sequence of zero or more characters;
_ (underscore): any single character.
LIKE %Baby% means a sequence of characters of anylength containing Baby.
Menampilkan detail transaksi dengan kode transaksi
bernilai 0113 pada karakter 3 sampai dengan 6 (Januari
2013):
SELECT * FROM Detail_Transaksi
WHERE Kode_Transaksi LIKE '_ _ 0113%'
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
29/97
Example 9 Pattern MatchingMenampilkan semua produk yang mengandung kata 'Baby' pada namanya:
SELECT * FROM Produk
WHERE Nama_Produk LIKE %Baby%;
Baby Oil, Tissue for Baby, Zwitsal Baby Hair Lotion
Pearson Education 2009
Menampilkan semua produk yang berawalan kata 'Baby' pada namanya:
SELECT * FROM Produk
WHERE Nama_Produk LIKE Baby%;
Baby Oil, Baby Hair Lotion
Menampilkan semua produk yang berakhiran kata 'Baby' pada namanya:
SELECT * FROM Produk
WHERE Nama_Produk LIKE %Baby;
Tissue for Baby, Cuddle Warm Baby
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
30/97
Example 10 NULL Search Condition
Menampilkan transaksi yang dilakukan oleh selain Pelanggan,dimana atribut Kode_Pelanggan tidak ada isinya.
Have to test for null explicitly using special keywordIS NULL:
SELECT Kode_TransaksiFROM Transaksi
WHERE Kode_Pelanggan IS NULL;
Kode_Transaksi
0105130001Negated version (IS NOT NULL) can test for non-null
values.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
31/97
Example 11 Single Column Ordering
Menampilkan semua produk diurutkan berdasarkan
harga secara menurun.
SELECT *
FROM Produk
ORDER BY Harga_Produk DESC;
ASC: menaik (ascending)
DESC: menurun (descending)Jika tidak dispesifikasikan, default-nya ascending
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
32/97
Example 12 Multiple Column Ordering
Menampilkan semua produk yang diurutkan
berdasarkan kode produk secara menaik kemudian
harga secara menurun:
SELECT *FROM Produk
ORDER BY Nama_Produk, Harga_Produk DESC;
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
33/97
SELECT Statement - Aggregates
ISO standard defines five aggregate functions:
COUNT returns number of values in specified column.
SUM returns sum of values in specified column.
AVG returns average of values in specified column.
MIN returns smallest value in specified column.
MAX returns largest value in specified column.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
34/97
SELECT Statement - Aggregates
Each operates on a single column of a table and
returns a single value.
COUNT, MIN, and MAX apply to numeric and non-
numeric fields, but SUM and AVG may be used on
numeric fields only.
Apart from COUNT(*), each function eliminates nulls
first and operates only on remaining non-null
values.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
35/97
SELECT Statement - Aggregates
COUNT(*) counts all rows of a table, regardless of
whether nulls or duplicate values occur.
Can use DISTINCT before column name to eliminate
duplicates.
DISTINCT has no effect with MIN/MAX, but may have
with SUM/AVG.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
36/97
SELECT Statement - Aggregates
Aggregate functions can be used only in SELECTlist and in HAVING clause.
If SELECT list includes an aggregate function andthere is no GROUP BY clause, SELECT list cannotreference a column out with an aggregate function.For example, the following is illegal:
SELECT staffNo, COUNT(salary)FROM Staff;
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
37/97
37
Example 13 Use of
COUNT(*)Menampilkan ada berapa transaksi yang terjadi
pada bulan Maret 2013 dan April 2013
SELECT COUNT(*) AS myCount
FROM Transaksi
WHERE MONTH(Tgl_Transaksi) IN (3,4)
AND YEAR(Tgl_Transaksi)= 2013;
Pearson Education 2009
Kode_Transaksi Tgl_Transaksi ....
0103130001 1 March 2013
0203130001 2 March 2013
0203130002 2 March 2013
0303130001 3 March 2013
0104130001 1 April 2013
0104130002 1 April 2013
0204130001 2 April 2013
0204130002 2 April 2013
myCount
8
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
38/97
38
Example 14
Use of
COUNT(DISTINCT)Ada berapa pelanggan yang melakukantransaksi di bulan Maret 2013?
SELECT COUNT(DISTINCT
Kode_Pelanggan) AS myCount
FROM Transaksi
WHERE Tgl_Transaksi BETWEEN 1-March-2013
AND 31-March-2013;
Bagaimana hasilnya jika:
SELECT COUNT(Kode_Pelanggan) AS
myCount .........
Pearson Education 2009
Kode_Transaksi Tgl_Transaksi . Kode_Pelanggan
0103130001 1 March 2013 A001
0203130001 2 March 2013 B001
0203130002 2 March 2013 A001
0303130001 3 March 2013 A001
0104130001 1 April 2013 A001
0104130002 1 April 2013 B001
0204130001 2 April 2013 B001
0204130002 2 April 2013 A001
myCount
2
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
39/97
Example 15 Use of COUNT, SUM, MAX, MIN, AVG
Menampilkan jumlah transaksi, total jumlah produk, harga satuan terbesar, harga satuan
terkecil, dan rata-rata harga satuan dari produk dengan harga satuan lebih besar dari
4000 dari Tabel DETAIL TRANSAKSI.
SELECT COUNT(Kode_Transaksi) AS JmlTransaksi, SUM(Jumlah) AS JmlProduk,
MAX(Harga_Satuan) AS HargaMax, MIN(Harga_Satuan) AS HargaMin,
AVG(Harga_Satuan) AS HargaAvg
FROM Detail_Transaksi
WHERE Harga_Satuan > 4000;
Pearson Education 2009
Kode_Transaksi
Kode_Produk
Jumlah
Harga_Satuan
0203130001 P0002 3 5000
0203130002 P0002 5 5000
0203130002 P0003 4 25000
0303130001 P0002 5 5000
jmlTransaksi jmlProduk HargaMax HargaMin HargaAvg
5 18 25000 5000 13000
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
40/97
SELECT Statement - Grouping
Use GROUP BY clause to get sub-totals.
SELECT and GROUP BY closely integrated: each
item in SELECT list must be single-valued per
group, and SELECT clause may only contain:
column names
aggregate functions
constants
expression involving combinations of the above.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
41/97
SELECT Statement - Grouping
All column names in SELECT list must appear in
GROUP BY clause unless name is used only in an
aggregate function.
If WHERE is used with GROUP BY, WHERE is
applied first, then groups are formed from remaining
rows satisfying predicate.
ISO considers two nulls to be equal for purposes of
GROUP BY.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
42/97
Example 16 Use of GROUP BYMenampilkan jumlah jenis produk, grand total transaksi yang dikelompokkanberdasarkan kode transaksi:
SELECT Kode_Transaksi,COUNT(Kode_Produk) AS myCount,
SUM(Jumlah*Harga_Satuan) AS mySum
FROM Detail_Transaksi
GROUP BY Kode_Transaksi
ORDER BY Kode_Transaksi;
Pearson Education 2009
Kode_Transaksi Kode_Produk
Jumlah Harga_Satuan
Sub_Tot
0103130001 P0001 2 1000 2
0203130001 P0001 1 1000 1
0203130001 P0002 3 5000 15
0203130002 P0002 5 5000 25
0203130002 P0003 4 25000 100
0303130001 P0001 3 1000 3
0303130001 P0002 5 5000 25
Kode_Transaksi myCount mySum
0103130001
1 2000
0203130001
2 16000
0203130002
2 125000
0303130001
3 53000
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
43/97
Restricted Groupings HAVING clause
HAVING clause is designed for use with GROUP BYto restrict groups that appear in final result table.
Similar to WHERE, but WHERE filters individual
rows whereas HAVING filters groups.
Column names in HAVING clause must also appear
in the GROUP BY list or be contained within an
aggregate function.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
44/97
Example 17 Use of HAVINGMenampilkan jumlah jenis produk, grand total transaksi yang dikelompokkan berdasarkan kodetransaksi serta minimal membeli 2 jenis produk:
SELECT Kode_Transaksi,
COUNT(Kode_Produk) AS myCount,
SUM(Jumlah*Harga_Satuan) AS mySum
FROM Detail_Transaksi
GROUP BY Kode_Transaksi
HAVING COUNT(Kode_Produk)>=2
ORDER BY Kode_Transaksi;
Pearson Education 2009
Kode_Transaksi Kode_Produk
Jumlah Harga_Satuan
Sub_Total
0103130001 P0001 2 1000 200
0203130001 P0001 1 1000 100
0203130001 P0002 3 5000 1500
0203130002 P0002 5 5000 2500
0203130002 P0003 4 25000 10000
0303130001 P0001 3 1000 300
0303130001 P0002 5 5000 2500
Kode_Transaksi myCount mySum
0203130001
2 16000
0203130002
2 125000
0303130001
3 53000
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
45/97
Subqueries
Some SQL statements can have a SELECTembedded within them.
A subselect can be used in WHERE and HAVING
clauses of an outer SELECT, where it is called a
subqueryornested query.
Subselects may also appear in INSERT, UPDATE,
and DELETE statements.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
46/97
Example 18 Subquery with EqualityMenampilkan transaksi yang dilakukan oleh pelanggan yang bernama Budiman. Dimana
equality (=) hanya mengembalikan 1 nilai pada sub query.
SELECT*
FROM Transaksi
WHERE Kode_Pelanggan=
(SELECT Kode_PelangganFROM Pelanggan
WHERE Nama_Pelanggan = Budiman);
Inner SELECT mencari Kode_Pelanggan untuk Pelanggan bernama Budiman(B001).Outer SELECT kemudian menampilkan transaksi yang dilakukan oleh Budiman. Outer
SELECT menjadi: SELECT * FROM Transaksi
WHERE Kode_Pelanggan = B001;
Pearson Education 2009
Kode_Pelanggan Nama_Pelanggan
A001 Aditya
B001 Budiman
D001 Dani
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
47/97
Example 18 Subquery with Equality
Inner SELECT finds Kode_Pelanggan for branch at163 Main St(B003).
Outer SELECT then becomes:
SELECT staffNo, fName, lName, positionFROM Staff
WHERE branchNo = B003;
Pearson Education 2009
Kode_Transkasi Tgl_Transaksi Jenis_Pembayaran Jenis_Transaksi Kode_Pelanggan
0203130001 2 March 2013 Cash B001
0104130002 1 April 2013 Debit Card B001
0204130001 2 April 2013 Debit Card B001
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
48/97
Subquery Rules
ORDER BY clause may not be used in a subquery (although itmay be used in outermost SELECT).
Subquery SELECT list must consist of a single column name
or expression, except for subqueries that use EXISTS.
By default, column names refer to table name in FROM clause
of subquery. Can refer to a table in FROM using an alias.
When subquery is an operand in a comparison, subquery
must appear on right-hand side.
A subquery may not be used as an operand in an expression.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
49/97
Example 19 Nested subquery: use of IN
Menampilkan transaksi yang dilakukan oleh pelanggan yang namanya diawalidengan huruf A.
SELECT *
FROM Transaksi
WHERE Kode_PelangganIN
(SELECT Kode_Pelanggan
FROM Pelanggan
WHERE Nama_Pelanggan LIKE 'A%');
Jika Equality(=) hanya ada 1 nilai yang dikembalikan oleh sub query, sedangkan INbisa mengembalikan lebih dari 1 nilai.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
50/97
EXISTS and NOT EXISTS
EXISTS and NOT EXISTS are for use only withsubqueries.
Produce a simple true/false result.
True if and only if there exists at least one row inresult table returned by subquery.
False if subquery returns an empty result table.
NOT EXISTS is the opposite of EXISTS.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
51/97
EXISTS and NOT EXISTS
As (NOT) EXISTS check only for existence or non-existence of rows in subquery result table, subquery
can contain any number of columns.
Common for subqueries following (NOT) EXISTS tobe of form:
(SELECT * ...)
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
52/97
Example 20 Query using EXISTS
Menampilkan transaksi yang dilakukan oleh pelanggan yang namanya diawalidengan huruf A.
SELECT *
FROM Transaksi t
WHERE EXISTS
(SELECT *
FROM Pelanggan p
WHERE Nama_Pelanggan LIKE 'A%'
AND t.Kode_Pelanggan = p.Kode_Pelanggan);
Bisa juga ditulis menggunakan JOIN:
SELECT t.*FROM Transaksi t, Pelanggan p
WHERE Nama_Pelanggan LIKE 'A%'
AND t.Kode_Pelanggan = p.Kode_Pelanggan;
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
53/97
ANY and ALL
ANY and ALL may be used with subqueries thatproduce a single column of numbers.
With ALL, condition will only be true if it is satisfiedby allvalues produced by subquery.
With ANY, condition will be true if it is satisfied byanyvalues produced by subquery.
If subquery is empty, ALL returns true, ANY returnsfalse.
SOME may be used in place of ANY.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
54/97
Example 21 Use of ANY/SOME
Tampilkan produk yang memiliki harga lebih besardari minimal salah satu harga satuan produk yang
dibeli pada tabel detail transaski.
SELECT *FROM Produk
WHERE Harga > SOME
(SELECT Harga_Satuan
FROM Detail_Transaksi);
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
55/97
Example 21 Use of ANY/SOME Inner query menghasilkan himpunan {1000, 5000, 25000} dan outer
query memilih Produk-Produk yang memiliki harga lebih besar dari
minimal salah satu nilai di himpunan tersebut.
Pearson Education 2009
Kode_Produk Nama_Produk Harga
P1 A 1000
P2 B 5000
P3 C 25000
P4 D 500
P5 E 30000
P6 F 10000
P7 G 2500
P8 H 27500
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
56/97
Example 21 Use of ANY/SOME Inner query menghasilkan himpunan {1000, 5000, 25000} dan outer
query memilih Produk-Produk yang memiliki harga lebih besar dari
minimal salah satu nilai di himpunan tersebut.
Pearson Education 2009
Kode_Produk Nama_Produk Harga
P2 B 5000
P3 C 25000
P5 E 30000
P6 F 10000
P7 G 2500
P8 H 27500
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
57/97
Example 22 Use of ALL
Tampilkan produk yang memiliki harga lebih besardari semua harga satuan produk yang dibeli pada
tabel detail transaski.
SELECT *
FROM Produk
WHERE Harga > ALL
(SELECT Harga_Satuan
FROM Detail_Transaksi);
Pearson Education 2009
Kode_Produk Nama_Produk Harga
P5 E 30000
P8 H 27500
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
58/97
Multi-Table Queries Can use subqueries provided result columns come from same table.
If result columns come from more than one table must use a join.
To perform join, include more than one table in FROM clause.
Use comma as separator and typically include WHERE clause to
specify join column(s).
Also possible to use an alias for a table named in FROM clause.
Alias is separated from table name with a space.
Alias can be used to qualify column names when there is ambiguity.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
59/97
Example 23 Simple Join
Menampilkan pelanggan yang pernah melakukan transaksi
beserta kode dan tanggal transaksi.
SELECT p.Kode_Pelanggan AS [Kode Pelanggan],
Nama_Pelanggan, Kode_Transaksi, Tgl_Transaksi
FROM Pelanggan p, Transaksi t
WHERE p.Kode_Pelanggan = t.Kode_Pelanggan;
Only those rows from both tables that have identical values in
the Kode_Pelanggan columns (p.Kode_Pelanggan =t.Kode_Pelanggan) are included in result.
Equivalent to equi-join in relational algebra.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
60/97
Example 23 Simple Join
Only those rows fromboth tables that have
identical values in the
Kode_Pelanggan
columns
(p.Kode_Pelanggan =t.Kode_Pelanggan)
are included in result. Equivalent to equi-
join in relationalalgebra.
Pearson Education 2009
Kode
Pelanggan
Nama_Pelanggan Kode_Transkasi Tgl_Transaksi
A001Aditya
0103130001 1 March 2013
B001Budiman
0203130001 2 March 2013
A001Aditya
0203130002 2 March 2013
A001Aditya
0303130001 3 March 2013
A001 Aditya 0104130001 1 April 2013
B001Budiman
0104130002 1 April 2013
B001Budiman
0204130001 2 April 2013
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
61/97
Alternative JOIN Constructs
SQL provides alternative ways to specify joins:
FROM Pelanggan p JOIN Transaksi t ON p.Kode_Pelanggan =
t.Kode_Pelanggan
FROM Pelanggan JOIN Transaksi USING Kode_Pelanggan
FROM Pelanggan NATURAL JOIN Transaksi
In each case, FROM replaces original FROM and WHERE.
However, first produces table with two identical
Kode_Pelanggancolumns.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
62/97
Example 24 Three Table Join
Menampilkan kode transaksi, tanggal transaksi, kode produk,nama produk, jumlah produk yang dibeli.
SELECT t.Kode_Transaksi AS [Kode Transaksi], Tgl_Transaksi,p.Kode_Produk AS [Kode Produk], Nama_Produk, Jumlah
FROM Transaksi t, Detail_Transaksi dt, Produk p
WHERE t.Kode_Transaksi = dt.Kode_TransaksiAND dt.Kode_Produk = p.Kode_Produk
ORDER BY t.Kode_Transaksi, p.Kode_Produk;
Alternative formulation for FROM and WHERE:
FROM (Transaksi t JOIN Detail_Transaksi dt USINGKode_Transaksi) AS
tdt JOIN Produk p USING Kode_Produk
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
63/97
Example 24 Three Table Join
Pearson Education 2009
Kode_Transkasi
Tgl_Transaksi
Kode_ProdukNama_Produk
Jumlah
01031300011 March 2013
P0001A
2
02031300012 March 2013
P0001A
1
02031300012 March 2013
P0002B
3
02031300022 March 2013
P0002B
5
02031300022 March 2013
P0003C
4
03031300013 March 2013
P0001A
3
03031300013 March 2013
P0002B
5
3 March 2013 C
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
64/97
Outer Joins
If one row of a joined table is unmatched, row isomitted from result table.
Outer join operations retain rows that do not satisfy
the join condition.
Consider following tables:
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
65/97
Outer Joins
The (inner) join of these two tables:
SELECT b.*, p.*
FROM Branch1 b, PropertyForRent1 p
WHERE b.bCity = p.pCity;
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
66/97
Outer Joins
Result table has two rows where cities are same.
There are no rows corresponding to branches in
Bristol and Aberdeen.
To include unmatched rows in result table, use an
Outer join.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
67/97
Example 25 Left Outer Join
List branches and properties that are in same cityalong with any unmatched branches.
SELECT b.*, p.*
FROM Branch1 b LEFT JOIN
PropertyForRent1 p ON b.bCity = p.pCity;
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
68/97
Example 25 Left Outer Join
Includes those rows of first (left) table unmatchedwith rows from second (right) table.
Columns from second table are filled with NULLs.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
69/97
Example 26 Right Outer Join
List branches and properties in same city and anyunmatched properties.
SELECT b.*, p.*
FROM Branch1 b RIGHT JOINPropertyForRent1 p ON b.bCity = p.pCity;
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
70/97
Example 26 Right Outer Join
Right Outer join includes those rows of second(right) table that are unmatched with rows from first
(left) table.
Columns from first table are filled with NULLs.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
71/97
Example 27 Full Outer Join
List branches and properties in same city and anyunmatched branches or properties.
SELECT b.*, p.*
FROM Branch1 b FULL JOINPropertyForRent1 p ON b.bCity = p.pCity;
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
72/97
Example 27 Full Outer Join
Includes rows that are unmatched in both tables.
Unmatched columns are filled with NULLs.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
73/97
Union, Intersect, and Difference (Except)
Can use normal set operations of Union,Intersection, and Difference to combine results oftwo or more queries into a single result table.
Union of two tables, A and B, is table containing allrows in either A or B or both.
Intersection is table containing all rows common toboth A and B.
Difference is table containing all rows in A but not inB.
Two tables must be union com patib le.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
74/97
Union, Intersect, and Difference (Except)
Format of set operator clause in each case is:
op [ALL] [CORRESPONDING [BY {column1 [,
...]}]]
If CORRESPONDING BY specified, set operationperformed on the named column(s).
If CORRESPONDING specified but not BY clause,
operation performed on common columns.
If ALL specified, result can include duplicate rows.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
75/97
Union, Intersect, and
Difference (Except)
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
76/97
Example 28 Use of UNION
List all cities where there is either a branch office ora property.
(SELECT city
FROM Branch
WHERE city IS NOT NULL) UNION(SELECT city
FROM PropertyForRent
WHERE city IS NOT NULL);
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
77/97
Example 28 Use of UNION
Or
(SELECT *
FROM Branch
WHERE city IS NOT NULL)
UNION CORRESPONDING BY city(SELECT *
FROM PropertyForRent
WHERE city IS NOT NULL);
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
78/97
Example 29 Use of UNION
Produces result tables from both queries andmerges both tables together.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
79/97
Example 30 Use of INTERSECT
List all cities where there is both a branch office anda property.
(SELECT city FROM Branch)
INTERSECT(SELECT city FROM PropertyForRent);
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
80/97
Example 30 Use of INTERSECT
Or
(SELECT * FROM Branch)
INTERSECT CORRESPONDING BY city
(SELECT * FROM PropertyForRent);
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
81/97
Example 30 Use of INTERSECT
Could rewrite this query without INTERSECToperator:
SELECT b.city
FROM Branch b PropertyForRent pWHERE b.city = p.city;
Or:
SELECT DISTINCT city FROM Branch b
WHERE EXISTS(SELECT * FROM PropertyForRent p
WHERE p.city = b.city);
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
82/97
Example 31 Use of EXCEPT
List of all cities where there is a branch office but noproperties.
(SELECT city FROM Branch)
EXCEPT
(SELECT city FROM PropertyForRent); Or
(SELECT * FROM Branch)
EXCEPT CORRESPONDING BY city
(SELECT * FROM PropertyForRent);
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
83/97
Example 31 Use of EXCEPT
Could rewrite this query without EXCEPT:
SELECT DISTINCT city FROM Branch
WHERE city NOT IN
(SELECT city FROM PropertyForRent); Or
SELECT DISTINCT city FROM Branch b
WHERE NOT EXISTS
(SELECT * FROM PropertyForRent p
WHERE p.city = b.city);
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
84/97
INSERT
INSERT INTO TableName [ (columnList) ]VALUES (dataValueList)
co lumnLis tis optional; if omitted, SQL assumes a
list of all columns in their original CREATE TABLEorder.
Any columns omitted must have been declared asNULL when table was created, unless DEFAULT wasspecified when creating column.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
85/97
INSERT
dataValueListmust match co lumnLis tas follows: number of items in each list must be same;
must be direct correspondence in position of items in two
lists;
data type of each item in dataValueList must be
compatible with data type of corresponding column.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
86/97
Example 32 INSERT VALUES
Insert a new row into Staff table supplying data forall columns.
INSERT INTO Staff
VALUES (SG16, Alan, Brown, Assistant, M, Date1957-05-25, 8300, B003);
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
87/97
Example 33 INSERT using Defaults
Insert a new row into Staff table supplying data forall mandatory columns.
INSERT INTO Staff (staffNo, fName, lName,
position, salary, branchNo)
VALUES (SG44,Anne,Jones,Assistant, 8100, B003);
Or
INSERT INTO Staff
VALUES (SG44, Anne, Jones, Assistant,NULL, NULL, 8100, B003);
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
88/97
INSERT SELECT
Second form of INSERT allows multiple rows to becopied from one or more tables to another:
INSERT INTO TableName [ (columnList) ]
SELECT ...
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
89/97
Example 34 INSERT SELECT
Assume there is a table StaffPropCount thatcontains names of staff and number of properties
they manage:
StaffPropCount(staffNo, fName, lName,
propCnt)
Populate StaffPropCount using Staff and
PropertyForRent tables.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
90/97
Example 34 INSERT SELECT
INSERT INTO StaffPropCount(SELECT s.staffNo, fName, lName, COUNT(*)
FROM Staff s, PropertyForRent p
WHERE s.staffNo = p.staffNo
GROUP BY s.staffNo, fName, lName)UNION
(SELECT staffNo, fName, lName, 0
FROM Staff
WHERE staffNo NOT IN(SELECT DISTINCT staffNo
FROM PropertyForRent));
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
91/97
Example 34 INSERT SELECT
If second part of UNION is omitted, excludes thosestaff who currently do not manage any properties.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
92/97
UPDATE
UPDATE TableNameSET columnName1 = dataValue1
[, columnName2 = dataValue2...]
[WHERE searchCondition]
TableNamecan be name of a base table or anupdatable view.
SET clause specifies names of one or morecolumns that are to be updated.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
93/97
UPDATE
WHERE clause is optional: if omitted, named columns are updated for all rows in
table;
if specified, only those rows that satisfy searchCondi t ion
are updated.
New dataValue(s)must be compatible with data
type for corresponding column.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
94/97
Example 35/36 UPDATE All Rows
Give all staff a 3% pay increase.
UPDATE StaffSET salary = salary*1.03;
Give all Managers a 5% pay increase.
UPDATE StaffSET salary = salary*1.05
WHERE position = Manager;
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
95/97
Example 37 UPDATE Multiple Columns
Promote David Ford (staffNo=SG14) to Managerand change his salary to 18,000.
UPDATE Staff
SET position = Manager, salary = 18000
WHERE staffNo = SG14;
SET: new valuesWHERE: conditions or old values
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
96/97
DELETE
DELETE FROM TableName[WHERE searchCondition]
TableNamecan be name of a base table or an
updatable view.
searchCondi t ionis optional; if omitted, all rows are
deleted from table. This does not delete table. If
search_condi t ionis specified, only those rows that
satisfy condition are deleted.
Pearson Education 2009
7/30/2019 M05640020220124029M0564 PSBD Pert 15-16 Additional DML VerMA10mei13
97/97
Example 38/39 DELETE Specific Rows
Delete all viewings that relate to property PG4.
DELETE FROM Viewing
WHERE propertyNo = PG4;
Delete all records from the Viewing table.
DELETE FROM Viewing;