Download as pdf or txt
Download as pdf or txt
You are on page 1of 133

DATABASE LAB

Lab5

Creating and Managing Tables


DDL

Ruba Sultan
Data Definition Language
• Data Definition Language (DDL) it is used to
specify a database scheme as a set of
definitions1.
• It allows you to create, alter, and destroy
database objects1.
• DDL consists of number of statements
– CREATE
– DROP
– ALTER
1

http://www.webopedia.com/T 2
ERM/D/DDL.html
Database Objects2

Object Description
Table Basic unit of storage composed of rows and columns
View Logically represents subsets of data from one or more
tables
Sequence Generates primary key values
Index Improves the performance of some queries
Synonym Gives alterative names to objects
Objects Naming3
 Table names and column names:
 Must begin with a letter.
 Can be 1-30 character long.
 Must contain only A-Z, a-z, 0-9 _, $ , and #
 Must not duplicate the name of another object
owned by the same user.
 Must not be an oracle server reserved word.

4
CREATE TABLE Statement
• To create a table
– CREATE TABLE privilege.
– A storage area.
• CREATE TABLE syntax.

CREATE TABLE [schema.]table


(column datatype [DEFAULT expr][, ...])

5
Datatypes5
Data type Description
VARCHAR2(size) variable length character data
CHAR(size) fixed length character data
NUMBER(p,s) variable length numeric data
DATE Date and time values
LONG Variable length character data up to 2 gigabytes
CLOB Single byte character data up to 4 gigabytes.
RAW and LONG RAW RAW binary data
BLOB Binary data stored up to 4 gigabytes.
BFILE Binary data stored in external file up to 4 gigabytes.

5 Introduction to Oracle: SQL and PL/SQL P10-11 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
Ex:
• Create the table.
CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13));
Table created.

• Confirm table creation.


DESCRIBE dept

7
Questions
 Question1
Create a table named College, and the
following contains a description of the table.
Column Name CID CName DeanID Location
Type NUMBER VARCHAR2 NUMBER VARCHAR2
Length 6 20 4 15
Default Value Hebron

8
Creating a Table Using Subqueries6
• Create a table insert rows by combining the
CREATE TABLE statement and AS subqeruy.
CREATE TABLE table
[{column, column ….}]
AS subquery;
• Match the number of specified columns to the
number of subquery columns.
• Define columns with column names and default
values.

6 Introduction to Oracle: SQL and PL/SQL P10-11 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999 9
Questions
 Question2
Create a table named dept90 which contains
employees’ numbers, names(first and last)
names, their annual salaries and their hire dates
for all employees who are in department 90.
 Question3
Retrieve all data in dept90 table. Describe table
structure and compare data types with that of
Employees table.
10
ALTER Statement
• ALTER statement used to change the structure
of table.
• There are three type of ALTER statement.
– ALTER ADD
– ALTER MODIFY
– ALTER DROP

11
ALTER Syntax
ALTER TABLE table
ADD(column datatype [DEFAULT expr]
[column datatype] ...);

ALTER TABLE table


MODIFY(column datatype [DEFAULT expr]
[column datatype] ...);

ALTER TABLE table


DROP COLUMN name;

12
Adding a Column
New column
DEPT90

“Add a new
column to
the DEPT90
DEPT90 table.”

13
Adding a Column
• You use the ADD clause to add columns.
ALTER TABLE dept90
ADD (job_id VARCHAR2(9));
Table altered.

• The new column becomes the last column.

14
Questions
 Question4
Add to employees table column named Gender
and it has a default value MALE.

 Question5
Modify employees table so length of name field of
employees become 15 instead of 10 and default
value of salary be $1500.

15
Modifying a Column
• You can change a column’s data type, size, and
default value.
ALTER TABLE dept90
MODIFY (last_name VARCHAR2(30));
Table altered.

• A change to the default value affects only


subsequent insertions to the table.

