Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Lecture 3 - Structural Query Language (SQL) - Part I PDF

The document discusses Structured Query Language (SQL) and its use for querying and manipulating data in relational databases. It covers key SQL statements like SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY. It also discusses SQL aggregate functions, joining tables, and using parameters in SQL statements. The objective is for readers to be able to use SQL to query data from tables, use aggregate functions, and design SQL statements with parameters.

Uploaded by

Chia Wei Han
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Lecture 3 - Structural Query Language (SQL) - Part I PDF

The document discusses Structured Query Language (SQL) and its use for querying and manipulating data in relational databases. It covers key SQL statements like SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY. It also discusses SQL aggregate functions, joining tables, and using parameters in SQL statements. The objective is for readers to be able to use SQL to query data from tables, use aggregate functions, and design SQL statements with parameters.

Uploaded by

Chia Wei Han
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Topic 3

Database Systems

Unit 3 :
Structural Query
Language
(SQL) Part 1

IT1768 Database Systems

Unit 3 :
Structural Query Language (SQL)

Topic 3

Objective :
At the end of this unit, you should be able to:
Use SQL to query data from tables
Use SQL statements with aggregate
functions
Design SQL statement with parameters
section

IT1768 Database Systems

Topic 3

Content
SQL statements; including SELECT, FROM,
WHERE, GROUP BY, HAVING and ORDER BY.
SQL Aggregate Functions; including COUNT (),
AVG (), SUM(), MAX(), MIN(), CONCAT () etc
SQL statements beginning with a
PARAMETERS keyword followed by a list of
parameter identifier(s) to add a Parameters
section to the SQL statement.
IT1768 Database Systems

Topic 3

Structural Query Language (SQL)


Background

SQL is a Structured Query Language for creating


and manipulating data in relational databases.
SQL is used by many commercial DBMS products
with minor syntax differences: Oracle, SQL/DS,
Sysbase & MS Access.
It is a non-procedural language.
What is SQL

It is a comprehensive Database Language


It is a standard language for accessing and
manipulating databases
IT1768 Database Systems

Topic 3

Overview of SQL
Data Definition Language (DDL)
CREATE, DROP and ALTER of relational tables
Data control language (DCL)
GRANT and REVOKE

Data Manipulation Language (DML)


SELECT, INSERT, UPDATE, and DELETE of tuples

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. e.g. SELECT, FROM, WHERE..
User-defined words are made up by user and represent names of
various database objects such as relations, columns, views.
IT1768 Database Systems

Topic 3

Applications of SQL
What can

SQL do ?

execute queries against a database


retrieve data from a database
Insert, update, delete records in a database
create new databases
create new tables in a database
create stored procedures in a database
can create views in a database
set permissions on tables, procedures, and views

IT1768 Database Systems

Topic 3

Syntax of SQL statement


Syntax :

SELECT
[DISTINCT] column_list
FROM
table_list
WHERE [condition]
GROUP BY [column_list]
HAVING [condition]
ORDER BY [column_list [DESC]]
Only SELECT & FROM are mandatory in a SQL statement
Other clauses are optional, depending on the conditions for use.
Order of the clauses cannot be changed

IT1768 Database Systems

Topic 3

Syntax of SQL Statement


SELECT

Specifies which columns are to appear in


output ( Projection in Relational Algebra)

FROM
WHERE
GROUP BY

Specifies table(s) to be used

HAVING
ORDER BY

Filters groups subject to some conditions

IT1768 Database Systems

Filters rows ( Selection in Relational Algebra)

Forms groups of rows with same column


value
Specifies the order of the rows inthe output

Topic 3

SELECTFROM Statement
The SELECT Statement
SELECT is used to retrieve and display data from one or
more tables
FROM Specifies table(s) to be used
Customer
CustNum Fname

SQL Syntax:
SELECT [column_list]
FROM [table_list]

SELECT CustNum
FROM Customer

IT1768 Database Systems

Lname

Address

zipcode

C-01

Hillary

Clinton

1 Street 1

010-12-345

C-02

John

Smith

2 Street 10

022-23-561

SELECT CustNum, Fname, Lname


FROM Customer

Compare with : CustNum, Fname, Lname

(Customer)

Topic 3

SELECT .. FROM clause


Customer
CustNum Fname Lname

Address

Zipcode

C-01

Hillary

Clinton

1 Street 1

010-12-345

C-02

John

Smith

2 Street 10

022-23-561

Retrieve full details of all customers


