DBP Lab
DBP Lab
DBP Lab
Lab5
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.
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.
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] ...);
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.
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.
16
Dropping a Column
Use the DROP COLUMN clause to drop columns you no
longer need from the table.
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
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
19
DROP Statement
• All data and table structure will be deleted.
• It can not be rolled back.
• The syntax of DROP statement as following
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
1 Introduction to Oracle: SQL and PL/SQL P9-3 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
INSERT Statement 2
3
2 Introduction to Oracle: SQL and PL/SQL P9-5 Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
Inserting New Rows 3
4
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
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
UPDATE tablename
SET column=value[, column=value,…]
[WHERE condition(s)];
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
Note:
All rows are deleted in a table if WHERE clause is not
used.
Deleting Rows Based on Another Table
13
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
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
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
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
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
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
Ruba Sultan
DEFINITIONS
3
SQL STATEMENTS
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.
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.
9
PROCEDURES TO USE SAMPLE TABLES
3-Enable both
CONNECT and
RESOURCE roles
10
4-Check all Directly
Granted System
Privileges
DEMONSTRATION TABLES
COUNTRIES
DEPARTMENTS
EMPLOYEES
JOBS
JOB_HISTORY
LOCATIONS
11
DATA RETRIEVAL
Join
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
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
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 ||
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
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
DESC[RIBE] tablename
Question11
Display table structure for EMPLOYEES and
DEPTARTMENTS tables.
20
ASSIGNMENT 1
21
SELECTION
22
9 Introduction to Oracle: SQL and PL/SQL P2-4Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
CHARACTER STRING AND DATES
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)
26
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
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
commission.
SORTING
Sorting rows can be implemented using
ORDER BY clause
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:
2
TWO TYPES OF SQL FUNCTIONS2
2 Introduction to Oracle: SQL and PL/SQL P3-4. Neena Kochhar, Ellen Gravina and Priya Nathan, July 1999
SINGLE ROW FUNCTION
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
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
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.
13
DATE FUNCTIONS
Date Functions
MONTHS_BETWEEN (date1,date2)
ADD_MONTHS (date ,n)
NEXT_DAY( date, ‘char’)
LAST_DAY (date)
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.
16
GENERAL FUNCTIONS (CONT.)
DECODE Function
It has similar capability as CASE or IF ELSE statements.
DECODE syntax
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
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
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
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
Main Query:
Subquery
?
What is Abel’s salary?
SUBQUERY SYNTAX
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.
11
SUBQUERY SYNTAX
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
• Single-row subquery
Main query
returns
Subquery ST_CLERK
• Multiple-row subquery
Main query
returns ST_CLERK
Subquery
SA_MAN
SINGLE-ROW SUBQUERIES
= Equal to
ERROR at line 4:
ORA-01427: single-row subquery returns more than
one row
WILL THIS STATEMENT RETURN ROWS?
no rows selected
MULTIPLE-ROW SUBQUERIES
…
USING THE ALL OPERATOR
IN MULTIPLE-ROW SUBQUERIES
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
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