16
Dropping a Column
Use the DROP COLUMN clause to drop columns you no
longer need from the table.

ALTER TABLE dept90


DROP COLUMN job_id;
Table altered.

17
RENAME Statement
• Used to change database object’s names.
• Only the owner of object can rename it.
• The syntax of RENAME statement as following

RENAME oldname TO newname

RENAME dept90 TO detail_dept;


Table renamed.
.

18
TRUNCATE Statement
• Remove all data from table.
• Release the storage space of that table.
• It can not be rolled back.
• The syntax of TRUNCATE statement as
following

TRUNCATE TABLE tablename

19
DROP Statement
• All data and table structure will be deleted.
• It can not be rolled back.
• The syntax of DROP statement as following

DRPOP TABLE tablename

20
Questions
 Question6
Modify name of job_History to be History.

 Question7
Delete all rows in dept90 permanently.

21
DATABASE LAB
Lab3: DML

Ruba Sultan
Data Manipulation Language(DML) 1
2

 A DML statement is executed when you1:


 Add new rows to a table
 Modify existing rows in a table

 Remove existing rows from a table

 A Transaction consists of a collection of DML


statements that form a logical unit of work1.

1 Introduction to Oracle: SQL and PL/SQL P9-3 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
INSERT Statement 2
3

 Add new rows to a table using the INSERT statement

INSERT INTO table [(column [, column,…] ) ]


VALUES (value [, value…]);

 Only one row is inserted at a time with the previous


syntax.

2 Introduction to Oracle: SQL and PL/SQL P9-5 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
Inserting New Rows 3
4

 Insert a new row containing values for each column.

 List values in the default order of the columns in the


table.

 Optionally list the columns in the INSERT clause.

 Enclose character and date values within single


quotation marks.

3 Introduction to Oracle: SQL and PL/SQL P9-6 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
Inserting Rows with Null Values 4
5

 Implicit method: Omit the column from the column


list.
INSERT INTO departments (department_id,
department_name, Location)
VALUES(280,'Client Relation',2500);

 Explicit method: Specify the NULL keyword


INSERT INTO departments
VALUES(290, 'Maintenance ', NULL, 1700);

4 Introduction to Oracle: SQL and PL/SQL P9-7 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
Questions
6

 Question1
Write an SQL statement to add the following
information of employee.
ID: 207
First Name: Rami
Last Name: Ali
Email: RamiAli
Hire Date: Current Date
Job ID: IT_PROG
Salary: $2500
Ex:
7
Copying Rows from Another Table
8

 Write your INSERT statement with a subquery.

 Do not use the VALUES clause.

 Match the number of columns in the INSERT clause to those in the


subquery.
UPDATE Statement 5
9

 Modify exiting rows with the UPDATE statement

UPDATE tablename
SET column=value[, column=value,…]
[WHERE condition(s)];

Update more than one row at a time, if required.


Note:
All rows are modified in a table if WHERE clause is
not used.
5 Introduction to Oracle: SQL and PL/SQL P9-14 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
Questions
10

 Question2
Write an SQL statement to modify salary of
employee 106 to be $12000.

 Question3
Write an SQL statement to modify salary and
commission of employee 105 to be same as that of
employee 155.
Updating Rows Based on Another Table
11

 Use subqueries in UPDATE statements to update


 rows in a table based on values from another table.
DELETE Statement
12

 Remove exiting rows from a table using DELETE


statement.

DELETE [FROM] tablename


[WHERE condition(s)];

Note:
All rows are deleted in a table if WHERE clause is not
used.
Deleting Rows Based on Another Table
13

 Use subqueries in DELETE statements to remove


 rows from a table based on values from another
table
Database Transitions 6
14

 Consist of one of the following statements:


 DML statements that make up one consistent

change to the data.


 One DDL statement.

 One DCL statement.

6 Introduction to Oracle: SQL and PL/SQL P 9-24 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
Database Transactions(cont) 7
15

 Begin when the first executable SQL statement is


