You are on page 1of 97

Course Name Year

: Introduction of Database System : 2012

SQL : Data Manipulation Week 8-11

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

Objectives of SQL
Ideally, database language should allow user to:
create the database and relation structures; perform insertion, modification, deletion of data from relations; perform simple and complex queries.

Must perform these tasks with minimal user effort and command structure/syntax must be easy to learn. It must be portable.

Pearson Education 2009

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 what information you require, rather than how to get it; it is essentially free-format.

Pearson Education 2009

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

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 both the formal and de facto standard language for relational databases.

Pearson Education 2009

Writing SQL Commands


SQL statement consists of reserved words and userdefined 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

Writing SQL Commands


Most components of an SQL statement are case insensitive, except for literal character data. More readable with indentation and lineation:
Each clause should begin on a new line. Start of a clause should line up with start of other clauses. If clause has several parts, should each appear on a separate line and be indented under start of clause.

Pearson Education 2009

Writing SQL Commands


Use extended form of BNF notation: - Upper-case letters represent reserved words.

- Lower-case letters represent user-defined words. - | indicates a choice among alternatives. - Curly braces indicate a required element. - Square brackets indicate an optional element. - indicates optional repetition (0 or more).

Pearson Education 2009

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

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

SELECT Statement
SELECT FROM WHERE GROUP BY HAVING ORDER BY Specifies which columns are to appear in output. Specifies table(s) to be used. Filters rows or Join Condition. Forms groups of rows with same column value. Filters groups subject to some condition. Specifies the order of the output.

Pearson Education 2009

Entity Relationship Diagram

Bina Nusantara University

14

Example: SELECT t.Kode_Pelanggan AS [Kode Pelanggan], Nama_Pelanggan, Jenis_Pembayaran, COUNT(*) AS Total_Jumlah_Transaksi FROM Pelanggan p, Transaksi t WHERE p.Kode_Pelanggan=t.Kode_Pelanggan AND MONTH(Tgl_Transaksi)=3 OR MONTH(Tgl_Transaksi)=4 AND YEAR(Tgl_Transaksi)=2013

GROUP BY t.Kode_Pelanggan, Nama_Pelanggan, Jenis_Pembayaran


HAVING COUNT(*)>=2 ORDER BY t.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, Filter transaksi 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

Kode_ Pelan ggan

Nama_Pela nggan

Kode_Transaksi

Tgl_Transaksi

Jenis_Pembayaran

Jenis _Tra nsak si

Kode_Pelang gan

A001

Aditya

0103130001

1 March 2013

Cash

A001

B001

Budiman

0203130001

2 March 2013

Cash

B001

D001

Dani

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

Tgl_Transaksi

Jenis_Pembayaran

Kode_Pelanggan

1 March 2013

Cash

A001 Kode Pelanggan Nama_Pelanggan Jenis_Pembayaran

Total_Jum

2 March 2013

Cash

B001 A001 Aditya Cash 3

2 March 2013

Cash

A001 A001 Aditya Credit Card 2

3 March 2013

Cash

A001 B001 2 Maret 2013 Cash 1

1 April 2013

Credit Card

A001 B001 3 Maret 2013 Debit Card 2

1 April 2013

Debit Card

B001

Keterangan: Sebelum HAVING COUNT(*)>=2 diterapkan


2 April 2013 Debit Card B001

2 April 2013

Credit Card

A001

Kode Pelanggan

Nama_Pelanggan

Jenis_Pembayaran

Total_Jumlah_Transaksi

A001

Aditya

Cash

A001

Aditya

Credit Card

B001

3 Maret 2013 HAVING COUNT(*)>=2 Debit Card Keterangan: Setelah diterapkan

Example 1 All Columns, All Rows


Menampilkan semua detail/atribut dari tabel Transaksi: SELECT Kode_Transaksi, Tgl_Transaksi, Jenis_Pembayaran, Jenis_Transaksi, Kode_Pelanggan FROM Transaksi;
Kode_Transaksi Tgl_Transaksi Jenis_Pembayaran Jenis_Transaksi Kode_Pelanggan Dapat

menggunakan sebagai

pengganti
0103130001 1 March 2013 Cash A001

penulisan semua SELECT * FROM Transaksi;

kolom/atribut:
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 Pearson Education 2009