- SELECT *
FROM Customer;
- SELECT CustNum, Fname, Lname, Address, Zipcode
FROM Customer;

Retrieve specific columns of all customers


- SELECT Fname, Lname, Zipcode
FROM Customer;
- SELECT Zipcode, Fname, Lname
FROM Customer;

IT1768 Database Systems

10

Topic 3

SELECT clause with Distinct


Example 1 :
Table Name:
StudMod

SELECT Module
FROM StudMod

Example 2 :
SELECT Distinct Module
FROM StudMod

SID

Module

Module

Module

S01

Maths

Maths

Maths

S02

Accounting

Accounting

Accounting

S03

Physics

Physics

Physics

S04

Physics

Physics

Chemistry

S05

Accounting

Accounting

S06

Chemistry

Chemistry
Note :
Repeated rows

IT1768 Database Systems

Note : DISTINCT
Removed
duplicated rows

11

Topic 3

SELECT clause with Alias


Syntax :
SELECT [column_list] AS [Alias name]
FROM [table_list]

A calculated (derived) columns in the column_list needs an


Alias as field name:

i) Arithmetic operations on the base table columns :


Select Prod_num, (Unit_price*1.1) As Newprice
From Product ;
Select Order_num, (Ship_date Order_date) As Span
From Orders ;

Span is an alias to the


calculated field

IT1768 Database Systems

12

Topic 3

SELECT clause with Functions( )

Syntax :
SELECT [column_list], [SQL function]
FROM [table_list]

ii) ROUND function on the columns :


- Select Prod_num, ROUND(unit_price, 0)
From Product ;
iii) Concatenation operations on the base table columns :
- Supported in MYSQL, Oracle only.
- In SQL Server, MS Access, use Fname + + Lname

- Select CONCAT(Fname, Lname) As Cust_name


From Customer ;
Alias name

Reference:
http://www.1keydata.com/sql/sql-concatenate.html
http://www.w3schools.com/sql/

IT1768 Database Systems

13

Topic 3

SQL Aggregate Functions

11

In MS Access, use:

SELECT (Fname + + Lname) as EmpName


FROM EMPLOYEE
WHERE Designation=Mgr

Example 6 :
SELECT
CONCAT( Fname, , Lname ) AS EmpName
FROM
EMPLOYEE
WHERE
Designation=Mgr
Fname Lname Designation
Aaron

Ang

Mgr

EmpName

Bruce

Lee

Accountant

Aaron Ang

Charlie Chan

QA

Eileen Er

Don

Ho

Designer

Eileen

Er

Mgr

IT1768 Database Systems

14

Topic 3

SELECT clause with Function( )

SELECT [column_list] [SQL function]


FROM [table_list]

iv) Substr function on the columns :


- Select SUBSTR(zipcode,1,3)

From Customer ;

- Supported in MYSQL, Oracle only.


In SQL Server, use SUBSTRING()
- In MS Access, use LEFT(zipcode, 3)

Customer
custID area

zipcode

zipcode

C-01

010-123

010

C-02

012-398

012

C-03

024-629

024
Reference:

IT1768 Database Systems

http://www.sql-ref.com/

15

Topic 3

WHERE condition clause

Syntax :
WHERE [column_name] <operator> [value(s)] ;

Row Selection, using the WHERE clause:


Where restricts the rows to be retrieved based on the
condition(s) specified on the base table columns:
Select Prod_num, Unit_price
From Product
Where Unit_price > 500 ;
Compare with

s Unit_price > 500 (Product)

Conditions can also be specified on derived columns:


Select Order_num, (Ship_date Order_date)
From Orders
Where (Ship_date Order_date) > 14 ;

IT1768 Database Systems

16

Topic 3

WHERE condition clause

5 basic search conditions that can be used in the


WHERE clause :
1) Comparison (=, <, >, <=, >=, <>)
WHERE Salary > 5000
WHERE State_code <> CA

2) Range (BETWEEN, NOT BETWEEN)


WHERE Salary BETWEEN 5000 AND 10000
WHERE Order_date BETWEEN 01-jul-2008 AND
31-jul-2008

3) Pattern match (LIKE) with wildcards (% _)


WHERE Address LIKE A%
WHERE State_code LIKE %A
WHERE State_code LIKE %m%
IT1768 Database Systems

or LIKE *m* in MS Access


17

Topic 3

WHERE condition clause

4) Set membership (IN, NOT IN)