executed
 End with one of the following events:
 COMMIT or ROLLBACK is issued
 DDL or DCL statement executes(automatic commit)

 User exits

 System crashes

7 Introduction to Oracle: SQL and PL/SQL P 9-25 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
Advantage of COMMIT and ROLLBACK8
16

 Ensure data consistency


 Preview data changes before making changes
permanent
 Group logically related operations

8 Introduction to Oracle: SQL and PL/SQL P 9-26 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
Transaction Statements 9
17

 COMMIT
 Ends the current transaction by making all pending data
changes permanent
 SAVEPOINT name
 Marks a savepoint within the current transaction
 ROLLBACK [TO SAVEPOINT name]
 ROLLBACK ends the current transaction by discarding
all pending data changes.
 ROLLBACK TO SAVEPOINT rolls back the current
transaction to the specific savepoint.
9 Introduction to Oracle: SQL and PL/SQL P 9-27 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
Implicit Transaction Processing 10
18

 An automatic commit occurs under the following


circumstances:
 DDL statement is issued
 DCL statement is issued.

 Normal exit from application without explicitly issuing


COMMIT or ROLLBACK.
 An automatic rollback occurs under an abnormal
termination of application or system failure.

10 Introduction to Oracle: SQL and PL/SQL P 9-28 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
State of the Data Before COMMIT
19
or ROLLBACK11
 The previous state of the data can be recovered.
 The current user can review the results of the DML
operations by using the SELECT statement.
 Other users cannot view the results of the DML
statements by the current user.
 The affected rows are locked, other users can't
change the data within the affected rows.

11 Introduction to Oracle: SQL and PL/SQL P 9-29 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
State of the Data After COMMIT 12
20

 Data changes are made permanent in the


database.
 The pervious state of the data is permanently lost.
 All users can view the results.
 Locks on the affected rows are released, those rows
are available for other users to manipulate
 All savepoints are erased.

12 Introduction to Oracle: SQL and PL/SQL P 9-30 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
State of the Data After ROLLBACK 13
21

 Discard all pending changes by using the


ROLLBACK statement.
 Data changes are undone.
 Previous state of the data is restored.

 Locks on the affected rows are released.

13 Introduction to Oracle: SQL and PL/SQL P 9-32 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
Questions
22

 Question4
Write an SQL statement to add the following
information of employee.
ID: 208
First Name: Rami
Last Name: Sameer
Email: RamiSameer
Hire Date: Current Date
Job ID: SH_CLERK
Salary: $1800
Questions
23

Make a permanent change on pervious action

Delete job history for employee 122.

Modify the location id for department 30 to be 1700.

Add the following department which has the following


information
ID: 300
Name: Auditing
Location ID: 2500
Questions
24

Rollback the pervious changes and notice the changes


before and after rollback.
DATABASE LAB
Lab1: Introduction
Basic Select Statement

Ruba Sultan
DEFINITIONS

 Database:is an organized collection of


information.

 Database Management System (DBMS):


is a program that stores, retrieves and
modifies data in database.

 StructuredQuery Language (SQL): is a


language used to access and modify data
in database. 2
DBMS

 DBMS that will be used Oracle 10g Express


Edition

 SQL *Plus is an SQL editor used to write SQL


statements and it’s included in Oracle
Database package.

3
SQL STATEMENTS

Data Retrieval SELECT


Data Manipulation Language (DML) INSERT
UPDATE
DELETE
Data Definition Language (DDL) CREATE
ALTER
DROP
TRUNCATE
RENAME
Data Control Language (DCL) GRANT
REVOKE
Transaction COMMIT
ROLLBACK 4

SAVEPOINT
PROCEDURES TO USE SAMPLE TABLES
Logging in as the Database Administrator2
 The first thing you need to do is to log in as the Oracle