A001

Example 2 Specific Columns, All Rows


Menampilkan kode transaksi, tanggal transaksi dan jenis pembayaran dari tabel transaksi SELECT Kode_Transaksi, Tgl_Transaksi, Jenis_Pembayaran FROM Transaksi;

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

Pearson Education 2009


Credit Card

Example 3 Use of DISTINCT


Menampilkan kode pelanggan pada tabel transaksi: SELECT Kode_Pelanggan FROM Transaksi; Menghapus duplikasi dengan menggunakan DISTINCT: SELECT DISTINCT Kode_Pelanggan FROM Transaksi;
B001 Kode_Pelanggan Kode_Pelanggan A001

B001

A001

A001

A001

B001

A001

A001

B001 Pearson Education 2009

Example 4 Calculated Fields


Menghasilkan sub total barang yang dibeli pada detail 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

Kode_Transaksi

Kode_Produk

Jumlah

Harga_Satuan

Sub_Total

0103130001

P0001

1000
1000

2000

0203130001

P0001

1000

0203130001

P0002

5000

15000

0203130002

P0002

5000

25000

0203130002

P0003

25000
1000

100000

0303130001

P0001

3000

0303130001

P0002

5000

25000

0303130001

P0003

25000

25000

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;
Kode_Transaksi Kode_Produk Jumlah Harga_Satuan

0203130001

P0002

5000

0203130002

P0002

5000

0203130002

P0003

25000

0303130001

P0002
Pearson Education 2009

5000

0303130001

P0003

25000

Example 6 Compound Comparison Search Condition


Menampilkan transaksi dengan jenis pembayaran yang menggunakan Credit Card atau Debit Card: SELECT * FROM Transaksi WHERE Jenis_Pembayaran = Credit Card OR Jenis_Pembayaran = Debit Card;

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

Pearson Education 2009 Credit Card

A001

Example 7 Set Membership


Menampilkan 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

Example 8 Range Search Condition


Menampilkan 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_Transaksi WHERE Harga_Satuan >=5000 AND Harga_Satuan <= 30000; BETWEEN test includes the endpoints of range. Also a negated version NOT BETWEEN.
Pearson Education 2009

Example 8 Range Search Condition


Menampilkan 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_Transaksi WHERE Harga_Satuan <5000 OR Harga_Satuan > 30000;

Pearson Education 2009

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 any length 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

Example 9 Pattern Matching


Menampilkan 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 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

Pearson Education 2009

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 keyword IS NULL: SELECT Kode_Transaksi
FROM Transaksi WHERE Kode_Pelanggan IS NULL; Kode_Transaksi 0105130001

Negated version (IS NOT NULL) can test for non-null values.

Pearson Education 2009

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

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

SELECT Statement - Aggregates


ISO standard defines five aggregate functions:
COUNT SUM AVG MIN MAX returns number of values in specified column. returns sum of values in specified column. returns average of values in specified column. returns smallest value in specified column. returns largest value in specified column.

Pearson Education 2009

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 nonnumeric 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

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

SELECT Statement - Aggregates


Aggregate functions can be used only in SELECT list and in HAVING clause. If SELECT list includes an aggregate function and there is no GROUP BY clause, SELECT list cannot reference a column out with an aggregate function. For example, the following is illegal: SELECT staffNo, COUNT(salary)
FROM Staff;

Pearson Education 2009

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;

Kode_Transaksi

Tgl_Transaksi

....

0103130001

1 March 2013

0203130001

2 March 2013

0203130002

2 March 2013

0303130001

3 March 2013

0104130001

1 April 2013

myCount
0104130002 1 April 2013

8
0204130001 2 April 2013

0204130002
Pearson Education 2009

2 April 2013

37

Example 14 Use of COUNT(DISTINCT)


Ada berapa pelanggan yang melakukan transaksi di bulan Maret 2013? SELECT COUNT(DISTINCT Kode_Pelanggan) AS myCount FROM Transaksi WHERE Tgl_Transaksi BETWEEN 1March-2013 AND 31-March-2013;

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

myCount 2
Bagaimana hasilnya jika: SELECT COUNT(Kode_Pelanggan) AS myCount .........
0204130001 2 April 2013 B001 38 0104130002 1 April 2013 B001