WHERE Position IN (Manager, Deputy Manager)
(Note: Compare with : Where Position = Manager)

5) Null (IS NULL, IS NOT NULL)


WHERE Ship_instruct IS NULL
(Note: Compare with : Where Ship_instruct = , any difference ?)

In addition, two or more conditions can be combined with


AND / OR, for examples:
WHERE Salary >= 3000 AND Salary <= 5000
WHERE Salary > 5000 AND Position = Manager
WHERE Order_date IS NULL OR Ship_date IS NULL
WHERE Salary > 5000 AND Gender = Male OR Position = Manager
IT1768 Database Systems

18

Topic 3

WHERE condition clause

Example 1:
SELECT SName, Age
FROM
STUDENT
WHERE Age BETWEEN 15 AND 19
SID

SName

Major

Age

100

Jones

Accounting

21

150

Parks

Math

19

200

Baker

History

16

250

Glass

History

18

300

Andy

Accounting

17

IT1768 Database Systems

SName

Age

Parks

19

Baker

16

Glass

18

Andy

17

19

Topic 3

WHERE condition clause

http://www.techonthenet.com/sql/like.php

Example 2:
SELECT SName, Age
FROM
STUDENT
WHERE SName LIKE %a%
SID

SName

Major

Age

100

Jones

Accounting

21

150

Parks

Math

19

200

Baker

History

16

250

Glass

History

18

300

Andy

Accounting

17

or LIKE *a* in MS Access

SName

Age

Parks

19

Baker

16

Glass

18
a*

The % sign functions as a wildcard. It signifies any character. Thus, a%" means all strings
that begin with the alphabet a. %s" means all strings that end with the alphabet s.
IT1768 Database Systems

*s

20

Topic 3

WHERE condition clause

Compare with:
SELECT SName, Age
FROM STUDENT
WHERE Major = Math ;

Example 3:
SELECT SName, Age
FROM
STUDENT
WHERE Major IN (Math, Accounting)
SID

SName

Major

Age

100

Jones

Accounting

21

150

Parks

Math

19

200

Baker

History

16

250

Glass

History

18

300

Andy

Accounting

17

SName

Age

Jones

19

Parks

16

Andy

18

The IN operator in the Where clause can accommodate more than one selected values;
like the case above, it accommodates Math and Accounting in the selection. In
21
contrast,
the = operator can accommodate only one value in the selection.
IT1768 Database
Systems

Topic 3

ORDER BY condition clause

ORDER BY is used to sort the rows in the query result, in


ascending (asc) or descending (desc) order of a column value
or a combination of columns

Syntax :
Order by column_list [desc]
where column_list is:
a column name in the select clause; or
a column number

Example 1:
SELECT Ename
FROM EMPLOYEE
ORDER BY Ename Desc

(e.g. 1 represents the first element in the select clause, 2 represents


the second element, and so on)

Order by 1, 2 desc
Order by 1 desc, 2
IT1768 Database Systems

Example 2:
SELECT Ename, Salary
FROM EMPLOYEE
ORDER BY 2 Desc

22

Topic 3

ORDER BY condition clause

Examples :
Sort in descending order of ZIPCODE :
SELECT *
FROM CUSTOMER
ORDER BY ZIPCODE DESC ;
Sort in ascending order of LNAME
SELECT ZIPCODE, LNAME, FNAME
FROM CUSTOMER
(Or ORDER BY 2 Asc)
ORDER BY 2 ;

Note: If unspecified, it is
defaulted as Asc

Sort in ascending order of SUPPL_CODE, followed by descending


order of UNIT_PRICE
SELECT *
FROM PRODUCT
ORDER BY SUPPL_CODE, UNIT_PRICE DESC ;
IT1768 Database Systems

23

Topic 3

ORDER BY condition clause

Example 1 :
SELECT
FROM
WHERE
ORDER BY

SName, Major, Age


STUDENT
Major = History
Or ORDER BY SName ASC
SName

SID

SName

Major

Age

SName

Major

Age

100

Jones

Accounting

21

Baker

History

16

150

Parks

Math

19

Glass

History

18

200

Baker

History

16

250

Glass

History

18

300

Andy

Accounting

17

IT1768 Database Systems

24

Topic 3

ORDER BY condition clause

Sorting can be ascending (ASC) or descending (DESC)

Example 2 :
SELECT
FROM
WHERE
ORDER BY

SName, Major, Age


STUDENT
Major IN (History, Accounting)
Major ASC, Age DESC