Database XE Administrator.
 Follow these steps:
 Open the Database Home Page login window:
 On Windows, from the Start menu, select Programs (or All
Programs), then Oracle Database 10g Express Edition, and then
Go To Database Home Page2.
 At the Database Home Page login window, enter the following

information2:
 Username: Enter system for the user name.

 Password: Enter the password that was specified when Oracle


Database XE was installed. 5
PROCEDURES TO USE SAMPLE TABLES

6
PROCEDURES TO USE SAMPLE TABLES
Unlocking the Sample User Account2
 To unlock the sample user account:
 Make sure you are still logged on as the database
administrator.
 Click the Administration icon, and then click
Database Users2.
 Click the HR schema icon to display the user
information for HR.

7
8
PROCEDURES TO USE SAMPLE TABLES
 Under Manage Database User, enter the
following settings2:
 Password and Confirm Password.
 Account Status: Select Unlocked.
 Roles: Ensure that both CONNECT and
RESOURCE are enabled.
 Directly Granted System Privileges: Check them all.

 Click Alter User.

9
PROCEDURES TO USE SAMPLE TABLES

5-Click on Alter User

1-Set a password for HR


schema

2-Set a Account Status to


Unlocked

3-Enable both
CONNECT and
RESOURCE roles
10
4-Check all Directly
Granted System
Privileges
DEMONSTRATION TABLES

 There are different tables that will used in this lab:

 COUNTRIES

 DEPARTMENTS

 EMPLOYEES

 JOBS

 JOB_HISTORY

 LOCATIONS

11
DATA RETRIEVAL

 SELECT statement capabilities3:


 Selection
 Projection

 Join

 Basic SELECT Statement4


SELECT [DISTINCT] {*,column [alias],…}
FROM tablename;

12
3 Introduction to Oracle: SQL and PL/SQL P1-3 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
4 Introduction to Oracle: SQL and PL/SQL P1-4 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
QUESTIONS

 Question1
Write a query to display all employee’s
information.
 Question2
Write a query to display all department’s
information.
 Question3
Write a query to display all department’s
names and their location.
 Question4
Write a query to display all information in
JOB_HISTORY table. 13
ARITHMETIC OPERATORS
Operato Description Operat Precedenc
r or e
+ Addition () High
- Subtraction
/ *
* Multiplicati
on + - Low
/ Division
 Arithmetic operations can be used with both
NUMBER and DATE data types. 14
QUESTIONS

 Question5
Write a query to display all employee’s names
and their salaries and their annual salaries.

 Question6
Modify the previous query where each
employee gets $100 bonus for each month.

 Question7
Write a query to display all employee’s
numbers, names and their annual income.
15
NULL VALUE

 Null: is a value that is unavailable,


unassigned, unknown or inapplicable, and it
is not same as zero or blank space5.

 Arithmetic expressions containing Null value


evaluated to Null6.

16
5 Introduction to Oracle: SQL and PL/SQL P1-14 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
6 Introduction to Oracle: SQL and PL/SQL P1-15 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
COLUMN ALIAS

 Rename column heading7.


 Immediately follows column name, use AS keyword
between column name and alias7.
 Requires double quotation if contains spaces or special
characters or case sensitive7.

 Question8
Write a query to display all employee’s numbers,
names and their annual income
Note: use appropriate column heading.

17

7 Introduction to Oracle: SQL and PL/SQL P1-16 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
CONCATENATION OPERATOR ||

 Concatenate a columns or a character strings to


other columns the result will be in one column.
 Use two vertical bars || for concatenation.

 Question9
Write a query to display all employee’s names and
their jobs.
Note: format must be as the following example

CLARK is a MANAGER 18
DISTINCT KEYWORD

 Used to eliminate duplicate rows8


 Used after SELECT statement8.

 Question10
Write a query to display all job positions in
EMPLOYEES table.

19

8 Introduction to Oracle: SQL and PL/SQL P1-23 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
DISPLAY TABLE STRUCTURE

 Using DESCRIBE command.