0204130002 Pearson Education 2009

2 April 2013

A001

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
Kode_Trans aksi Kode_ Produk Ju mla h Harga_SaWHERE Harga_Satuan > 4000; tuan

0203130001

P0002

5000

0203130002

P0002

5000

jmlTransaksi 5

jmlProduk 18

HargaMax 25000

HargaMin 5000

HargaAvg 13000

0203130002

P0003

25000

0303130001

P0002

5000
Pearson Education 2009

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

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

Example 16 Use of GROUP BY

Menampilkan jumlah jenis produk, grand total transaksi yang dikelompokkan berdasarkan kode transaksi: SELECT Kode_Transaksi, COUNT(Kode_Produk) AS myCount, Kode_Transaksi Kode_Pr Jumlah Harga_S Sub_Tota oduk atuan SUM(Jumlah*Harga_Satuan) AS mySum FROM Detail_Transaksi 0103130001 P0001 2 1000 2 GROUP BY Kode_Transaksi ORDER BY Kode_Transaksi;
0203130001 Kode_Transaksi myCount 1 0103130001 2 0203130001 2 0203130002 3 0303130001
Pearson Education 2009

P0001

1000

mySum 2000 0203130001 P0002 3 5000

15

16000

0203130002

P0002

5000

25

125000

0203130002

P0003

25000

100

53000

0303130001

P0001

1000

0303130001

P0002

5000

25

Restricted Groupings HAVING clause


HAVING clause is designed for use with GROUP BY to 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

Example 17 Use of HAVING


Menampilkan jumlah jenis produk, grand total transaksi yang dikelompokkan berdasarkan kode transaksi 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; 0203130001 P0001 1 1000 0103130001 P0001 2 1000 Kode_Transaksi Kode_P roduk Jumlah Harga_ Satuan Sub_Total

2000

1000

0203130001
Kode_Transaksi myCount 2 mySum 16000

P0002

5000

15000

0203130002

P0002

5000

25000

0203130001
2 125000

0203130002

P0003

25000

100000

0203130002
3 53000

0303130001

P0001

1000

3000

0303130001
Pearson Education 2009 0303130001

P0002

5000

25000

Subqueries
Some SQL statements embedded within them. can have a SELECT

A subselect can be used in WHERE and HAVING clauses of an outer SELECT, where it is called a subquery or nested query. Subselects may also appear in INSERT, UPDATE, and DELETE statements.

Pearson Education 2009

Example 18 Subquery with Equality


Menampilkan 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_Pelanggan FROM Pelanggan WHERE Nama_Pelanggan = Budiman);
B001 Budiman A001 Aditya Kode_Pelanggan Nama_Pelanggan

D001

Dani

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

Example 18 Subquery with Equality


Inner SELECT finds Kode_Pelanggan for branch at Kode_Transkasi Tgl_Transaksi Jenis_Pembayaran Jenis_Transaksi Kode_Pelanggan 163 Main St (B003 ). Outer SELECT then becomes:
0203130001

SELECT staffNo, fName, lName, position 2 March 2013 Cash B001 FROM Staff WHERE branchNo = B003;
1 April 2013 Debit Card B001

0104130002

0204130001

2 April 2013

Debit Card

B001

Pearson Education 2009

