0% found this document useful (0 votes)
85 views94 pages

Database Application SSK 3408: Data Manipulation Language

The document discusses SQL data manipulation language (DML) commands. It describes how to insert, update, and delete data from tables using INSERT, UPDATE, DELETE statements. It also covers SELECT statements to retrieve data including basic syntax, expressions, null values, column aliases, concatenation, and limiting rows with WHERE clauses.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views94 pages

Database Application SSK 3408: Data Manipulation Language

The document discusses SQL data manipulation language (DML) commands. It describes how to insert, update, and delete data from tables using INSERT, UPDATE, DELETE statements. It also covers SELECT statements to retrieve data including basic syntax, expressions, null values, column aliases, concatenation, and limiting rows with WHERE clauses.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 94

Database Application SSK 3408

CHAPTER 3 DATA MANIPULATION LANGUAGE

Learning Objectives

Define key terms: join, equijoin, self-join, nonequijoin, natural join, outer join, set operators and subquery. Applying the DML command to insert, update and delete data from table. Write single and multiple table queries using SQL commands Write queries using subqueries.

Data Manipulation Language (DML)


Used to create, modify and retrieve data
Insert Select Update Delete

DML Adding Data


Use the Insert keyword and specify:
table

name field names - optional values for each field


INSERT INTO customer VALUES(Teplow,MA,23445.67);

OR
INSERT INTO customer (last_name, state_cd, sales) VALUES (Teplow ,MA,23445.67);

DML Update Data


Use the Update and Set keywords and specify:
table

name field name(s) where clause (optional)


UPDATE inventory SET price = price*1.05; UPDATE inventory SET price = price*1.05 WHERE product_id = 'P103';

DML Remove Data


Use the Delete From keywords and specify:
table

name where clause (optional)


DELETE FROM customer; DELETE FROM customer WHERE sales < 10000;

DML Select Data

Select statement retrieves information from the databases. Capabilities of SQL Select Statements:
Selectio n

Projection

Join

Table 1

Table 2

Table 1

Table 2

Basic Select Statement

SELECT identifies the columns to be displayed FROM identifies the table containing those columns.

SELECT *|{[DISTINCT] column_name | expression [alias],..} FROM table_name;


DISTINCT suppresses duplicates * select all columns alias gives the selected columns different headings FROM identifies the table containing those

Expressions

Create expression with number and date by using arithmetic operators (i.e. +, -, *, /). If an expression contains more than one operator, * and / are evaluated first. If operators in an expression are of the same priority, evaluation is done from left to right.
SALARY 1000 1200 1500 SALARY* 12 12000 14400 18000

LAST_NAME SELECT last_name, salary, salary*12 Siti Razilah FROM employee; Musa Ahmad Martin Luke

Expressions ..cont.
SELECT last_name, salary, 12*salary+100 FROM employee;
LAST_NAME Siti Razilah Musa Ahmad Martin Luke SALAR Y 1000 1200 1500 SALARY*1 2 12100 14500 18100

SELECT last_name, salary, 12*(salary+100) FROM employee;

LAST_NAME Siti Razilah Musa Ahmad Martin Luke

SALAR Y 1000 1200 1500

SALARY*1 2 13200 15600 19200

Defining a Null Value

Null is a value that is unavailable, unassigned, unknown, or inapplicable. Null is not the same as zero or a blank space.

SELECT last_name, salary, commission FROM LAST_NAME employee; SALARY COMMISSIO


N Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff 1000 1200 1500 1800 1230 2500 (null) 0.2 0.6 0.3 (null) 0.8

Defining a Null Value ..cont.


SELECT last_name, salary, commission, salary*commission FROM employee;
LAST_NAME Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff SALARY 1000 1200 1500 1800 1230 2500 COMMISSION (null) 0.2 0.6 0.3 (null) 0.8 SALARY*COMMISSION (null) 240 900 540 (null) 2000

Column Heading Default

Uppercase, however can be override the column heading with heading display with an alias. A column alias:

Is useful with calculations Immediately follows the column name (There can be also the optional AS keyword between column name and the alias.) Requires double quotation marks if it contains spaces of special characters, or if it is case-sensitive.

Example:
IDENTITYNO 790120-14-6222 800828-10-6323 870401-12-6087

NAME SELECT last_name as name, nokp as identityno Siti Razilah FROM employee; Musa Ahmad Martin Luke

Column Heading Default ..cont.


SELECT last_name as NaMe, nokp as identity no FROM employee;
NaMe Siti Razilah Musa Ahmad Martin Luke Identity no 790120-14-6222 800828-10-6323 870401-12-6087

SELECT last_name as **Name**, nokp as #identityno FROM employee;


**Name** Siti Razilah Musa Ahmad Martin Luke #identityno 790120-14-6222 800828-10-6323 870401-12-6087

Concatenation Operator
Links columns or character strings to other columns Is represented by two vertical bars (||) Create a resultant column that is a character employeeName expression SELECT last_name || first_name as