DESC[RIBE] tablename

 Question11
Display table structure for EMPLOYEES and
DEPTARTMENTS tables.

20
ASSIGNMENT 1

 List at least ten different DBMS.


 List different versions of Oracle DBMS.

 Write a query to display all data from emp table,


separate each column by comma.
Note: use appropriate column heading.

21
SELECTION

 Restricting Row using WHERE clause9

SELECT [DISTINCT] {*,column [alias],…}


FROM tablename
WHERE condition(s);9

22

9 Introduction to Oracle: SQL and PL/SQL P2-4Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
CHARACTER STRING AND DATES

 Character string and date values enclosed in single


quotation10.
 Character values are case sensitive and date values are
format sensitive10.
 Default Date format is DD-MON-YY10.

23

10 Introduction to Oracle: SQL and PL/SQL P2-6 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
COMPARISON OPERATORS
Operator Description
= Equal to
<> or != Not Equal to
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
24
QUESTIONS

 Question12
Write a query to display all employee’s information
whose salary $2800 or more and less than or equal
$3500.

 Question13
Write a query to display all employee’s information
whose job FI_MGR.

25
MORE COMPARISON OPERATOR

Operator Meaning
BETWEEN …AND… Between two values(inclusive)

IN Match value in a list of values

LIKE Match character pattern

IS NULL Is NULL value

26

This Table form


Introduction to Oracle: SQL and PL/SQL P2-6 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
QUESTIONS

 Question14
Write a query to display all employee’s
information whose salary $2800 or more and less
than or equal $3500.

 Question15
Write a query to display employee’s numbers,
names and salaries whose salary $800 or $3000
or $5000. 27
USING LIKE OPERATOR12

 Use the LIKE operator to perform wildcard


searches of valid search string values.
 Search conditions can contain either literal
characters or numbers.
% denotes zero to many character.
 _ denotes one character

28

12 Introduction to Oracle: SQL and PL/SQL P2-12 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
QUESTIONS

 Question16
Write a query to display all employee’s
information for employees whose names
contain letter A.

 Question17
Write a query to display all employee’s
information for employees whose names
contain letter A and contain four letters.
29
LOGICAL OPERATOR

Operat Operato
Description Precedence
or r
NOT Returns True if
NOT High
condition is False

AND Returns True if both


AND
conditions
evaluated True
Low
OR Returns True if one of
OR
conditions
30
evaluated True
QUESTIONS
 Question18
Write a query to display names, jobs and
salaries for employees who get more than
$2650 and their job IT_PROG.
 Question19
Write a query to display names, jobs and
salaries for employees who do not get $800,
$3000 or $5000.
 Question20
Write a query to display all employee’s
information for employees who have known 31

commission.
SORTING
 Sorting rows can be implemented using
ORDER BY clause

 There are two options:


 ASC: ascending order, default13

 DESC: descending order13

 The ORDER BY clause comes last in the


SELECT statement13. 32

13 Introduction to Oracle: SQL and PL/SQL P2-22 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
QUESTIONS
 Question21
Write a query to display all employee’s
information, sort output according to hire date
form most recently hired to least hire date.

 Question22
Write a query to display all employee’s names
and their annual income sort output according
to annual income in ascending.

33
DATABASE LAB
Lab2: SQL Functions

Ruba Sultan
SQL FUNCTIONS
 Functions are a very powerful feature of SQL can
be used to do the following:

 Perform calculations on data


 Modify individual data items
 Manipulate output for groups of rows
 Format dates and numbers for display
 Convert column data types

2
TWO TYPES OF SQL FUNCTIONS2

 There are two distinct types of SQL Functions


Single Row Function (SRF)
Multiple Row Function (MRF)

2 Introduction to Oracle: SQL and PL/SQL P3-4. Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
SINGLE ROW FUNCTION

 Single Row Function Categories3

Character Functions
Number Functions

Date Functions

Conversion Functions

General Functions