SID

SName

Major

Age

SName

Major

Age

100

Jones

Accounting

21

Jones

Accounting

21

150

Parks

Math

19

Andy

Accounting

17

200

Baker

History

16

Glass

History

18

250

Glass

History

18

Baker

History

16

300

Andy

Accounting

17

IT1768 Database Systems

25

Topic 3

Multiple Tables Queries

Multiple tables query is used to obtain information


from different tables (e.g. customer table, order table).
It could be accomplished by using either a
subquery or a Join.
Example of using a Join (List all the orders made by
customers with a Join) :
Select custName, orderNum
From Customer As c, Orders As o
This is a Join on
Where c.custNum = o.custNum (Note:
common attribute custNum)
custNum from
Customer table

IT1768 Database Systems

custNum from
Orders table
26

Topic 3

Multiple Tables Queries

Multiple

table query :
- Select CustName, OrderNo, OrderDate, PaidDate
From
Customer As c, Orders As o
Where c.custNum = o.custNo
o
o

Include multiple table(s) in the FROM clause


Include a WHERE clause to specify the column(s) to join,
these columns must have compatible data types. (e.g.
custNum vs custNo)
Whenever there is ambiguity in the source of the
columns (same column name used in multiple tables), it
may use an alias for the table to qualify the column
name.

IT1768 Database Systems

27

Reference 1: http://sqlzoo.net/

Reference 2: http://www.sql-tutorial.net/

Multiple Tables Queries


Customer
CustNum

Topic 3

(Joining tables) 3

Orders
CustName

CustNo

OrderNo

OrderDate

1000

1000

01/03/2008

1001

1000

02/03/2008

1002

1001

03/03/2008

1003

1002

04/03/2008

1004

1004

05/03/2008

PaidDate
28/03/2008
30/03/2008

WHERE c.CustNum = o.CustNo


c.CustNum

CustName

o.CustNo

OrderNo

OrderDate

1000

1000

01/03/2008

1000

1000

02/03/2008

1001

1001

03/03/2008

1002

1002

04/03/2008

1004

1004

05/03/2008

IT1768 Database Systems

(The result)

PaidDate
28/03/2008
30/03/2008

28

Topic 3

SQL Aggregate Functions

5 aggregate functions can be applied on


column values :
COUNT(), SUM(), AVG(), MIN(), MAX()
o Each function operates on a single column of a table
and return a single value. e.g.
SELECT SUM(total_price) As TotalPrice
FROM Order_detail ;
Note :
o Use functions with SELECT, HAVING clauses only.
o Need to assign alias as field name to the column generated by the
function.
Reference:
IT1768 Database Systems

http://www.w3schools.com/sql/sql_functions.asp

29

Topic 3

SQL Aggregate Functions


Function Format
COUNT

Returns

COUNT(*)

Counts all rows of a table, regardless of


whether nulls or duplicate values occur.

COUNT(DISTINCT
column-name)

No. of unique values in the specified


column.

AVG

AVG (column-name)

Average of values in a specified numeric


column.

SUM

SUM (column-name) Sum of values in a specified numeric


column.

MIN

MIN (column-name)

MAX

MAX (column-name) Highest value in the specified column.

ABS

ABS(column-name)

IT1768 Database Systems

Lowest value in the specified column.

Absolute value in the specified column.


30

Topic 3

SQL Aggregate Functions


Example 1 :
SELECT
FROM

COUNT()
STUDENT

SID

SName

Major

Age

100

Jones

Accounting

21

150

Parks

Math

19

200

Baker

History

16

250

Glass

History

18

300

Andy

Accounting

17

IT1768 Database Systems

31

Topic 3

SQL Aggregate Functions

Example 2 :

SELECT
FROM

COUNT(Major)
STUDENT

Will the following SQL query works ?


SELECT
FROM

5
Will it return 5 ?
At least it does not works in MS Access.

COUNT(DISTINCT Major)
STUDENT

How about the following SQL query in MS Access ?


SELECT
FROM
IT1768 Database Systems

COUNT(*)
(Select DISTINCT Major From STUDENT);

3
32

Topic 3

SQL Aggregate Functions


WARNING 1 :
SELECT
SName, COUNT( )
FROM
STUDENT

Count() is Not allowed !!!


Unless use with
GROUP BY

GROUP BY SName
WARNING 2 :
Typically, built-in functions cannot be used as part of
the WHERE clause
Built-in functions can be applied to groups of rows
within a table
For example, students can be grouped by Major,
meaning one group will be formed for each value of
Major
IT1768 Database Systems

