0% found this document useful (0 votes)
72 views

SQL Data Manipulation 1

This document discusses SQL data manipulation and provides examples of using SELECT statements to retrieve data from a database. It covers selecting specific columns or all columns, filtering rows using WHERE clauses, sorting results with ORDER BY, and using functions like DISTINCT, calculated fields, comparison operators, and compound conditions. The examples demonstrate retrieving staff data based on salary amounts, city names, and other fields.

Uploaded by

MFachry Nazuli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

SQL Data Manipulation 1

This document discusses SQL data manipulation and provides examples of using SELECT statements to retrieve data from a database. It covers selecting specific columns or all columns, filtering rows using WHERE clauses, sorting results with ORDER BY, and using functions like DISTINCT, calculated fields, comparison operators, and compound conditions. The examples demonstrate retrieving staff data based on salary amounts, city names, and other fields.

Uploaded by

MFachry Nazuli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

SQL Data Manipulation 1

LECTURE 4

Dr. Said Mirza Pahlevi


Lecture 4 - Objectives
2

 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.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Objectives of SQL
4

 SQL is a transform-oriented language, that is, a language


designed to use relations to transform inputs into required
outputs

 It has 2 major components:


 A DDL for defining database structure.
 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.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Objectives of SQL
5

 Consists of standard English words:

 CREATE TABLE Staff(staffNo VARCHAR(5),


lName VARCHAR(15),
salary DECIMAL(7,2));

 INSERT INTO Staff VALUES (‘SG16’, ‘Brown’, 8300);

 SELECT staffNo, lName, salary FROM Staff WHERE salary >


10000;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Objectives of SQL
6

 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.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Writing SQL Commands
7

 SQL statement consists of reserved words and user-


defined 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.
Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)
Writing SQL Commands
8

 Most components of an SQL statement are case


insensitive, except for literal character data.
 e.g., search with ‘SMITH’ will not return ‘Smith’

 More readable with indentation and lineation:, e.g.,


 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.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Literals
10

 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).

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


SELECT Statement
11

SELECT [DISTINCT | ALL]


{* | [columnExpression [AS newName]] [,...] }
FROM TableName [alias] [, ...]
[WHERE condition]
[GROUP BY columnList] [HAVING condition]
[ORDER BY columnList]

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


SELECT Statement
12

 FROM: Specifies relation/table(s) to be used.


 WHERE: Filters tuple/rows.
 GROUP BY: Forms groups of rows with same column
value.
 HAVING: Filters groups subject to some condition.
 SELECT: Specifies which columns are to appear in
output.
 ORDER BY: Specifies the order of the output.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


SELECT Statement
13

 Order of the clauses cannot be changed.

 Only SELECT and FROM are mandatory.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 1: All Columns, All Rows
14

 List full details of all staff.

SELECT staffNo, fName, lName, position,


sex, DOB, salary, branchNo
FROM Staff;

 Can use * as an abbreviation for ‘all columns’:

SELECT *
FROM Staff;
Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)
Result of Example 1
15

SELECT staffNo, fName, lName,


position, sex, DOB, salary, branchNo
FROM Staff;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 2: Specific Columns, All Rows
16

Produce a list of salaries for all staff, showing only staff


number, first and last names, and salary.

SELECT staffNo, fName, lName, salary


FROM Staff;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Result of Example 2
17

SELECT staffNo, fName, lName, salary


FROM Staff;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 3: A Specific Column
18

List the property numbers of all properties that have


been viewed.

SELECT propertyNo
FROM Viewing;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 4: Use of DISTINCT
19

Use DISTINCT to eliminate duplicates:


SELECT DISTINCT position
FROM Staff;
Staff query result
position
Manager
Assistant
supervisor

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 5: Calculated Fields
20

Produce list of monthly salaries for all staff, showing


staff number, first/last name, and salary.
SELECT staffNo, fName, lName, salary/12
FROM Staff;
Staff Result

2500.00
1000.00
1500.00
750.00
2000.00
7500.00

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 6: Calculated Fields
21

To name column, use AS clause:


SELECT staffNo, fName, lName, salary/12
AS monthlySalary
FROM Staff; Result
monthlySalary

2500.00
1000.00
1500.00
750.00
2000.00
7500.00

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 7: Comparison Search Condition
22

List all staff with a salary greater than 10,000.


SELECT staffNo, fName, lName, position, salary
FROM Staff Result
WHERE salary > 10000;

Staff

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 8: Compound Comparison Search Condition
23

List addresses of all branch offices in London or Glasgow.


SELECT *
FROM Branch
WHERE city = ‘London’ OR city = ‘Glasgow’;

Branch Result

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 9: Range Search Condition
24

List all staff with a salary between 20,000 and 30,000.


SELECT staffNo, fName, lName, position, salary
FROM Staff
WHERE salary BETWEEN 20000 AND 30000;
BETWEEN test includes the endpoints of range.
Staff Result

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 10: Range Search Condition
25

 Also a negated version NOT BETWEEN.


 BETWEEN does not add much to SQL’s expressive