3 Introduction to Oracle: SQL and PL/SQL P3-6 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
CHARACTER FUNCTIONS4

4 Introduction to Oracle: SQL and PL/SQL P3-7 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
CHARACTER FUNCTIONS

Character Functions
LOWER (column | expression)
UPPER (column | expression)
INITCAP (column | expression)
CONCAT(column1|expression1,column2|expression2)
SUBSTR (column , m ,[n])
LENGTH (column | expression)
INSTR (column | expression , m)
6

LPAD (column , n , ‘string’)


QUESTIONS

 Question1
Write a query to display all employee’s names and
their jobs.
Note: format must be as the following example

Blake is a manager
 Question2
Write a query to display first name and three letters
of last name for all employees in department 90.

7
QUESTIONS

 Question3
Write a query to display last three letters of
employee’s names.

 Question4
Write a query to display all employee’s information
whose their names contain 4 letters.

8
NUMBER FUNCTIONS

Number Functions
ROUND (column | expression , n)
TRUNC (column | expression , n)
MOD (m , n)

9
EXAMPLES

SELECT
ROUND(65.723,2) , ROUND(65.723),
ROUND(65.723,-1), ROUND(65.723,-2)
FROM dual;

SELECT
TRUNC(65.723,2) , TRUNC(65.723),
TRUNC(65.723,-1), TRUNC(65.723,-2)
FROM dual;
10
DUAL TABLE

 DUAL table owned by the user SYSTEM and can be


accessed by all users5.
 It contains one column DUMMY and one row with the
value X5.
 The DUAL table is useful when you want to return a
value once only5.
 It can be used to test function on expressions.

 It can be used to display current date using


SYSDATE.

11

5 Introduction to Oracle: SQL and PL/SQL P3-17 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
ARITHMETIC WITH DATES6
 Add or subtract a number to or from a date for a
resultant date value.
 Subtract two dates to find the number of days
between those dates.
 Add hours to a date by dividing the number of hours
by 24.

Operation Result Description


date + number Date Adds a number of days to a date
date - number Date Subtracts a number of days from a date
date - date Number of days Subtracts one date from another
date + number/24 Date Adds a number of hours to a12date
QUESTIONS
 Question5
Write a query to display employee's name,
numbers and the number of weeks employed for
all employees who earns more than $5750.

13
DATE FUNCTIONS

Date Functions
MONTHS_BETWEEN (date1,date2)
ADD_MONTHS (date ,n)
NEXT_DAY( date, ‘char’)
LAST_DAY (date)

 The default date format DD-MON-YY7


 SYSDATE is a function returning date and time.

14
QUESTIONS

 Question6
Write a query to display the date of the first FRIDAY.

 Question7
Write a query to display your age in months.

 Question8
Write a query to display last date of the current
month.

15
GENERAL FUNCTIONS

 NVL Function
 U sed to converts NULL into actual values.
 NVL (column | expression , expression)

 Question9
Write a query to display employee’s first names and
their annual income.

Note: For employees who have unknown commission


consider it to be 0.

16
GENERAL FUNCTIONS (CONT.)

 DECODE Function
 It has similar capability as CASE or IF ELSE statements.
 DECODE syntax

DECODE (column | expression ,


search1 , result1,
search2 , result2,….,
default)

17
GENERAL FUNCTIONS (CONT.)

 Question10
Write a query to display all employee’s names, their
salaries, and situation.
Note: situation of employee known form salary value.

Salary Situation
800 Low
3000 Moderate

5000 High
18

Otherwise Unknown
QUESTIONS
 Question11
List ten functions other than listed in the
slides. Gives an example of each one.

19
JOIN
 Join types
 Equijoin
 Non – Equijoin
 Outer Join
 Self Join
 To join n tables together you need a minimum of (n-1)
join conditions.
 Are used to obtain data from more than one table.
 If the same column appears in more than one table, the
column name must be prefixed with the table name.