33

Topic 3

SQL Aggregate Functions

The SQL COUNT aggregate function is used to count the number


of rows in a database table

SELECT
Major, COUNT( ) As SNumber
FROM
STUDENT
GROUP BY Major
SID

SName

Major

Age

100

Jones

Accounting

21

150

Parks

Math

19

200

Baker

History

16

250

Glass

History

18

300

Andy

Accounting

17

IT1768 Database Systems

Major

SNumber

Accounting

History

Math

34

Topic 3

SQL Aggregate Functions

Example:
SELECT
FROM
GROUP BY
HAVING

Major, COUNT( ) As SNumber


STUDENT
Major
COUNT (*) > 1

SID

SName

Major

Age

100

Jones

Accounting

21

150

Parks

Math

19

200

Baker

History

16

250

Glass

History

18

300

Andy

Accounting

17

IT1768 Database Systems

Major

SNumber

Accounting

History

35

Topic 3

SQL Aggregate Functions

The SQL AVG aggregate function selects the average value for
certain table column.

SELECT
FROM
WHERE
GROUP BY
HAVING

Major, AVG( Age ) As Avg_Age


STUDENT
SID Between 200 AND 250
Major
COUNT (*) > 1

SID

SName

Major

Age

100

Jones

Accounting

21

150

Parks

Math

19

200

Baker

History

16

250

Glass

History

18

300

Andy

Accounting

17

IT1768 Database Systems

Major
History

AVG _Age)
17

The average 16 and 18 is 17


36

Topic 3

SQL Aggregate Functions

The SQL MAX/MIN aggregate function allows us to select the


highest (maximum)/ lowest (minimum) value for a certain column.

SELECT Dep, MAX( Salary ) AS Highest_Sal


FROM EMPLOYEE
GROUP BY Dep
Dep

SName

Salary

Age

D1

Jones

2000

21

D1

Parks

4000

19

D1

Baker

3000

16

D2

Glass

5000

18

D2

Andy

3500

17

IT1768 Database Systems

Dep

Highest_Sal

D1

4000

D2

5000

Highest_Sal shows the highest


salary in the depatment
37

Topic 3

SQL Aggregate Functions

10

The SQL SUM aggregate function allows selecting the total for a
numeric column.

SELECT Dep, SUM( Salary ) AS SUM_Pay


FROM EMPLOYEE
GROUP BY Dep
Dep

SName

Salary

Age

D1

Jones

2000

21

D1

Parks

4000

19

D1

Baker

3000

16

D2

Glass

5000

18

D2

Andy

3500

17

IT1768 Database Systems

Dep

SUM_Pay

D1

9000

D2

8500

Sum_Pay shows the aggregate


salary in the department
38

Topic 3

SQL with Parameters Section

Example 1:
PARAMETERS *Choose Employees Department:+ Text ;
SELECT
Ename, Department
FROM
EMPLOYEES
WHERE
Department= *Choose Employees Department:+ ;
EID

Ename

Salary Department

E-01

Robert

2,500

QA

E-02

Kelly

3,500

Accounting

E-03

Mohd

4,200

Design

E-04

Chandra

6,500

Production

E-05

Jasmine

3,800

Sales

IT1768 Database Systems

Ename

Department

Robert

QA
39

Topic 3

SQL View with Parameters Section

IT1768 Database Systems

40

Topic 3

SQL with Parameters Section

Example 2:
PARAMETERS *Indicate Employees Salary :+ Number ;
SELECT
Ename, Salary
FROM
EMPLOYEES
WHERE
Salary= *Indicate Employees Salary :+ ;
EID

Ename

Salary Department

E-01

Robert

2,500

QA

E-02

Kelly

3,500

Accounting

E-03

Mohd

4,200

Design

E-04

Chandra

6,500

Production

E-05

Jasmine

3,800

Sales

IT1768 Database Systems

Ename

Salary

Chandra

6,500
41

Topic 3

Summary

SQL Syntax
SELECT .. FROM are mandatory clauses in SQL
statements
WHERE, GROUP BY, HAVING, ORDER BY are optional
clauses in SQL statements.

Aggregate functions in SQL statements.


Parameters section in SQL statements.

IT1768 Database Systems

42

Topic 3

EXERCISE REVIEW 1
Match the function of the SELECT statement to the correct
descriptions.
HAVING