power. Could also write:

SELECT staffNo, fName, lName, position, salary


FROM Staff
WHERE salary>=20000 AND salary <= 30000;

 Useful, though, for a range of values.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 11: Set Membership
26

List all managers and supervisors.

SELECT staffNo, fName, lName, position


FROM Staff
WHERE position IN (‘Manager’, ‘Supervisor’);

Staff Result

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 12: Set Membership
27

 There is a negated version (NOT IN).


 IN does not add much to SQL’s expressive power.
Could have expressed this as:

SELECT staffNo, fName, lName, position


FROM Staff
WHERE position=‘Manager’ OR position=‘Supervisor’;

 IN is more efficient when set contains many values.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 13: Pattern Matching
28

 Find all owners with the string ‘Glasgow’ in their


address.
SELECT ownerNo, fName, lName, address, telNo
FROM PrivateOwner
WHERE address LIKE ‘%Glasgow%’;

Result

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 14: Pattern Matching
29

 SQL has two special pattern matching symbols:


 %: sequence of zero or more characters;

 _ (underscore): any single character.

 LIKE ‘%Glasgow%’ means a sequence of characters of


any length containing ‘Glasgow’.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 15: NULL Search Condition
30

 List details of all viewings on property PG4 where a comment has


not been supplied.

 There are 2 viewings for property PG4, one with and one without a
comment.

 Have to test for null explicitly using special keyword IS NULL.

SELECT clientNo, viewDate


FROM Viewing
WHERE propertyNo = ‘PG4’ AND comment IS NULL;

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

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 16: Single Column Ordering
31

 List salaries for all staff, arranged in descending order of


salary.

SELECT staffNo, fName, lName, salary


FROM Staff
ORDER BY salary DESC;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 17: Single Column Ordering
32

 Produce abbreviated list of properties in order of


property type.

SELECT propertyNo, type, rooms, rent


FROM PropertyForRent
ORDER BY type;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 18: Multiple Column Ordering
33

 Four flats in this list - as no minor sort key specified,


system arranges these rows in any order it chooses.
 To arrange in order of rooms, specify minor order:

SELECT propertyNo, type, rooms, rent


FROM PropertyForRent
ORDER BY type, rooms DESC;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Kuis 1
34

1. Tampilkan id dari pada staff berikut gaji perbulannya, dengan syarat,


gaji perbulan staff tersebut lebih besar dari 1000 pound. Kemudian
urutkan berdasarkan gaji yang terbesar.

2. Tampilkan ID property yang memiliki kamar lebih atau sama dengan


4 tetapi biaya sewanya lebih kecil dari 500 pound.

3. Tampilkan info lengkap private owner yang beralamat di Glasgow


tetapi first namenya tidak berawalan “T”.

4. Tampilkan first name dan last name dari semua staff yang berada
pada branch B005 atau B007.

5. Tampilkan kode properti dan kodeposnya, dimana pada awal


kodepos tsb terdapat string “G12”.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


SELECT Statement - Aggregates
35

 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.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


SELECT Statement - Aggregates
36

 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.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


SELECT Statement - Aggregates
37

 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.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


SELECT Statement - Aggregates
38

 Aggregate functions can be used only in SELECT list and in


HAVING clause; CANNOT be used in WHERE clause!

 If SELECT list includes an aggregate function and there is


no GROUP BY clause, SELECT list cannot reference a
column without an aggregate function.

 For example, the following staffNo is illegal:

SELECT staffNo, COUNT(salary)


FROM Staff;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 19: Use of COUNT(*)
39

 How many properties cost more


than £350 per month to rent?

 SELECT COUNT(*) AS myCount


FROM PropertyForRent
WHERE rent > 350;

Dr. Said Mirza Pahlevi


Example 20: Use of COUNT(DISTINCT)
40

How many different properties viewed in


May ‘04?

SELECT COUNT(DISTINCT propertyNo)


AS myCount
FROM Viewing
WHERE viewDate
BETWEEN ‘1-May-01’ AND
‘31-May-01’;

Dr. Said Mirza Pahlevi


Example 21: Use of COUNT and SUM
41

Find number of Managers and


sum of their salaries.

SELECT COUNT(staffNo) AS
myCount,
SUM(salary) AS mySum
FROM Staff
WHERE position = ‘Manager’;

Dr. Said Mirza Pahlevi


Example 22: Use of MIN, MAX, AVG
42

Find minimum, maximum,


and average staff salary.

SELECT MIN(salary) AS myMin,


MAX(salary) AS myMax,
AVG(salary) AS myAvg
FROM Staff;

Dr. Said Mirza Pahlevi


SELECT Statement - Grouping
43

 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.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


SELECT Statement - Grouping
44

 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.
Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)
Example 23: Use of GROUP BY
45

 Find number of staff in each branch and their total


salaries.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 23: Use of GROUP BY
46

 Find number of staff in each branch and their total


salaries.

SELECT branchNo, COUNT(staffNo) AS myCount,