20
CARTESIAN PRODUCT9
 Cartesian product formed when
 Join condition is omitted
 Join condition is invalid
 To avoid a Cartesian product, always include a valid
join condition in a WHERE clause.

21
EQUIJOIN
 Also called simple joins or inner joins.

SELECT
e.first_name,d.department_id,d.department_name

FROM employees e, deptartments d

WHERE e.department_id=d.department_id;

22
EQUIJOIN

Notes:
• Use table prefixes to qualify column names that
are in multiple tables.
• improve performance by using table prefixes.
• distinguish columns that have identical names
but reside in different tables by using column
aliases.

23
QUESTIONS
 Question12
Write a query to display all employee’s first
names, their department’s names and their
job title for all employees in department 30
and 80.

24
OUTER JOIN
SELECT table1.column,table2.column
FROM table1 , table2
WHERE table1.column = table2.column(+)
Deficiency of Data
 Question13
Write a query to display employee’s first
names, their last names, departments
numbers, and names of their departments.

Note: 25
Include departments that have no employees
SELF JOIN
 This type occurs when join occurred to the table itself.

 Question13
Write a query to display employee’s numbers,
their names, their managers numbers and
their managers names.

26
DATABASE LAB
Lab3: Group Functions
and Subquery

Ruba Sultan
GROUP FUNCTIONS

 Group or Aggregate Functions:


SUM
AVG

MIN

MAX

COUNT

STDDEV

VARIANCE

2
QUESTIONS

 Question1
Write a query to display maximum and minimum
salaries for department 10 and 30.
 Question2
Write a query to display hire date for first hired
employee and hire date for the newest hired employee.

3
QUESTIONS

 Question3
Write a query to display total ,average, maximum and
minimum for the paid salaries.

 Question4
Write a query to display total ,average, maximum and
minimum for the paid commissions.

4
GROUP BY

SELECT column,….,aggregate func.


FROM table name
WHERE condition(s)
GROUP BY column1,..,column m
ORDER BY column1,..,column m

 Question5
Write a query to display the total paid salaries for
each department.

5
HAVING
 WHERE clause can only be used with non-aggregate
functions, it couldn’t be used with aggregate functions.
 HAVING clause used when there is a condition on
aggregate values.
SELECT column,….,aggregate func.
FROM table name
WHERE condition(s)
GROUP BY column1,..,column m
HAVING condition(s)
ORDER BY column1,..,column m
6
QUESTIONS

 Question6
Write a query to display the total paid salaries for
each department, exclude any departments that their
total salary less than $10000.
 Question7
State whether the following query valid or not
SELECT deptno,job,SUM(sal)
FROM emp
GROUP BY deptno;

7
QUESTIONS
 Question8
State whether the following query valid or not
SELECT deptno,SUM(sal)
FROM emp
GROUP BY deptno,job;

8
USING A SUBQUERY
TO SOLVE A PROBLEM

Who has a salary greater than Abel’s?

Main Query:

Which employees have salaries greater


?
than Abel’s salary?

Subquery
?
What is Abel’s salary?
SUBQUERY SYNTAX

SELECT column,….,aggregate func.


FROM table name
WHERE column comparison oper. Main or Outer Query
(SELECT column
FROM table name);

Subquery or Inner Query

10
SUBQUERIES

 Question9
Write a query to display all employee’s names, their
salaries and their job whose jobs same as job of
William Smith.

To solve this query


❑ Find the job of William Smith
❑ Then find all employee’s whose job is same as job found.

11
SUBQUERY SYNTAX
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);

The subquery (inner query) executes once before the 


main query.
The result of the subquery is used by the main query 
(outer query).
USING A SUBQUERY
SELECT last_name
11000 employees
FROM
WHERE salary >
(SELECT salary
FROM employees
WHERE last_name = 'Abel');
GUIDELINES FOR USING SUBQUERIES

 Enclose subqueries in parentheses.


 Place subqueries on the right side of the comparison