Specifies the order of the


output.

FROM

Filters the rows subject to


some condition

ORDER BY

Forms groups of rows with


the same column value.

SELECT

Specifies the table/s


to be used.

GROUP BY

Specifies which columns are to


appear in the output.

WHERE

the groups subject to


some condition.

IT1768 Database Systems

43

Topic 3

Quiz
Give an example of using GROUP BY clause.
When do we need to use the HAVING clause?
Which clause shall be used if the result displayed
is arranged in descending?
Arrange in order in SQL statement using Having,
Group by , Order By, Select, Where, From.
IT1768 Database Systems

44

Topic 3

EXERCISE REVIEW 2
From Table : SalesInfor. Write a SQL statement to display the
following:
a) Sales between $2,000 and $3,000
b) All Sales in descending order
c) Total sales for each branch
d) The branch with sales over $4,000

IT1768 Database Systems

Branch

Sales

Promoter

Orchard

3500

Aaron

Bedok

1500

Bruce

Orchard

2000

Charlie

JurongP

800

Don

NorthP

1750

Eileen

JurongP

3000

Francis
45

Topic 3

EXERCISE REVIEW 3
From Table : Sales. Write a SQL statement to display
the following:
a) All customers and their sub-total sum
b) The highest transaction
ItemNo

Unit_price

Qty

Customer

250

Aaron

500

Bruce

2000

Charlie

800

Don

750

Eileen

3000

Francis

IT1768 Database Systems

46

Topic 3

EXERCISE REVIEW 1

(Solution)

Match the function of the SELECT statement to the correct


descriptions.
HAVING

Specifies the order of the


output.

FROM

Filters the rows subject to


some condition

ORDER BY

Forms groups of rows with


the same column value.

SELECT

Specifies the table/s


to be used.

GROUP BY

Specifies which columns are to


appear in the output.

WHERE

the groups subject to


some condition.

IT1768 Database Systems

47

Topic 3

EXERCISE REVIEW 2
a)
b)
c)
d)

Sales between $2,000 and $3,000


All Sales at branch in descending order
Total sales for each branch
The branch with sales over $4,000

a) Solution

Branch

Sales

Promoter

Orchard

3500

Aaron

Orchard

2000

Charlie

SELECT Branch, Sales


FROM SalesInfor
ORDER BY Sales DESC
IT1768 Database Systems

Branch

Sales

Promoter

Orchard

3500

Aaron

Bedok

1500

Bruce

Orchard

2000

Charlie

JurongP

800

Don

NorthP

1750

Eileen

JurongP

3000

Francis

c) Solution

JurongP 3000 Francis


SELECT *
FROM SalesInfor
WHERE Sales Between 2000 and 3000

b) Solution

(Solution)

Branch

Sales

Orchard

3500

JurongP

3000

Orchard

2000

NorthP

1750

Bedok

1500

JurongP

800

SELECT Branch, Sum(Sales) As Sub-total


Branch
Sub-total
FROM SalesInfor
Orchard
5500
GROUP BY Branch
Bedok
1500

d) Solution

JurongP

3800

NorthP

1750

SELECT Branch, Sum(Sales)


FROM SalesInfor
Branch
GROUP BY Branch
Orchard
HAVING Sum(Sales) > 4000

Sub-total
5500
48

Topic 3

EXERCISE REVIEW 3

(Solution)

a) All customers and their sub-total sum


b) The highest transaction

ItemNo

a) Solution

Unit_price

Qty

Customer

250

Aaron

500

Bruce

2000

Charlie

800

Don

750

Eileen

3000

Francis

SELECT
Customer, Unit_price * Qty As Sub-total
FROM
Sales
GROUP BY Customer
b) Solution
SELECT MAX (Unit_price * Qty ) As Highest
FROM
Sales
For b), how to display the customer with the highest transaction ?
IT1768 Database Systems

49

Topic 3

Quiz

(Solution)

1) Give an example of using GROUP BY clause.


SELECT sex, count(*)
FROM student
GROUP BY sex;

2) When do we need to use the HAVING clause?


When we need to filter the result of a statement which
involves the GROUP BY clause.
E.g. SELECT sex, count(*)
FROM student
GROUP BY sex
HAVING count(*) > 1;

3) Which clause shall be used if the result


displayed is arrange in descending
ORDER BY
E.g. SELECT *
FROM student
ORDER BY adminNo DESC;
IT1768 Database Systems

4)
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY

50

You might also like