SUM(salary) AS mySum
FROM Staff
GROUP BY branchNo
ORDER BY branchNo;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 24: Use of HAVING
47

 For each branch with more than 1 member of staff, find


number of staff in each branch and sum of their salaries.

SELECT branchNo,
COUNT(staffNo) AS myCount,
SUM(salary) AS mySum
FROM Staff
GROUP BY branchNo
HAVING COUNT(staffNo) > 1
ORDER BY branchNo;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


48

 Untuk setiap tipe properti tampilkan type, jumlah


properti, total biaya sewa dan total jumlah kamar
properti tersebut. Urutkan hasilnya berdasarkan tipe
properti.
 Tampilkan id dari properti owner beserta total jumlah
properti yang dimilikinya dan total jumlah kamar dari
properti-properti tersebut, dengan syarat jumlah
properti yang dimiliki tersebut minimum 2 properti
dan total jumlah kamar adalah lebih besar dari 8
kamar.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Latihan 1
49

 Untuk setiap tipe properti tampilkan type, jumlah properti,


total biaya sewa dan total jumlah kamar properti tersebut.
Urutkan hasilnya berdasarkan tipe properti.

SELECT type,
COUNT(propertyNo) AS tProperty,
SUM(rent) AS tRent,
SUM(rooms) AS tRoom
FROM propertyForRent
GROUP BY type
ORDER BY type;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Latihan 2
50

 Tampilkan id dari properti owner beserta total jumlah


properti yang dimilikinya dan total jumlah kamar dari
properti-properti tersebut, dengan syarat jumlah properti
yang dimiliki tersebut minimum 2 properti dan total
jumlah kamar adalah lebih besar dari 8 kamar.

SELECT ownerNo,
COUNT(propertyNo) AS tProperty,
SUM(rooms) AS tRoom,
FROM propertyForRent
GROUP BY ownerNo
HAVING COUNT(propertyNo) >= 2 AND SUM(rooms)>8;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Subqueries
51

 Some SQL statements can have a SELECT embedded


within them.

 A subselect can be used in SELECT, 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.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 25: Subquery with Equality
52

 List staff who work in branch at ‘163 Main St’.

SELECT staffNo, fName, lName, position


FROM Staff
WHERE branchNo =
(SELECT branchNo
FROM Branch
WHERE street = ‘163 Main St’);

The result of the subquery must be one tuple.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 26: Subquery with Equality
53

 Inner SELECT finds branch number for branch at ‘163


Main St’ (‘B003’).
 Outer SELECT then retrieves details of all staff who
work at this branch.
 Outer SELECT then becomes:

SELECT staffNo, fName, lName, position


FROM Staff
WHERE branchNo = ‘B003’;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 28: Subquery with Aggregate
54

 List all staff whose salary is greater than the average


salary, and show by how much.

SELECT staffNo, fName, lName, position,


salary – (SELECT AVG(salary) FROM Staff) As SalDiff
FROM Staff
WHERE salary >
(SELECT AVG(salary)
FROM Staff);

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 29: Subquery with Aggregate
55

 Cannot write ‘WHERE salary > AVG(salary)’


 Instead, use subquery to find average salary (17000),
and then use outer SELECT to find those staff with
salary greater than this:

SELECT staffNo, fName, lName, position,


salary – 17000 As salDiff
FROM Staff
WHERE salary > 17000;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Subquery Rules
56

 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 in a subquery refer to table


name in FROM clause of the subquery. Can refer to a
table in FROM using an alias.
Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)
Subquery Rules
57

 When subquery is an operand in a comparison,


subquery must appear on right-hand side.

 The following is invalid

SELECT staffNo, fName, lName, position, salary


FROM Staff
WHERE
(SELECT AVG(salary)
FROM Staff) < salary;

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Example 30: Nested subquery: use of IN
58

 List properties handled by staff at ‘163 Main St’.

SELECT propertyNo, street, city, postcode, type, rooms, rent


FROM PropertyForRent
WHERE staffNo IN
(SELECT staffNo
FROM Staff
WHERE branchNo =
(SELECT branchNo
FROM Branch
WHERE street = ‘163 Main St’));

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


Latihan
59

 Tampilkan detail client yang melihat properti yang


dikelola oleh seorang manager yang bekerja di branch
yang berada di kota London.
 Tampilkan detail client yang melihat properti yang
dikelola oleh seorang staff yang mengelola lebih dari
satu properti dan client melihat pada bulan Mei.

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


60

 List all double or family rooms with a price below £40.00 per
night, in ascending order of price.
 List the bookings for which no dateTo has been specified.
 What is the average price of a room?
 What is the total revenue per night from all double rooms?
 List the details of all rooms at the Grosvenor Hotel, including the
name of the guest staying in the room, if the room is occupied.
 What is the total income from bookings for the Grosvenor Hotel
today?
 What is the average number of bookings for each hotel in
August?
 What is the most commonly booked room type for each hotel in
London?

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)


61

Dr. Said Mirza Pahlevi Sekolah Tinggi Ilmu Statistik (STIS)

You might also like