condition.
 The ORDER BY clause in the subquery is not needed
unless you are performing Top-N analysis.
 Use single-row operators with single-row subqueries
and use multiple-row operators with
multiple-row subqueries.
TYPES OF SUBQUERIES

• Single-row subquery
Main query
returns
Subquery ST_CLERK

• Multiple-row subquery
Main query
returns ST_CLERK
Subquery
SA_MAN
SINGLE-ROW SUBQUERIES

Return only one row 


Use single-row comparison operators 
Operator Meaning

= Equal to

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

<> Not equal to


EXECUTING SINGLE-ROW SUBQUERIES
SELECT last_name, job_id, salary
FROM employees
WHERE job_id =ST_CLERK
(SELECT job_id
FROM employees
WHERE employee_id = 141)
AND salary > 2600
(SELECT salary
FROM employees
WHERE employee_id = 143);
USING GROUP FUNCTIONS IN A SUBQUERY
SELECT last_name, job_id, salary
FROM employees2500
WHERE salary =
(SELECT MIN(salary)
FROM employees);
THE HAVING CLAUSE WITH SUBQUERIES

The Oracle server executes subqueries first. 


The Oracle server returns results into the HAVING 
clause of the main query.

SELECT department_id, MIN(salary)


FROM employees
GROUP BY department_id
2500
HAVING MIN(salary) >
(SELECT MIN(salary)
FROM employees
WHERE department_id = 50);
WHAT IS WRONG
WITH THIS STATEMENT?

SELECT employee_id, last_name


FROM employees
WHERE salary =
(SELECT MIN(salary)
FROM employees
GROUP BY department_id);

ERROR at line 4:
ORA-01427: single-row subquery returns more than
one row
WILL THIS STATEMENT RETURN ROWS?

SELECT last_name, job_id


FROM employees
WHERE job_id =
(SELECT job_id
FROM employees
WHERE last_name = 'Haas');

no rows selected
MULTIPLE-ROW SUBQUERIES

Return more than one row 


Use multiple-row comparison operators 
Operator Meaning

IN Equal to any member in the list

ANY Compare value to each value returned by


the subquery

Compare value to every value returned by


ALL
the subquery
USING THE ANY OPERATOR
IN MULTIPLE-ROW SUBQUERIES

SELECT employee_id, last_name, job_id, salary


FROM 9000,
employees
6000, 4200
WHERE salary < ANY
(SELECT salary
FROM employees
WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';


USING THE ALL OPERATOR
IN MULTIPLE-ROW SUBQUERIES

SELECT employee_id, last_name, job_id, salary


FROM employees
9000, 6000, 4200
WHERE salary < ALL
(SELECT salary
FROM employees
WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';
NULL VALUES IN A SUBQUERY

SELECT emp.last_name
FROM employees emp
WHERE emp.employee_id NOT IN
(SELECT mgr.manager_id
FROM employees mgr);

no rows selected
QUESTIONS
 Question10
Write a query to display all employees names, their
hire dates and their departments numbers that was
hired after Tayler Fox and get more than employee
184

 Question11
Write a query to display all employees information who
have the get maximum paid salary.

26
QUESTIONS
 Question12
Write a query to display departments and their
total paid salaries, exclude any department
that its total salary less than that of
department 30.
 Question13
State weather the following query is valid or not
SELECT empno , ename
FROM emp
WHERE sal = (SELECT MIN(sal)
FROM emp 27
GROUP BY deptno);
MULTIPLE ROW OPERATOR

Operator Description

IN Equal to any value

ALL Compare it to every value

ANY Compare it each value

28
QUESTIONS
 Question14
Write a query to display all employee’s
information whose less than any Stock Clerk
and they are not Stock Clerk.

 Question15
Write a query to display employee’s numbers,
names and their salaries for employees who
earn more than the average salary and who
work in department with any employee with a
letter T in their names. 29

You might also like