Database Application SSK 3408: Data Manipulation Language
Database Application SSK 3408: 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.
OR
INSERT INTO customer (last_name, state_cd, sales) VALUES (Teplow ,MA,23445.67);
Select statement retrieves information from the databases. Capabilities of SQL Select Statements:
Selectio n
Projection
Join
Table 1
Table 2
Table 1
Table 2
SELECT identifies the columns to be displayed FROM identifies the table containing those columns.
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
Null is a value that is unavailable, unassigned, unknown, or inapplicable. Null is not the same as zero or a blank space.
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
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
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.
Or you can use Quote (q) Operator [ ],< >,{ }, ( ) are allowed
Duplicate Rows
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.
FACULTYID
LNAME FNAME DEPT OFFICEID
NOT NULL
NOT NULL
NUMBER
VARCHAR2(30) VARCHAR2(5) NUMBER
PHONE
EMAIL RANK 8 rows selected
VARCHAR2(15)
VARCHAR2(75) CHAR(4)
Quiz
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.
Restrict the rows that are returned by using the WHERE clause:
column name
comparison condition column name, constant or list of values
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
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
> >=
< <= <>
BETWEENAND Between two values (inclusive) IN(set) Many any of a list of values
LIKE
IS NULL
SELECT last_name, dept_id, salary, commission FROM employee WHERE dept_id between 10 and 20 ;
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
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
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)
SELECT last_name, dept_id, salary, commission FROM employee WHERE dept_id in (10, 20) ;
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
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)
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
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
LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff
10 20 30 20 10 20
10 10 20 20 20 30
Musa Ahmad
LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff
10 20 30 20 10 20
30 20 20 20 10 10
(null)
Taylor Duff
2000
Ammar Faizul
SELECT last_name, dept_id, salary, commission FROM employee ORDER BY dept_id DESC;
LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff
10 20 30 20 10 20
30 20 20 20 10 10
(null)
Taylor Duff
2000
Ammar Faizul
LAST_NAME
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff
10 20 30 20 10 20
540
Martin Luke
(null)
Taylor Duff
30 20 20 20 10 10
2000
Ammar Faizul
SELECT last_name, dept_id, salary, commission FROM employee ORDER BY dept_id, salary desc;
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;
DEPT_ID 20 20 20
20
FUNCTIONS
MULTIPLEROW FUNCTIONS
Return one result per set of rows
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)
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*****
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
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
types that can be used are date, character and number. Data types must match:
NVL(commission,
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
MAX(SALARY ) 2500
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.
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
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
1500 1800
10 20 30
Ammar Faizul
Safiyah Shahizan
Taylor Duff
10
20
1230
2500
SELECT *|{[DISTINCT] column_name | expression [alias], FROM table_name [WHERE conditon(s)]; [GROUP BY group_by_expression] [ORDER BY column];
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)
20 30 10
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
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;
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
Table Joins
Process of combining data from two or more tables, normally using primary and/or foreign keys. Basic types of joins:
Natural Joins:
LEFT OUTER JOIN clause RIGHT OUTER JOIN clause FULL OUTER JOIN clause
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];
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.
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
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
Siti Razilah Musa Ahmad Martin Luke Ammar Faizul Safiyah Shahizan Taylor Duff
Department of Networking Department of Info. Science Department of Multimedia Department of Info. Science Department of Networking Department of Info. Science
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.
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
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)
Department of Networking Department of Info. Science Department of Multimedia Department of Info. Science Department of Networking Department of Info. Science
SELECT e.last_name, e.salary, d.dept_name FROM employee e JOIN department d USING (dept_id) WHERE dept_id in (10,20);
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);
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
EMPLOYEE (WORKER)
DEPT_I D SALAR Y COMMISSIO N MGR_I D
10 20 30 20 10 20
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
6 4 6 6 1
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
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
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)
SELECT * FROM AR JOIN LateCategory ON ((Date() - AR.DateDue) >= LateCategory.MinDays) AND ((Date() - AR.DateDue) < LateCategory.MaxDays)
OUTER JOIN clause RIGHT OUTER JOIN clause FULL OUTER JOIN clause
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.
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
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;
10 20 30 20
Department of Networking Department of Info. Science Department of Multimedia Department of Info. Science
10 20 30 20
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
DEPART (4 rows)
COMMISSIO N DEPT_ID DEPT_NAME
DEPT_I D
SALAR Y
10 20 30 20 10 20
10 20 30 40
Department of Networking Department of Info. Science Department of Multimedia Department of Computer Science
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
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
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);
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
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));
List the name of any employee who has worked for both the East and West regions.
T1
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
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.