Subquery Rules
ORDER BY clause may not be used in a subquery (although it may 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

Example 19 Nested subquery: use of IN


Menampilkan transaksi yang dilakukan oleh pelanggan yang namanya diawali dengan huruf A. SELECT * FROM Transaksi WHERE Kode_Pelanggan IN (SELECT Kode_Pelanggan FROM Pelanggan WHERE Nama_Pelanggan LIKE 'A%');

Jika Equality(=) hanya ada 1 nilai yang dikembalikan oleh sub query, sedangkan IN bisa mengembalikan lebih dari 1 nilai.

Pearson Education 2009

EXISTS and NOT EXISTS


EXISTS and NOT EXISTS are for use only with subqueries. Produce a simple true/false result.

True if and only if there exists at least one row in result table returned by subquery.
False if subquery returns an empty result table.

NOT EXISTS is the opposite of EXISTS.

Pearson Education 2009

EXISTS and NOT EXISTS


As (NOT) EXISTS check only for existence or nonexistence of rows in subquery result table, subquery can contain any number of columns.

Common for subqueries following (NOT) EXISTS to be of form:


(SELECT * ...)

Pearson Education 2009

Example 20 Query using EXISTS


Menampilkan transaksi yang dilakukan oleh pelanggan yang namanya diawali dengan 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

ANY and ALL


ANY and ALL may be used with subqueries that produce a single column of numbers. With ALL, condition will only be true if it is satisfied by all values produced by subquery. With ANY, condition will be true if it is satisfied by any values produced by subquery. If subquery is empty, ALL returns true, ANY returns false. SOME may be used in place of ANY.

Pearson Education 2009

Example 21 Use of ANY/SOME


Tampilkan produk yang memiliki harga lebih besar dari 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

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.

Kode_Produk P1
P2

Nama_Produk A
B

Harga 1000
5000

P3
P4 P5 P6 P7 P8

C
D E F G H
Pearson Education 2009

25000
500 30000 10000 2500 27500

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.
Kode_Produk P2 P3 P5 P6 P7 P8 Nama_Produk B C E F G H Harga 5000 25000 30000 10000 2500 27500

Pearson Education 2009

Example 22 Use of ALL


Tampilkan produk yang memiliki harga lebih besar dari semua harga satuan produk yang dibeli pada tabel detail transaski. SELECT * FROM Produk WHERE Harga > ALL (SELECT Harga_Satuan FROM Detail_Transaksi);
Kode_Produk P5 P8 Nama_Produk E H Harga 30000 27500

Pearson Education 2009

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

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

Example 23 Simple Join


Kode Pelanggan
Nama_Pelangga n

Kode_Transkasi

Tgl_Transaksi

A001

Aditya

0103130001

1 March 2013

B001

Budiman

0203130001

2 March 2013

A001

Aditya

0203130002

2 March 2013

A001

Aditya

0303130001

3 March 2013

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 equijoin in relational algebra.

A001

Aditya

0104130001

1 April 2013

B001

Budiman

0104130002

1 April 2013

B001

Budiman

0204130001

2 April 2013

Pearson Education 2009

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_Pelanggan columns.

Pearson Education 2009

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_Transaksi AND 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 Kode_Transaksi) AS tdt JOIN Produk p USING Kode_Produk
Pearson Education 2009

dt

USING

Example 24 Three Table Join


Kode_Transkasi
Tgl_Transaksi

Kode_Produk

Nama_Produk

Jumlah

0103130001

1 March 2013

P0001

0203130001

2 March 2013

P0001

0203130001

2 March 2013

P0002

0203130002

2 March 2013

P0002

0203130002

2 March 2013

P0003

0303130001

3 March 2013

P0001

0303130001

3 March 2013

P0002
Pearson Education 2009

3 March 2013

Outer Joins
If one row of a joined table is unmatched, row is omitted from result table. Outer join operations retain rows that do not satisfy the join condition. Consider following tables:

Pearson Education 2009

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

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

Example 25 Left Outer Join


List branches and properties that are in same city along with any unmatched branches.

SELECT b.*, p.*


FROM Branch1 b LEFT JOIN PropertyForRent1 p ON b.bCity = p.pCity;

Pearson Education 2009

Example 25 Left Outer Join


Includes those rows of first (left) table unmatched with rows from second (right) table. Columns from second table are filled with NULLs.

Pearson Education 2009

Example 26 Right Outer Join


List branches and properties in same city and any unmatched properties. SELECT b.*, p.*
FROM Branch1 b RIGHT JOIN PropertyForRent1 p ON b.bCity = p.pCity;

Pearson Education 2009

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

Example 27 Full Outer Join


List branches and properties in same city and any unmatched branches or properties. SELECT b.*, p.*
FROM Branch1 b FULL JOIN PropertyForRent1 p ON b.bCity = p.pCity;

Pearson Education 2009

Example 27 Full Outer Join


Includes rows that are unmatched in both tables. Unmatched columns are filled with NULLs.

Pearson Education 2009

Union, Intersect, and Difference (Except)


Can use normal set operations of Union, Intersection, and Difference to combine results of two or more queries into a single result table. Union of two tables, A and B, is table containing all rows in either A or B or both. Intersection is table containing all rows common to both A and B. Difference is table containing all rows in A but not in B. Two tables must be union compatible.