employeeName FROM employee; If a null value with a character string, the result is a character string. e.g: last_name || null last_name

Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff

Using Literal Character Strings

Literal is a character, a number, or a date that is included in the select statement. It is not a column name or a column alias. Date and character literal values must be enclosed within single quotation marks; number literals need not be enclosed in a similar manner; Each character string is output once for each row returned.

Using Literal Character Strings ..cont.


SELECT last_name ||:s 1 month salary =||salary Monthly FROM employee;
MONTHLY Siti Razilah :1 month salary = 1000 Musa Ahmad: 1 month salary = 1200 Martin Luke : 1 month salary = 1500 Ammar Faizul: 1 month salary = 1800 Safiyah Shahizan: 1 month salary = 1230 Taylor Duff: 1 month salary = 2500

Using Literal Character Strings ..cont.


SELECT last_name ||s 1 month salary =||salary Monthly FROM employee;
MONTHLY Siti Razilah s1 month salary = 1000 Musa Ahmads 1 month salary = 1200 Martin Luke s 1 month salary = 1500 Ammar Faizul s 1 month salary = 1800 Safiyah Shahizans 1 month salary = 1230 Taylor Duff s 1 month salary = 2500

Or you can use Quote (q) Operator [ ],< >,{ }, ( ) are allowed

SELECT last_name ||q[s 1 month salary =]||salary Monthly FROM employee;

Duplicate Rows

The default display of queries is all rows, including duplicate rows.


SELECT department_id FROM employee;
DEPARTMENT_ID

SELECT DISTINCT department_id FROM employee;


DEPARTMENT_ID

10
20 30 20 10 20

10
20 30

Note: If you specify multiple columns after the DISTIN qualifier, the result is every distinct combination of the columns.

Displaying the Table Structure


Use DESCRIBE command e.g: desc faculty;

Name ------------------------Null Type -------------- -----------------------------------------------------------------

FACULTYID
LNAME FNAME DEPT OFFICEID

NOT NULL
NOT NULL

NUMBER
VARCHAR2(30) VARCHAR2(5) NUMBER

NOT NULL VARCHAR2(20)

PHONE
EMAIL RANK 8 rows selected

VARCHAR2(15)
VARCHAR2(75) CHAR(4)

Quiz

Identify the SELECT statements that execute successfully.

1. SELECT first_name, last_name, job_id, salary*12 as yearly salary

FROM employees;
2.

SELECT first_name, last_name, job_id, salary*12 yearly salary FROM employees; SELECT first_name, last_name, job_id, salary*12 as yearly salary FROM employees; SELECT first_name || last_name name||q{s total salary is}||salary FROM employees;

3.

4.

Limiting Rows using a Selection

Restrict the rows that are returned by using the WHERE clause:

SELECT *|{[DISTINCT] column_name | expression [alias], FROM table_name [WHERE conditon(s)];

WHERE clause consists of three elements:


column name
comparison condition column name, constant or list of values

Limiting Rows using a Selection ..cont.


LAST_NAME Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff DEPT_ID 10 20 30 20 10 20 SALAR Y 1000 1200 1500 1800 1230 2500 COMMISSIO N (null) 0.2 0.6 0.3 (null) 0.8 SALARY*COMMISSIO N (null) 240 900 540 (null) 2000

SELECT last_name, dept_id, salary, commission FROM employee WHERE dept_id = 20;
LAST_NAME Musa Ahmad Ammar Faizul Taylor Duff DEPT_ID 20 20 20 SALAR Y 1200 1800 2500 COMMISSIO N 0.2 0.3 0.8

Limiting Rows using a Selection ..cont.


LAST_NAME Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff DEPT_ID 10 20 30 20 10 20 SALAR Y 1000 1200 1500 1800 1230 2500 COMMISSIO N (null) 0.2 0.6 0.3 (null) 0.8 SALARY*COMMISSIO N (null) 240 900 540 (null) 2000

1. Character strings and data values are enclosed with single quotation marks. 2. Character values are case-sensitive and date value are formatsensitive.

SELECT last_name, dept_id, salary, commission FROM employee WHERE last_name = Siti Razilah;
LAST_NAME Siti Razilah DEPT_ID 10 SALAR Y 1000

COMMISSIO N (null)

Comparison Operators
Operator = Meaning Equal to

> >=
< <= <>

Greater than Greater than or equal to


Less than Less than or equal to Not equal to

BETWEENAND Between two values (inclusive) IN(set) Many any of a list of values

LIKE
IS NULL

Match a character pattern


Is a Null value

Limiting Rows using a Selection ..cont.


LAST_NAME Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff DEPT_ID 10 20 30 20 10 20 SALAR Y 1000 1200 1500 1800 1230 2500 COMMISSIO N (null) 0.2 0.6 0.3 (null) 0.8 SALARY*COMMISSIO N (null) 240 900 540 (null) 2000

SELECT last_name, dept_id, salary, commission FROM employee WHERE dept_id between 10 and 20 ;

LAST_NAME Siti Razilah

DEPT_ID 10

SALAR Y 1000

COMMISSIO N (null)

Musa Ahmad
Ammar Faizul Safiyah Shahizan Taylor Duff

20
20 10 20

1200
1800 1230 2500

0.2
0.3 (null) 0.8

Limiting Rows using a Selection ..cont.


LAST_NAME Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff DEPT_ID 10 20 30 20 10 20 SALAR Y 1000 1200 1500 1800 1230 2500 COMMISSIO N (null) 0.2 0.6 0.3 (null) 0.8 SALARY*COMMISSIO N (null) 240 900 540 (null) 2000

SELECT last_name, dept_id, salary, commission FROM employee WHERE last_name like M% ;
LAST_NAME Musa Ahmad Martin Luke DEPT_ID 20 30 SALAR Y 1200 1500 COMMISSIO N 0.2 0.6

Limiting Rows using a Selection ..cont.


LAST_NAME Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff DEPT_ID 10 20 30 20 10 20 SALAR Y 1000 1200 1500 1800 1230 2500 COMMISSIO N (null) 0.2 0.6 0.3 (null) 0.8 SALARY*COMMISSIO N (null) 240 900 540 (null) 2000

SELECT last_name, dept_id, salary, commission FROM employee WHERE last_name like _a% ;
LAST_NAME Martin Luke Safiyah Shahizan DEPT_ID 30 10 SALAR Y 1500 1230 COMMISSIO N 0.6 (null)

Limiting Rows using a Selection ..cont.


LAST_NAME Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff DEPT_ID 10 20 30 20 10 20 SALAR Y 1000 1200 1500 1800 1230 2500 COMMISSIO N (null) 0.2 0.6 0.3 (null) 0.8 SALARY*COMMISSIO N (null) 240 900 540 (null) 2000

SELECT last_name, dept_id, salary, commission FROM employee WHERE dept_id in (10, 20) ;

LAST_NAME Siti Razilah

DEPT_ID 10

SALAR Y 1000

COMMISSIO N (null)

Musa Ahmad
Ammar Faizul Safiyah Shahizan Taylor Duff

20
20 10 20

1200
1800 1230 2500

0.2
0.3 (null) 0.8

Limiting Rows using a Selection ..cont.


LAST_NAME Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff DEPT_ID 10 20 30 20 10 20 SALAR Y 1000 1200 1500 1800 1230 2500 COMMISSIO N (null) 0.2 0.6 0.3 (null) 0.8 SALARY*COMMISSIO N (null) 240 900 540 (null) 2000

SELECT last_name, dept_id, salary, commission FROM employee WHERE commission is null;
LAST_NAME Siti Razilah Safiyah Shahizan DEPT_ID 10 10 SALAR Y 1000 1230 COMMISSIO N (null) (null)

Conditions Using the Logical Operators


Operator AND OR NOT Meaning Return TRUE If both component conditions are true Return TRUE If either component condition is true Return TRUE If the condition is true

AND Logical Operator


LAST_NAME Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff DEPT_ID 10 20 30 20 10 20 SALAR Y 1000 1200 1500 1800 1230 2500 COMMISSIO N (null) 0.2 0.6 0.3 (null) 0.8 SALARY*COMMISSIO N (null) 240 900 540 (null) 2000

SELECT last_name, dept_id, salary, commission FROM employee WHERE last_name like M% AND dept_id = 20;
LAST_NAME Musa Ahmad DEPT_ID 20 SALAR Y 1200 COMMISSIO N 0.2

AND Truth Table


AND TRUE FALSE NULL TRUE TRUE FALSE NULL FALSE FALSE FALSE FALSE NULL NULL FALSE NULL

OR Logical Operator
LAST_NAME Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff DEPT_ID 10 20 30 20 10 20 SALAR Y 1000 1200 1500 1800 1230 2500 COMMISSIO N (null) 0.2 0.6 0.3 (null) 0.8 SALARY*COMMISSIO N (null) 240 900 540 (null) 2000

SELECT last_name, dept_id, salary, commission FROM employee WHERE last_name like M% OR dept_id = 20;

LAST_NAME

DEPT_ID

SALAR Y

COMMISSIO N

Musa Ahmad
Martin Luke Ammar Faizul Taylor Duff

20
30 20 20

1200
1500 1800 2500

0.2
0.6 0.3 0.8

OR Truth Table
OR TRUE FALSE NULL TRUE TRUE TRUE TRUE FALSE TRUE FALSE NULL NULL TRUE NULL NULL

NOT Operator
LAST_NAME Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff DEPT_ID 10 20 30 20 10 20 SALAR Y 1000 1200 1500 1800 1230 2500 COMMISSIO N (null) 0.2 0.6 0.3 (null) 0.8 SALARY*COMMISSIO N (null) 240 900 540 (null) 2000

SELECT last_name, dept_id, salary, commission FROM employee WHERE dept_id NOT IN (10,30);
LAST_NAME Musa Ahmad Ammar Faizul Taylor Duff DEPT_ID 20 20 20 SALAR Y 1200 1800 2500 COMMISSIO N 0.2 0.3 0.8

Sorting Rows

Sort the retrieved rows with the ORDER BY clause:


ASC: Ascending order, default DESC: Descending order


DEPT_I D SALAR Y COMMISSIO N SALARY*COMMISSIO N

LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff

10 20 30 20 10 20

1000 1200 1500 1800 1230 2500

(null) 0.2 0.6 0.3 (null) 0.8

(null) 240 900 540 Siti Razilah (null) 2000


Safiyah Shahizan LAST_NAME DEPT_I D SALARY COMMISSIO N

10 10 20 20 20 30

1000 1230 1200 1800 2500 1500

(null) (null) 0.2 0.3 0.8 0.6

Musa Ahmad

SELECT last_name, dept_id, salary, commission FROM employee ORDER BY dept_id;

Ammar Faizul Taylor Duff Martin Luke

Sorting Rows ..cont.

Sort the retrieved rows with the ORDER BY clause:


ASC: Ascending order, default DESC: Descending order


DEPT_I D SALAR Y COMMISSIO N SALARY*COMMISSIO N

LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff

10 20 30 20 10 20

1000 1200 1500 1800 1230 2500

(null) 0.2 0.6 0.3 (null) 0.8

(null) 240 900 540


Martin Luke LAST_NAME DEPT_I D SALARY COMMISSIO N

30 20 20 20 10 10

1500 2500 1800 1200 1000 1230

0.6 0.8 0.3 0.2 (null) (null)

(null)
Taylor Duff

2000
Ammar Faizul

SELECT last_name, dept_id, salary, commission FROM employee ORDER BY dept_id DESC;

Musa Ahmad Siti Razilah Safiyah Shahizan

Sorting Rows ..cont.

Sort the retrieved rows with the ORDER BY clause:


ASC: Ascending order, default DESC: Descending order


DEPT_I D SALAR Y COMMISSIO N SALARY*COMMISSIO N

LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff

10 20 30 20 10 20

1000 1200 1500 1800 1230 2500

(null) 0.2 0.6 0.3 (null) 0.8

(null) 240 900 540


Martin Luke LAST_NAME DEPT_I D SALARY COMMISSIO N

30 20 20 20 10 10

1500 2500 1800 1200 1000 1230

0.6 0.8 0.3 0.2 (null) (null)

(null)
Taylor Duff

2000
Ammar Faizul

SELECT last_name, dept_id, salary, commission FROM employee ORDER BY 2 DESC

Musa Ahmad Siti Razilah Safiyah Shahizan

Sorting Rows ..cont.

Sort the retrieved rows with the ORDER BY clause:


ASC: Ascending order, default DESC: Descending order


DEPT_I D SALAR Y COMMISSIO N SALARY*COMMISSIO N

LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff

10 20 30 20 10 20

1000 1200 1500 1800 1230 2500

(null) 0.2 0.6 0.3 (null) 0.8

(null) 240 900


LAST_NAME DEPT_I D SALARY COMMISSIO N

540
Martin Luke

(null)
Taylor Duff

30 20 20 20 10 10

1500 2500 1800 1200 1230 1000

0.6 0.8 0.3 0.2 (null) (null)

2000
Ammar Faizul

SELECT last_name, dept_id, salary, commission FROM employee ORDER BY dept_id, salary desc;

Musa Ahmad Safiyah Shahizan Siti Razilah

Substitution Variables

Use a variable prefixed with an ampersand (&) to prompt the user for a value:
SELECT last_name, dept_id, salary, commission FROM employee WHERE dept_id = &dept_id;

LAST_NAME Musa Ahmad

DEPT_ID 20 20 20

SALAR Y 1200 1800 2500

COMMISSIO N 0.2 0.3 0.8

20

Ammar Faizul Taylor Duff

Using Functions to Customize Output

FUNCTIONS

SINGLE-ROW FUNCTIONS Return one result per row

MULTIPLEROW FUNCTIONS
Return one result per set of rows

Single Row Functions Character Data Type

LOWER(column/expression) UPPER(column/expression) INITCAP(column/expression) CONCAT(column/expression, column/expression) SUBSTR(column/expression, m[,n])


m character position (if m is negative, the count starts from the end of the character value. n character long (if n is omitted, all characters to the end of the string are returned)

LENGTH(column/expression) INSTR(column/expression, string [, m] , [n])

An Example
FUNCTION LOWER(Database application) RESULT database application

UPPER(Database application)
INITCAP(Database application) CONCAT(Hello, World) SUBSTR(HelloWorld,2,5) INSTR(HelloWorld, W) LPAD(salary,10,*) RPAD(salary,10,*)

DATABASE APPLICATION
Database Application HelloWorld elloW 6 *****24000 24000*****

REPLACE(JACK AND JUE, J, BL)

BLACK AND BLUE

Single Row Functions Number Data Type

ROUND: Rounds value to a special decimal TRUNC: Truncates value to specified decimal MOD: Returns remainder of division
FUNCTION ROUND(45.926, 2) TRUNC(45.926, 2) RESULT 45.93 45.92

MOD(1600, 300)

100

Nesting Functions
LAST_NAME Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff DEPT_ID 10 20 30 20 10 20 SALAR Y 1000 1200 1500 1800 1230 2500 COMMISSIO N (null) 0.2 0.6 0.3 (null) 0.8 SALARY*COMMISSIO N (null) 240 900 540 (null) 2000

SELECT last_name, UPPER(CONCAT(SUBSTR(last_name,1,8), _US)) name FROM employee;

LAST_NAM E
Siti Razilah Musa Ahmad Martin Luke

NAME
SITI RAZ_US MUSA AHM_US MARTIN L_US

Ammar Faizul
Safiyah Shahizan Taylor Duff

AMMAR FA_US
SAFIYAH _US TAYLOR D_US

NVL FUNCTION

Convert a null value to an actual value:


Data

types that can be used are date, character and number. Data types must match:
NVL(commission,

0) NVL(hire_date, 01-JAN-10) NVL(job, No Job Yet)

CASE EXPRESSION
Not available in Microsoft Access. It is in SQL Server and Oracle.

Select AnimalID, CASE WHEN Date()-DateBorn < 90 Then Baby WHEN Date()-DateBorn >= 90 AND Date()-DateBorn < 270 Then Young WHEN Date()-DateBorn >= 270 AND Date()-DateBorn < 365 Then Grown ELSE Experienced END STATUS FROM Animal; Used to change data to a different context. Example: Define age categories for the animals.

Less than 3 months Between 3 months and 9 months Between 9 months and 1 year Over 1 year

Multiple-Row Functions

Group functions operate on sets of rows to give one result per group.
LAST_NAME
Siti Razilah Musa Ahmad Ammar Faizul Safiyah Shahizan Taylor Duff

DEPT_ID
10 20 20 10 20

SALAR Y
1000 1200 1800 1230 2500

Maximum salary in EMPLOYE ES table

MAX(SALARY ) 2500

Type of Multiple Row Functions

AVG(column) MAX(column) MIN(column) SUM(column) COUNT(*) or COUNT(column) or COUNT(DISTINCT column)


COUNT(*) returns the number of rows in a table. COUNT(commission) returns the number of rows with non-null values. COUNT(DISTINCT commission) returns the number of distinct commission values.

Multiple-Row Functions and Null Values

Group functions ignore null values in the column: SELECT


AVG(commission) FROM employee;

The NVL function forces group functions to include null values:


SELECT AVG(NVL(commission,0)) FROM employee;

LAST_NAM E
Siti Razilah

DEPT_I D

SALAR COMMISSIO Y N

10

1000

(null)

Musa Ahmad
Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff

20 30 20 10
20

1200 1500 1800 1230


2500

0.2 0.6 0.3 (null)


0.8

GROUP BY clause

Group functions operate on sets of rows to give one result per group.
LAST_NAME Siti Razilah Musa Ahmad
Martin Luke

DEPT_ID 10 20 30 20

SALAR Y 1000 1200 DEPT_ID MAX(SALARY)

Maximum salary for each department in EMPLOYEE S table

1500 1800

10 20 30

1230 2500 1500

Ammar Faizul

Safiyah Shahizan
Taylor Duff

10
20

1230
2500

Creating Groups of Data

To divide rows in a table into smaller groups by using GROUP BY clause.

SELECT *|{[DISTINCT] column_name | expression [alias], FROM table_name [WHERE conditon(s)]; [GROUP BY group_by_expression] [ORDER BY column];

Using the GROUP BY clause


All the columns in the SELECT list that are not in group functions must be in the GROUP BY clause. However, the GROUP BY column does not have to be in the SELECT list.
SELECT dept_id, MAX(salary) FROM employee GROUP BY dept_id; DEPT_ID MAX(SALARY) 10 20 30 1230 2500 1500 SELECT MAX(salary) FROM employee GROUP BY dept_id;
MAX(SALARY)

1230 2500 1500

Use Group Functions in ORDER BY


SELECT dept_id, MAX(salary) FROM employee GROUP BY dept_id ORDER BY MAX(salary);
DEPT_ID MAX(SALARY)

20 30 10

2500 1500 1230

Restricting Group Results


LAST_NAME Siti Razilah Musa Ahmad
Martin Luke

DEPT_ID 10 20 30 20 10 20

SALAR Y 1000 1200 1500 1800 1230 2500 Maximum salary for each department BUT only for those who average salary is greater than 1 1300

DEPT_ID

MAX(SALARY)

20 30

2500 1500

Ammar Faizul Safiyah Shahizan Taylor Duff

Restricting Group with HAVING clause

SELECT *|{[DISTINCT] column_name | expression [alias],.. FROM table_name [WHERE conditon(s)]; [GROUP BY group_by_expression] [HAVING group_coundition] [ORDER BY column];
SELECT dept_id, MAX(salary) FROM employee GROUP BY dept_id HAVING MAX(salary) > 1300;

End with displaying data from a table


Then, we continue with displaying data from multiple tables or known as join tables. Shall we start?

EMPLOYEE
EMPI D
1 2

DEPENDENT
DEPT_I D SALAR Y COMMISSIO N DEPI D
101 102 103 104

NAME
Muhammad Sarah Linda Ali

DOB
12-10-1960 03-03-1990 12-06-1993 27-09-1997

LAST_NAME
Siti Razilah Musa Ahmad

STATU S
Suami Anak Anak Anak

EMPID
1 1 1 1

10 20

1000 1200

(null) 0.2

3
4 5 6

Martin Luke
Ammar Faizul Safiyah Shahizan Taylor Duff

30
20 10 20

1500
1800 1230 2500

0.6
0.3 (null) 0.8

105
106 107 108 109

Sarimah
Adibah Haziq Elizabeth Ridzuan

11-08-1976
24-07-2003 06-03-2005 04-04-1973 09-02-1990

Isteri
Anak Anak Isteri Anak

2
2 2 6 4

LAST_NAM E Siti Razilah Siti Razilah Siti Razilah Siti Razilah Musa Ahmad Musa Ahmad Musa Ahmad Ammar

SALARY 1000 1000 1000 1000 1200 1200 1200 1800

NAME Muhamma d Sarah Linda Ali Sarimah Adibah Haziq Ridzuan

STATUS Suami Anak Anak Anak Isteri Anak Anak Anak

Table Joins

Process of combining data from two or more tables, normally using primary and/or foreign keys. Basic types of joins:

Natural Joins:

NATURAL JOIN clause USING clause ON clause

Self-Joins Nonequijoins Outer Joins:


LEFT OUTER JOIN clause RIGHT OUTER JOIN clause FULL OUTER JOIN clause

CROSS JOIN clause

Joining Tables Using SQL:1999 syntax

SELECT table1.column, table2.column FROM table1 [NATURAL JOIN table2] | [JOIN table2 USING (column_name)] | [JOIN table2 on (table1.column_name = table2.column_name)] | [LEFT | RIGHT | FULL OUTER JOIN table2 on table1.column_name = table2.column_name)]| [CROSS JOIN table2];

Creating NATURAL JOIN clause

The NATURAL JOIN clause is based on all the columns in the two tables that have the same name. It selects rows from the two tables that have equal values in all matched columns.

If the columns having same name but different data type, an error is returned.

Example of Using NATURAL JOIN clause


EMPLOYEE
EMPI D
1 2 3 4 5 6

DEPARTMENT
DEPT_I D SALAR Y COMMISSIO N DEPT_ID DEPT_NAME

LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff

10 20 30 20 10 20

1000 1200 1500 1800 1230 2500

(null) 0.2 0.6 0.3 (null) 0.8

10 20 30 40 50 60
LAST_NAME

Department of Networking Department of Info. Science Department of Multimedia Department of Computer Science Department of Applied Science Department of Robotics
SALAR Y DEPT_NAME

SELECT last_name, salary, dept_name FROM employee NATURAL JOIN department

Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff

1000 1200 1500 1800 1230 2500

Department of Networking Department of Info. Science Department of Multimedia Department of Info. Science Department of Networking Department of Info. Science

Creating join with the USING clause

If several columns have same name but different data type then use the USING clause to specify the columns for the equijoin. Or, use the USING clause when wanted to match only one column of many column matches.

Example of Using NATURAL JOIN clause


EMPLOYEE
EMPI D
1 2 3 4 5 6

DEPARTMENT
DEPT_I D SALAR Y COMMISSIO N DEPT_ID DEPT_NAME

LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff

10 20 30 20 10 20

1000 1200 1500 1800 1230 2500

(null) 0.2 0.6 0.3 (null) 0.8

10 20 30 40 50 60
LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff

Department of Networking Department of Info. Science Department of Multimedia Department of Computer Science Department of Applied Science Department of Robotics
SALAR Y DEPT_NAME

SELECT last_name, salary, dept_name FROM employee JOIN department USING (dept_id)

1000 1200 1500 1800 1230 2500

Department of Networking Department of Info. Science Department of Multimedia Department of Info. Science Department of Networking Department of Info. Science

Using Table Aliases with the USING clause

Do not qualify a column that is used in the USING clause.


SELECT e.last_name, e.salary, d.dept_name FROM employee e JOIN department d USING (dept_id) WHERE d.dept_id in (10,20);

SELECT e.last_name, e.salary, d.dept_name FROM employee e JOIN department d USING (dept_id) WHERE dept_id in (10,20);

Creating Joins with the ON clause


NATURAL JOIN is basically equijoin of all columns with the same name. For arbitrary conditions (selected columns) use the ON clause Example:
SELECT e.last_name, e.salary, d.dept_name FROM employee e JOIN department d ON (e.dept_id = d.dept_id);

Applying Additional Conditions to a Join

Use the AND clause or the WHERE clause to specify additional conditions. Example:
SELECT e.last_name, e.salary, d.dept_name FROM employee e JOIN department d ON (e.dept_id = d.dept_id) AND e.salary > 1000; SELECT e.last_name, e.salary, d.dept_name FROM employee e JOIN department d ON (e.dept_id = d.dept_id) WHERE e.salary > 1000;

SELF-JOIN

EMPI D
1 2 3 4 5 6

Joining a table to itself.


LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff

EMPLOYEE (WORKER)
DEPT_I D SALAR Y COMMISSIO N MGR_I D

10 20 30 20 10 20

1000 1200 1500 1800 1230 2500

(null) 0.2 0.6 0.3 (null) 0.8


EMPI D
1 2 3 4 5

6 4 6 6 1 (null)

EMPLOYEE (MANAGER)
LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan

DEPT_I D

SALAR Y

COMMISSIO N

MGR_I D

10 20 30 20 10

1000 1200 1500 1800 1230

(null) 0.2 0.6 0.3 (null)

6 4 6 6 1

Self-Join using the ON clause


SELECT worker.last_name emp, worker.dept_id department, worker.salary salary, manager.last_name manager FROM employee worker JOIN employee manager ON (worker.mgr_id = manager.empid);
EMP Safiyah Shahizan Musa Ahmad Ammar Faizul Siti Razilah Martin Luke DEPARTME NT 10 20 20 10 30 SALAR Y 1230 1200 1800 1000 1500 MANAGER Siti Razilah Ammar Faizal Taylor Duff Taylor Duff Taylor Duff

Nonequijoins
A join condition containing something other than an equality operator. EMPLOYEE

JOB_GRADE
GRADE_LEV EL A B C

EMPI D
1
2 3 4 5

LAST_NAME
Siti Razilah
Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan

DEPT_I D

SALAR Y

COMMISSIO N

MGR_I D

LOW_SA L 0 1000 2000

MAX_SA L 999 1999 2999

10
20 30 20 10

1000
1200 1500 1800 1230

(null)
0.2 0.6 0.3 (null)

6
4 6 6 1

D
E
LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff

3000
4000
SALAR Y

3999
10000
GRADE_LE VEL

Taylor Duff

20

2500

0.8

(null)

SELECT e.last_name, e.salary, j.grade_level FROM employee e JOIN job_grade j ON e.salary BETWEEN j.low_sal AND j.max_sal

1000 1200 1500 1800 1230 2500

B B B B B C

Nonequijoins ..cont.
AccountsReceivable Categorize by Days Late 30, 90, 120+ Three queries? New table for business rules
AR(TransactionID, CustomerID, Amount, DateDue)

LateCategory(Category, MinDays, MaxDays, Charge, )


Month Quarter Overdue 30 90 120 90 120 9999 3% 5% 10%

SELECT * FROM AR JOIN LateCategory ON ((Date() - AR.DateDue) >= LateCategory.MinDays) AND ((Date() - AR.DateDue) < LateCategory.MaxDays)

Returning Record with No Direct Match

Use OUTER joins.


LEFT

OUTER JOIN clause RIGHT OUTER JOIN clause FULL OUTER JOIN clause

LEFT OUTER JOIN

Used when you may not have matching data in the secondary table, but still want to include the data you have in the primary table.

NOTE: The primary table is normally listed on the left side of the equation, the secondary on the right side.

An Example of Left Joins


Insert a new department in table dept (for example, dept_id=50).
Select d.dept_id, d.dept_name, e.dept_id, e.last_name FROM dept d LEFT OUTER JOIN employee e ON d.dept_id = e.dept_id;
DEPT_I D DEPT_NAME DEPT_I D LAST_NAME Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan

10 20 30 20 10

Department of Networking Department of Info. Science Department of Multimedia Department of Info. Science Department of Networking

10 20 30 20 10

RIGHT OUTER JOINS

Used when you may have data in the secondary table with no matching data in the primary table. Example:

Insert a new employee in table employee (for example, empid=7). Select d.dept_id, d.dept_name, e.dept_id, e.last_name FROM dept d RIGHT OUTER JOIN employee e ON d.dept_id = e.dept_id;

RIGHT OUTER JOINS ..cont.


Insert a new employee in table employee (for example, empid=7). Select d.dept_id, d.dept_name, e.dept_id, e.last_name FROM dept d RIGHT OUTER JOIN employee e ON d.dept_id = e.dept_id;
DEPT_I D DEPT_NAME DEPT_I D LAST_NAME Gopal

10 20 30 20

Department of Networking Department of Info. Science Department of Multimedia Department of Info. Science

10 20 30 20

Siti Razilah Musa Ahmad Martin Luke Ammar Faizul

FULL OUTER JOIN


Select d.dept_id, d.dept_name, e.dept_id, e.last_name FROM dept d RIGHT OUTER JOIN employee e ON d.dept_id = e.dept_id;
DEPT_I D DEPT_NAME DEPT_I D LAST_NAME Gopal

10 20 30 20 10 20

Department of Networking Department of Info. Science Department of Multimedia Department of Info. Science Department of Networking Department of Info. Science

10 20 30 20 10 20

Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff

Generating a Cartesian Product

Use CROSS JOIN clause


EMPLOYEE (6 rows)
LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff

DEPART (4 rows)
COMMISSIO N DEPT_ID DEPT_NAME

DEPT_I D

SALAR Y

10 20 30 20 10 20

1000 1200 1500 1800 1230 2500

(null) 0.2 0.6 0.3 (null) 0.8

10 20 30 40

Department of Networking Department of Info. Science Department of Multimedia Department of Computer Science

Cartesian Product: 6 X 4 = 24 rows

Generating a Cartesian Product ..cont.

Using Subqueries to Solve Queries


Main Query: Which employees have salaries greater than Ammar Faizuls salary?

Sub Query: How much is Ammar Faizuls salary?

SubQuery Syntax
SELECT select_list FROM table WHERE expr operator (Select select_list FROM TABLE);

The subquery (inner query) executes before the main query (outer query) The result of subquery is used by the main query.

An Example of Subquery
SELECT last_name, salary FROM employee where salary > (SELECT salary FROM employee WHERE last_name = Ammar Faizul);
LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff

DEPT_I D

SALAR Y

LAST_NAME
Taylor Duff

SALAR Y

10 20 30 20 10 20

1000 1200 1500 1800 1230 2500

2500

Types of Subqueries

Single-row subquery
Main Query returns 1000

SubQuery

Multiple-row subquery
Main Query SubQuery returns 1200 1800 2500

An Example
SELECT last_name, salary FROM employee where salary = (SELECT salary FROM employee WHERE dept_id = 20);
Single-row operator with multiple-row subquery

SELECT last_name, salary FROM employee where salary in (SELECT salary FROM employee WHERE dept_id = 20);

Subquery Characteristics

Can be used in the SELECT, CREATE, INSERT, UPDATE and DELETE statements Can be used as part of a condition in the WHERE clause

Can be used in multiple AND or OR predicates of the same SQL statement


Is enclosed in parenthesis and must appear on the right in a WHERE clause condition

Cannot include an ORDER BY clause


The number of rows returned by the subquery must match the number expected by the main query

Combining Subqueries

Multiple subqueries can be used to check for more than one condition in a statement.
Example: SELECT last_name, salary FROM employees WHERE dept_id = (SELECT dept_id FROM employee WHERE last_name = Taylor Duff) AND salary > (SELECT salary FROM employee WHERE last_name = Taylor Duff);

Same or different types can be nested.

NOTE: Nested subqueries are executed from the most deeply nested to the least deeply nested subquery.

Example
Show all customers who have placed an order
SELECT customer_name FROM customer_t WHERE customer_ID IN
(SELECT DISTINCT customer_ID FROM order_t);

Subquery is embedded in parentheses. In this case it returns a list that will be used in the WHERE clause of the outer query

Subquery for Calculation


Which cats sold for more than the average sale price of cats? Assume we know the average price is $170. Usually we need to compute it first.
SELECT SaleAnimal.AnimalID, Animal.Category, SaleAnimal.SalePrice FROM Animal SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE ((Animal.Category="Cat") AND (SaleAnimal.SalePrice>170)); SELECT SaleAnimal.AnimalID, Animal.Category, SaleAnimal.SalePrice FROM Animal JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE ((Animal.Category="Cat") AND (SaleAnimal.SalePrice> ( SELECT AVG(SalePrice) FROM Animal JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE (Animal.Category=Cat) ) ) );

Using NOT IN with a Subquery


Which animals have not been sold?

Start with list of all animals. Subtract out list of those who were sold. SELECT Animal.AnimalID, Animal.Name, Animal.Category FROM Animal WHERE (Animal.AnimalID Not In (SELECT AnimalID From SaleAnimal));

UNION, INTERSECT, MINUS

List the name of any employee who has worked for both the East and West regions.

T1

T2

T1 UNION T2 T1 INTERSECT T2 T1 EXCEPT T2

A+B+C B A

SELECT EID, Name FROM EmployeeEast INTERSECT SELECT EID, Name FROM EmployeeWest

UNION
SELECT EID, Name, Phone, Salary, East AS Office FROM EmployeeEast UNION SELECT EID, Name, Phone, Salary, West AS Office FROM EmployeeWest
EID 352 876 372 890 361 Name Jones Inez Stoiko Smythe Kim Phone 3352 8736 7632 9803 7736 Salary 45,000 47,000 38,000 62,000 73,000 Office East East East West West

Offices in Los Angeles and New York. Each has an Employee table (East and West). Need to search data from both tables. Columns in the two SELECT lines must match the column number and column type.

Summary

In this chapter you learned how to:


Define

key terms: join, equijoin, self-join, nonequijoin, natural join, outer join, set operators and subquery. Apply the DML command to insert, update and delete data from table. Write single and multiple table queries using SQL commands Write queries using subqueries.

You might also like