Pearson Education 2009

Union, Intersect, and Difference (Except)


Format of set operator clause in each case is:

op [ALL] [CORRESPONDING [BY {column1 [, ...]}]]


If CORRESPONDING BY specified, set operation performed 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

Union, Intersect, and Difference (Except)

Pearson Education 2009

Example 28 Use of UNION


List all cities where there is either a branch office or a property.
(SELECT city FROM Branch WHERE city IS NOT NULL) UNION (SELECT city FROM PropertyForRent WHERE city IS NOT NULL);

Pearson Education 2009

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

Example 29 Use of UNION


Produces result tables from both queries and merges both tables together.

Pearson Education 2009

Example 30 Use of INTERSECT


List all cities where there is both a branch office and a property.
(SELECT city FROM Branch) INTERSECT (SELECT city FROM PropertyForRent);

Pearson Education 2009

Example 30 Use of INTERSECT


Or
(SELECT * FROM Branch) INTERSECT CORRESPONDING BY city (SELECT * FROM PropertyForRent);

Pearson Education 2009

Example 30 Use of INTERSECT


Could rewrite operator: this query without INTERSECT

SELECT b.city FROM Branch b PropertyForRent p WHERE 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

Example 31 Use of EXCEPT


List of all cities where there is a branch office but no properties. (SELECT city FROM Branch) EXCEPT (SELECT city FROM PropertyForRent); Or (SELECT * FROM Branch) EXCEPT CORRESPONDING BY city (SELECT * FROM PropertyForRent);

Pearson Education 2009

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

INSERT
INSERT INTO TableName [ (columnList) ]
VALUES (dataValueList)

columnList is optional; if omitted, SQL assumes a list of all columns in their original CREATE TABLE order. Any columns omitted must have been declared as NULL when table was created, unless DEFAULT was specified when creating column.

Pearson Education 2009

INSERT
dataValueList must match columnList as 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

Example 32 INSERT VALUES


Insert a new row into Staff table supplying data for all columns.
INSERT INTO Staff VALUES (SG16, Alan, Brown, Assistant, M, Date195705-25, 8300, B003);

Pearson Education 2009

Example 33 INSERT using Defaults


Insert a new row into Staff table supplying data for all 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

INSERT SELECT
Second form of INSERT allows multiple rows to be copied from one or more tables to another:

INSERT INTO TableName [ (columnList) ]


SELECT ...

Pearson Education 2009

Example 34 INSERT SELECT


Assume there is a table StaffPropCount that contains names of staff and number of properties they manage:

StaffPropCount(staffNo, propCnt)
Populate StaffPropCount PropertyForRent tables.

fName,

lName,

using

Staff

and

Pearson Education 2009

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

Example 34 INSERT SELECT

If second part of UNION is omitted, excludes those staff who currently do not manage any properties.
Pearson Education 2009

UPDATE
UPDATE TableName SET columnName1 = dataValue1 [, columnName2 = dataValue2...] [WHERE searchCondition]

TableName can be name of a base table or an updatable view. SET clause specifies names of one or more columns that are to be updated.

Pearson Education 2009

UPDATE
WHERE clause is optional:
if omitted, named columns are updated for all rows in table; if specified, only those rows that satisfy searchCondition are updated.

New dataValue(s) must be compatible with data type for corresponding column.

Pearson Education 2009

Example 35/36 UPDATE All Rows


Give all staff a 3% pay increase. UPDATE Staff
SET salary = salary*1.03;

Give all Managers a 5% pay increase.


UPDATE Staff
SET salary = salary*1.05 WHERE position = Manager;

Pearson Education 2009

Example 37 UPDATE Multiple Columns


Promote David Ford (staffNo=SG14) to Manager and change his salary to 18,000.

UPDATE Staff
SET position = Manager, salary = 18000 WHERE staffNo = SG14;

SET: new values WHERE: conditions or old values

Pearson Education 2009

DELETE
DELETE FROM TableName [WHERE searchCondition]

TableName can be name of a base table or an updatable view. searchCondition is optional; if omitted, all rows are deleted from table. This does not delete table. If search_condition is specified, only those rows that satisfy condition are deleted.

Pearson Education 2009

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;

Pearson Education 2009

You might also like