0% found this document useful (0 votes)
158 views34 pages

DBWorksheet Update

The document provides instructions for logging into the HR user in Oracle 11g and 18c databases and performing basic tasks. It explains how to unlock the HR account in Oracle 11g by connecting as the system user and running an ALTER command. It then links to YouTube videos showing how to install Oracle 18c and unlock the HR database. The document concludes with exercises to display table names and column descriptions, check the number of records in a table, and display the system date.

Uploaded by

Lara AbuDayeh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
158 views34 pages

DBWorksheet Update

The document provides instructions for logging into the HR user in Oracle 11g and 18c databases and performing basic tasks. It explains how to unlock the HR account in Oracle 11g by connecting as the system user and running an ALTER command. It then links to YouTube videos showing how to install Oracle 18c and unlock the HR database. The document concludes with exercises to display table names and column descriptions, check the number of records in a table, and display the system date.

Uploaded by

Lara AbuDayeh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Department of Computer Information System

Introduction to Database Lab


‫مختبر مقدمة في نظم قواعد البيانات‬
(151002241)

1
 Login into HR user in ORACLE 11g
In order to login in, you need to unlock HR account by performing the following process for the
first time only>>>>>>
1- Connect to system account.
2- insert the following command “Alter user HR identified by HR account unlock;”
3- connect to Hr account with password HR.

 Login into HR user in ORACLE 18C


Please watch the following videos to install ORACLE 18c and to unlock hr
database.
1- ‫طريقة تنزيل برمجية اوراكل‬18c
https://www.youtube.com/watch?v=YnDgQX4lK-
A&list=PL2haDau_5PYtR9mTjnDGCqGaIWlYY6vUC&index=3

2-‫ تشغيل برنامج‬sql developer ‫ وربطه مع برمجية‬oracle 18c


https://www.youtube.com/watch?v=jvGdCthuL3I&list=PL2haDau_5PYtR9mTjn
DGCqGaIWlYY6vUC&index=4

2
Login to hr account in SQL plus

Login to hr account in SQL Developer


1

3
Exercise:

 Display all tables names in HR account.


Select * from tab;
 Display columns names for table employees.
Describe employees;
 How many records are in table employees?
 Display system date (from dual table).

4
Database Lab Worksheet 1

Data Definition Language (DDL) : as a standard for commands through which data structures
are defined. It is a computer language that is used for creating and modifying structure of the
database objects, such as schemas, tables, views, indexes…etc
DDL for tables:
 The SQL create table statements.
 The SQL alter table statements.
 The SQL drop table statement.

1) The create table statement

CREATE TABLE table_name


(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
column_name3 data_type
);

SQL Data Types:

VARCHAR(size), VARCHAR2(size) : hold string with size characters


DATE : Stores a date like June 30, 1991
NUMBER (size) : Store an integer value
Number(percistion,scale): store a double value

Create Table - By Copying selected columns from another table


The syntax for the CREATE TABLE AS statement that copies the selected columns in
Oracle/PLSQL is:

CREATE TABLE new_table AS (SELECT column_1, column2, ... column_n FROM old_table);

5
2) The SQL ALTER TABLE Statement
1)ADD COLUMN IN TABLE

To add a column in a table, the SQL ALTER TABLE syntax is:

ALTER TABLE table_name ADD column_name column-Datatype;

2)ADD MULTIPLE COLUMNS IN TABLE

To add multiple columns to an existing table, the SQL ALTER TABLE syntax is:

ALTER TABLE table_name


ADD (column_1 column-definition,
column_2 column-definition,
...
column_n column_definition);

3)MODIFY COLUMN IN TABLE

To modify a columns’ data type in an existing table, the SQL ALTER TABLE syntax is:

ALTER TABLE table_name MODIFY column_name column_type;

4)MODIFY MULTIPLE COLUMNS IN TABLE

To modify multiple columns(Data Type) in an existing table, the SQL ALTER TABLE syntax is:

ALTER TABLE table_name


MODIFY (column_1 column_type,
column_2 column_type,
...
column_n column_type);

6
5)DROP COLUMN IN TABLE
To drop a column in an existing table, the SQL ALTER TABLE syntax is:

ALTER TABLE table_name DROP COLUMN column_name;

6)RENAME COLUMN IN TABLE

To rename a column in an existing table, the SQL ALTER TABLE syntax is:

ALTER TABLE table_name RENAME COLUMN old_name to new_name;

7)RENAME TABLE
To rename a table, the SQL ALTER TABLE syntax is:

ALTER TABLE table_name RENAME TO new_table_name;

3)The SQL DROP TABLE Statement

DROP TABLE table_name ;

Exercise 1:
Based on the DDL SQL commands, Answer the following Questions:
Q1. Write a query to create a table employee with empno, ename, job, and salary.
CREATE TABLE employee (EMPNO NUMBER (4), ENAME VARCHAR2 (10), job VARCHAR2 (10),
SALARY NUMBER (8,2));
Q2. Write a query to create a new table called emp1 from an existing table emp with all the
fields.

Q3. Write a Query to change the size of column EMPNO in employee from NUMBER(4) TO
NUMBER(6).

Q4. Write a query to add a new column called QUALIFICATION to employee table of type string
20.
Q5. Write a query to drop a column job from an existing table employee.
Q6. Write a query to drop an existing table employee.
7
Exercise 2:

Consider the following table and answer the following Questions:

CREATE TABLE customer


( customer_id number(10),
customer_name varchar(50),
address varchar(50),
city varchar(50) );

A) Add two columns, phone as a varchar(12) and email as a varchar (20 ) to the customer
table.
B) Rename the customer_id column to id.
C) Rename the customer table to custom.
D) Drop the city column.
E) Change the data type of phone column to number(10).

8
Data Manipulation Language(DML) Commands
SQL statements that can be used to manipulate data in tables and views.
1- INSERT: The INSERT INTO statement is used to insert a new row in a table.
Syntax:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

Hint: in case we want to insert an entire row data, there is no need to write column
names.
2- UPDATE: the UPDATE statement is used to change and replace existing data in a table.
Syntax:
UPDATE table_name SET column1=value, column2=value2,... WHERE
some_column=some_value;

Hint: The following (UPDATE table_name SET column1=value;) store the same value in
all records of column1.
3- DELETE: The DELETE statement is used to delete rows in a table.
Syntax:
DELETE FROM table_name WHERE some_column=some_value;

4- SELECT: the SELECT statement is used to select data from a database.


Syntax:
SELECT column_name(s) FROM table_name;

WHERE Clause: The WHERE clause is used to extract only those records that fulfill a
specified criterion.
Syntax:
SELECT column_name(s) FROM table_name WHERE column_name operator value;

Basic Operator Description


= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal

9
Exercise3:

Create a folder with your ID number on the desktop, and do the following:
1. Create a table courses with the following properties:
a. Id_number, with 8 numeric digits.
b. St_Name, with 15 character string.
c. Course_name with 15 character string.
d. Department, with 3 character string.
e. Bdate, date type.
f. Mark, with 3 numeric digits.

2. Insert the following data to courses table:


Id_number St_Name Course_name Department Bdatee Mark
11 ALi DB CSA 14-2-2013 70
22 Ahmad DB CIS 15-3-2012 40
33 Muna VP SWE 11-4-2012 90

3. Modify the courses table by adding the following columns:


a. Gpa, with 5 numeric digits size, 2 decimal points.
b. Flag, with 1 digit number.

4. Modify the courses table by delete gpa column.

5. Create table new_courses from the table courses.

6. Delete the table new_courses from your Database.

7. Display all data contains in courses table.

8. Delete all data of id_number =11.

9. Write and run the suitable SQL command to display only st_name and mark for all
students on courses table.

10. Put the value 1 in flag column for all students in courses table .

11. Write and run the suitable SQL command to display only id_number, st_name, bdate,
and mark for all students on CIS department.

10
Database lab Worksheet 2

Operators in select statement


Alias Names : is the process of renaming a column(s) temporarily by giving another name .
Syntax:
SELECT column_name as alias_name FROM table_name;
OR
SELECT column_name “ alias_name” FROM table_name

Concatenation Operator || : Concatenates character strings.


Example:
SELECT first_name ||’ ‘ || last_name as “Full name” FROM employees;

Arithmetic operators are used to perform mathematical functions in SQL—the same as in most
other languages. There are four conventional operators for mathematical functions:
 + (addition)
 - (subtraction)
 * (multiplication)
 / (division)

Example:
SELECT salary, salary*12 “ annual salary” FROM employees;

DISTINCT keyword :is used to return only distinct (different) values.

Syntax:
SELECT DISTINCT column1 FROM table_name ;

Exercise 1: use( employees table in hr)


1) Write a query to display employee id, first name, hire Date for all employees. Name the
column headings : EMP#, EMPLOYEE and StartDate .

2) Write a query to display first name, job id for all employees. Display the first name
concatenated with the job id( separated by comma and space)and name the column
Employee and Title.
11
3) Write a query to display first name, last name and a column called ” Total income” for all
employees. Total income is calculated by multiplying monthly salary with 12, plus onetime
bonus $100.

4) Write a query to display job id without duplicated rows.

SELECT and WHERE Clause: The WHERE clause is used to extract only those records that
fulfill a specified criterion.
Syntax:
SELECT column_name(s) FROM table_name WHERE column_name operator value;

Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN To specify multiple possible values for a column

BETWEEN operator: is used to select a range. The syntax for the BETWEEN operator is as
follows:
SELECT column1, column2,…. FROM table_name WHERE column_name between value1 and
value2;

IN operator: is used to select one or more of the values in parenthesis.


The syntax for using the IN keyword is as follows:
SELECT column1, column2, …. FROM table_name WHERE column_name IN (value1
,value2,….);

12
Like operator: is used to compare a value to similar values using wildcard operators. There are two
wildcards used:
1) The percent sign (%)represents zero, one, or multiple characters
2) The underscore (_) represents a single number or character.

Syntax:
SELECT column1, column2, …FROM table_name
WHERE column_name LIKE ‘ pattern’;

Exercise 2: use( employees table in hr)


1) Write a query to display first name, last name and hire date for all employees who were
hired before 07-03-2006.

2) Write a query to display employee id, first name, hire date for all employees who joined
Between January, 2002 and December, 2002.

3) Write a query to display the first name, last name and salary for all employees whose
salary is between $2,500 and $3,500.

4) Write a query to display employee id, first name, last name, salary and manager’s
employee number for all employees whose manager’s employee number is 100, 101 or
201.

5) Write a query to display employee id, first name, last name, and Department id for all
employees whose last name is included in the following list of name [ Hartstein, Vargas,
Hunold ].

6) Write a query to display last name, job id for all employees whose Job id is not in
[IT_PROG, ST_CLERK, SA_REP].

7) Write a query to display employee id, first name, last name for all employees whose last
name have the letter "o" as the second character .

8) Write a query to display employee id, first name, last name for all employees whose first
name begins with the letter "O" .

13
The SQL AND, OR and NOT Operators
The WHERE clause can be combined with AND, OR, and NOT operators that help to include two
or more conditions.

Exercise 3: use( employees table in hr)

1) Write a query to display employee id, first name, last name for all employees who have a
job title contains the string 'MAN' and earn 1000$ or more.

2) Write a query to display employee id, first name, job id for all employees who have a job
title contains the string 'MAN' or earn 1000$ or more.

3) Write a query to display employee id, first name, job if employee job is (AD_PRES) or
(SA_REP), and if employee salary is more than 15000$.

The SQL ORDER BY Keyword: is used to sort the result-set in ascending or descending
order. The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword. ORDER BY is written at the end of the
command statement followed by column name.

Exercise 4: use( employees table in hr)

1) Write a query to display employee id, first name and department id. The result should
be sorted by department id in descending order.

2) Write a query to display employee id, first name and department id. Order the query in
ascending alphabetical order by first name.

14
Exercise 5: use( employees table in hr)

1) Write a query in SQL to display the details of the employees who have salary within the
range 7000 to 12000 and works in department number is 50.

2) Write a query in SQL to display the employee ID, first name, job id, and department
number for those employees who is working except the departments 50,30 and 80.

3) Write a query in SQL to display the first and last name, and department number for
those employees who holds a letter ‘s’ as a 3rd character in their first name.

4) Write a query in SQL to display the full name (first name and last name), hire date,
commission percentage, email and telephone separated by '-', and salary for those
employees who earn the salary above 11000 or the seventh digit in their phone number
equals 3 and make the result set in a descending order based on first name.

5) Write a query in SQL to display the full name (first and last), job id and date of hire for
those employees who were hired during March 5th, 2004 and July 5th, 2005.

6) Write a query in SQL to display the full name (first and last) name, and salary, for all
employees whose salary is out of the range 7000 and 15000 and make the result set in
ascending order by the first name.

7) Write a query in SQL to display all the information for all employees who have the
letters D, S, or N in their first name and also arrange the result in descending order by
salary.

15
Database Lab Worksheet 3

SQL NULL is the term used to represent a missing value. A NULL value in a table is a value in a
field that appears to be blank. We use the IS NULL and IS NOT NULL operators to check if a field
is blank or not.

SQL NULL Functions:


1- NVL(exp1,exp2): The NVL function permits you to replace all null values with a default value.
It requires two parameter values first value is column name and second is any default value.
If the value in the first parameter is NULL, then the function returns the value in the second
parameter. If the first parameter is any value other than null, it returns unchanged value.

2- NVL2(EXP1,EXP2,EXP3):If the first column value is not null then it returns the value of the
second column. If the first column value is null then it returns the value of third column.

3- NULLIF(EXP1,EXP2): It compares expr1 and expr2. If expr1 and expr2 are equal, the NULLIF
function returns NULL. Otherwise, it returns expr1.

Example: Run this command and study the results


select employee_id ,nvl (commission_pct,0), nvl2 (commission_pct, 10, 0), nullif(salary,9000)
from employees;

Exercise1: (From employees table).

1)Write a query to display last name, job id, commission for all employees who are not entitled
to receive a commission.

2)Write a query to display last name, commission for all employees. If the employee does not
receive a commission show 0 value instead of blank.

3)Write a query that returns salary if commission is null, otherwise it would return the result of
summation of salary and commission. Name new column (income).

4)Write a query to display employee id, salary, commission_pct and a column called New Salary.
New Salary is calculated by multiplying monthly salary with 12, plus multiplying commission_pct
with salary. (USE appropriate null function to get correct results)

16
SQL character functions:
1-Lower(string): is used to convert all characters of a string to lower case.
2-Upper(string) :is used to convert all characters of a string to uppercase.

3-INITCAP(string) function sets the first character in each word to uppercase and the rest to
lowercase.

4-SUBSTR (string,Position,length ) is used to return a portion of string. ** When length is not


specified, the entire string starting from the position-th character is returned.
5-LENGTH(string) function: returns the length of the specified string.
6-CONCAT(string1,string2) function: is used to concatenate two strings to form a single string.
7-REPLACE( string_expression , string_pattern , string_replacement ): In string_expression ,
find where string_pattern occurs, and replace it with string_replacement.

Example:
What is the output, after executing the following SQL commands?
1-SELECT LOWER (first_name) FROM employees WHERE First_Name = 'Alexander';
2- SELECT UPPER (first_name) FROM employees
WHERE upper(First_Name) = 'Alexander';

3-SELECT SUBSTR (First_name, 3) FROM employees WHERE First_Name = 'Alexander';

4-SELECT SUBSTR (First_name, 3,4) FROM employees WHERE First_Name = 'Alexander';

5-SELECT length( CONCAT (first_name,'**')) FROM employees


WHERE First_Name = 'Alexander';

6-SELECT REPLACE (first_name,'et','eee') FROM employees;

Exercise2: (From employees table).

1) Write a query to display employee_id, last name and department_id for employee who is last
name is higgins.Hint :- Do not use any character function .

2) Write a query to display employee_id, last name and department_id for employee higgins .
Hint :- use lower function.

17
3) Write a query to display employee_id, last name and department_id for employee
HIGGINS.Hint :- use upper function.

4) Write a query to display employee_id, last name and department_id for employee higgins.
Note :- use initcap function.

5) Write a query to display employee_id, first name and last name joined together (give
concatenated string suitable name), job ID, length of employee last name for all employees
who have REP, contained in the job ID starting at the fourth position of the job ID. Note :- use
concat function, length function and substr function

6) Write a query to retrieve last name, the first eight characters of last name and ‘_Us’ joined
together (the new column should be displayed in uppercase) for all employees who work in
department 60.

7) Write a query to display first name, the last name, length of the first name, length of the last
name, and the query should compare the length of first name and last name. When the
lengths of names are equal then the null value is displayed. Otherwise the length of first name
is displayed. Hint :- use NULLif function in appropriate way.

SQL Numeric functions:


We will study the following functions:
1)Mod(N,M):This function returns the remainder of N divided by M.
Example:
SELECT MOD(29,3) FROM dual;

2)ROUND(numeric value,[decimals]): is used to round a numeric field to the number of


decimals specified.
Example: What is the output?
SELECT ROUND (5.567, 2) FROM dual;
SELECT ROUND(55.67, -1) FROM dual;

3)TRUNC (numeric value, [decimals]): returns a number truncated to a certain number of


decimal places.
Example: What is the output?
SELECT TRUNC(125.815, 1) from dual;
SELECT TRUNC(125.815, -1) from dual;

18
Exercise3: (from dual table).

1) Write a query to round (45.239) to two decimal places.


2) Write a query to round (1045.239) to nearest thousands.
3) Write a query to round (45.239) to zero decimal places.
4) Write a query to truncate (45.239) to two decimal places.
5) Write a query to truncate (45.239) to zero decimal places.
6) Write a query to truncate (45.239) to one decimal places to the left.

The Oracle TO_CHAR() function: converts a DATE or INTERVAL value to a string in a


specified date format. The Oracle TO_CHAR() function is very useful for formatting the internal
date data returned by a query in a specific date format.
Syntax:
TO_CHAR(<date>, '<format>')
Format:
MM Numeric month (e.g., 07)
MON Abbreviated month name (e.g., JUL)
MONTH Full month name (e.g., JULY)
DD Day of month (e.g., 24)
DY Abbreviated name of day (e.g., FRI)
DAY Full name of day (e.g., FRIDAY)
YYYY 4-digit year (e.g., 1998)
YY Last 2 digits of the year (e.g., 98)
AM (or PM) Meridian indicator
HH Hour of day (1-12)
HH24 Hour of day (0-23)
MI Minute (0-59)
SS Second (0-59)

19
Example:
Select TO_CHAR(sysdate, 'yyyy/mm/dd') from dual;
Result: '2020/07/09'

Select TO_CHAR(sysdate, 'Month DD, YYYY') from dual;


Result: 'July 09, 2003'

Select TO_CHAR(sysdate, 'MON DDth, YYYY') from dual;


Result: 'JUL 09TH, 2003'

The Oracle TO_DATE() function: converts char of CHAR, VARCHAR2 datatype to a value
of DATE datatype.
Syntax:
TO_Date(<date>, '<format>')
where the <format> string has the same options as in TO_CHAR function.

Exercise4: (use employees table)

1- Write a query to display hire date as 17 of JUN2020 12:00:00 AM.


2- Write a query to show the hire date in years only for all employees.
3- Write a query to display all employees who were hired before the year 2003.
Hint: solve using to_char function/ resolve it using like operator.

4- Write a SQL command to insert the following row into employees table.

Employe First_nam Last_name Email Hire date Department_id JOB_ID


e_id e
2020 Ali Ali [email protected] 03.12/2012 50 ST_CLER
K

5- Write a query to display the length of employee’s first name, and the month( i.e. JULY) of hiring
for all employees whose first name length is larger than 5.

20
Database lab Worksheet 4

SQL Aggregate functions: Aggregate functions return a single value.

 SUM(column): calculates the sum of values.


 AVG (column): calculates the average of a set of values.
 COUNT (column): counts number of rows in a specified table.
 MIN(column): gets the minimum value in a set of values.
 MAX(column): gets the maximum value in a set of values.

Example:
What is the output, after executing the following SQL commands?
1-SELECT MIN(salary) FROM employees;

2-SELECT Max(salary) FROM employees;

3-SELECT count(*) FROM employees;

4-SELECT sum(salary) “total salaries of employees”, AVG(salary) “Average salaries in the


company” FROM employees;

Exercise 1: (From employees table).

1)Write a query to display the highest, lowest, sum and average salary for all employees. Label
the columns Maximum, Minimum, Sum, and Average respectively .

2)Write a query to display the number of employees whose job id contains the string 'REP'.

3)Write a query to display the number of employees work in department 80.

4)Write a query to display the number of department values in the employees table without
duplication.

5)Write a query to display number of employees who are not receiving a commission and were
hired in 2004.

21
GROUP BY clause: is used in collaboration with the SELECT statement to arrange identical
data into groups.The usage of SQL GROUP BY clause is, to divide the rows in a table into smaller
groups. When some rows are retrieved from a grouped result against some condition, that is
possible with HAVING clause. GROUP BY statement is often used with aggregate functions
Syntax
SELECT <column_list> FROM < table name > [WHERE] <condition>
GROUP BY <columns> [HAVING] <condition>;

Example:

1)Write a query to display department_id ,highest salary, lowest salary , sum of salary and
average of salary for each department.

Select department_id, max(salary),min(salary),sum(salary),avg(salary) from employees group


by department_id;

2)Write a query to display department number, maximum salaries for those departments with
a maximum salary greater than 10000$.

Select department_id, max(salary) from employees group by department_id having


max(salary)>10000;

Exercise 2: (From employees table).

1)Write a query to display job id and number of employees who are entitled in each job.

2)Write a query to display job id and number of employees in each job. Show only the jobs that
have more than 5 employees.

3)Write a query to display job id, total monthly salary for each job. Such that show all job id that
contain REP string, total monthly salary for each job that has a total more than 1300. The
output should be sorted descending by the total monthly salary.

22
A Subquery or Inner query or a Nested query: is a query within another SQL query and
embedded within the WHERE clause. A subquery is used to return data that will be used in the
main query as a condition to further restrict the data to be retrieved.

Example:
1)Write a query to display the employee ID, first name and job ID for all employees whose job
ID is the same as that of employee 141.

Select employee_id, job_id from employees


Where job_id = (select job_id from employees where employee_id=141);

Exercise3( from employees table)

1)Write a query to display the name ( first name and last name ) for all employees who gets
more salary than the employee id 163.

2)Write a query to display the employee last name, job ID and salary for all employees whose
salary is equal to minimum salary.

3)Write a query to display department ID, minimum salary for each department that have
minimum salary greater than that of department 50.

4)Write a query to display all information of last hired employee.


Hint: use appropriate aggregation function and use column employee_id.

5)Write a query to display the employee id, employee name (first name and last name ) for all
employees who earn more than the average salary.

23
Database lab Worksheet 5

The UNION operator is used to combine the result-set of two or more SELECT statements.

Notice that each SELECT statement within the UNION must have:
 The same number of columns.
 The columns must also have similar data types.
 The columns in each SELECT statement must be in the same order.

Syntax:
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

Example:
SELECT first_name FROM employess UNION SELECT last_name FROM employees;

Exercise1:

1)Write a query to display employee id, first name for all employees with employee id between
140 and 150. And department id and department Name for all departments together in one
column.

2)Write a query to display employee id, first name for all employees who work in department
10. And show department id and department name for all departments above 50.

3) Write a query to display the maximum salary for all employees. And the minimum salary for
all employees. Show the results in new column called” MAX and MIN”.

24
CROSS JOIN produces a result set which is the number of rows in the first table multiplied by
the number of rows in the second table if no WHERE clause is used along with CROSS JOIN. This
kind of result is called as Cartesian Product.
Suppose, the A table has N rows and B table has M rows, the CROSS JOIN of these two tables will
produce a result set that contains NxM rows.
Example:

SELECT * FROM A, B;

1) Write a query to display employee id, first name, department id, and department name
for all employees. (From employees and departments tables).

Equi join returns the matching column values of the associated tables. It uses a comparison
operator in the WHERE clause to refer equality.
To remove duplicated rows WHERE clause is used along with CROSS JOIN.
Syntax:

SELECT * FROM A, B where A.id = B.id;


Hint: id column is primary key in table A and foreign key in table B.

Example:

1)Write a query in SQL to display the first name, last name, department number and
department name, for all employees for departments 80 or 40.

SELECT first_name,last_name,departments.department_id,department_name FROM


employees, departments WHERE departments.department_id= employees.department_id
AND departments.department_id in(40,80);

Exercise2: (From employees and departments tables).

1)Write a query to display employee id, first name, department id, and department name for all
employees. (Without duplication)

2) Write a query in SQL to display department name and the full name (first and last name) of
the manager.

3)Write a query Write a query to display department name, number of employees, maximum
salary, minimum salary for each departments with more than 4 employees.

25
4)Write a query to display department name, number of employees for each departments and
the total number of all departments. Hint: use union.

5)Write a query in SQL to display job title, full name (first and last name ) of employees, and the
difference between maximum salary for the job and salary of the employee.(From employees
and Jobs tables)

Table Constraints:

constraint Description Example Example Example Example


(Create) (modify) (add) (drop)
This constraint create table Alter table
NOT NULL confirms that a student ( student
column cannot id number(3) Modify name
store NULL not null, varchar(3)
value. name not null;
varchar(10), To remove
mark not null
number(4) constraint:
); Alter table
student
Modify name
varchar(3)
null;
This constraint create table Alter table
DEFAULT prevents two student ( student
records from id number(3) Modify name
having , varchar(3)
identical name default 50;
values in a varchar(10), To remove
particular mark default
column. number(4) constraint:
default 50 ); Alter table
student
Modify mark
number(4)
default null;
This constraint create table Alter table Alter table student Alter table
UNIQUE ensures that student ( student Add constraint student
each rows for id Modify myuniquec drop
a column must number(3) id number(3) unique(id); constraint
have different unique, unique ; Or myuniquec ;
value. name ALTER table Stud
varchar(10), ent add UNIQUE(
mark id);
number(4));

26
Primary key create table Alter table student Alter table
PRIMARY constraint student ( Add constraint student
uniquely id mypkc primary drop
KEY identifies number(3) key(id); constraint
each each row primary key, Or mypkc ;
in the table. name Alter table student or
varchar(10), Add primary Alter table
mark key(id); student
number(4)); Drop
primary key;

create table Alter table Alter table


FOREIGN A foreign key classes( classes classes
is a key used c_id Add constraint drop
KEY to link two number(3), myfkc foreign constraint
tables c_date key(s_id) myfkc ;
together. date, references Or
s_id student(id);
number(3) Or Alter table
references Alter table classes classes
student(id) ); Add foreign Drop foreign
key(s_id) key;
references
student(id);
This constraint create table Alter table Alter table student Alter table
CHECK is used to student ( student Add constraint student
restrict the id Modify mycheckc drop
value of a number(3), Mark check(mark>50); constraint
column name number(4) mycheckc ;
between a varchar(10), check
range mark (mark>50);
number(4)
check
(mark>50) ) ;

Exercise3:
A)Create the following schema: with Primary key and foreign key as shown below:

27
1-Add a constraint not null to studentName col.
2- Add a constraint to check that DepartmentName is either (CSA,CIS,SW) only.
3-Make the default value of DateOfbirth to be ‘1/1/1990’.

4-Remove default value in DateOfbirth col.


5-Delete Tables Students, Dep.

B)
Create table emp with the following specification:
Column Data type Size constraint
name
Id Number 2 Primary key
Fname String 15 NOT NULL
Lname String 15 Default ‘no fname’
sal Number 6,2 Between 150 and 900
Dept_id Number 2

Create table dept with the following specification:


Column Data type Size constraint
name
id Number 2 Primary key
name String 15 Not null

1)Alter table emp by adding foreign key constraint on column dept_Id referenced by id of dept
table.

2)Delete the primary key constraint of emp table.


3)Delete tables emp,Dept.

28
Database lab Worksheet 6

PL/SQL programming language was developed by Oracle Corporation as procedural


extension language for SQL and the Oracle relational database.

PL/SQL block-structure in an example:


Execute the following pl/sql code:

set serveroutput on;


Declare
a integer :=3;
b Float :=8.12;
s Varchar2(20) := 'hello pl/sql';
c number(5,1);
BEGIN
dbms_output.put_line('Value of a: '||a);
dbms_output.put_line('Value of b: '||b);
dbms_output.put_line('Value of s: '||s);
c:=a+b;
dbms_output.put_line('A + B = ' ||c);
END;
/

Note: In order to ask a value from the use we use the & operator, enter string value between
single quotations)
For example:
A integer := &A;
B varchar2(30) := ‘B’;

Exercise1:
1)Write Pl/Sql code to do the following:
 In declaration section define the following variables: std_id, std_name, and std_major
representing student id, student name, and student major respectively.
 In the execution section assign std_id, std_name, and std_major by your id,name, and
major respectively.
 Display on the screen all variables values.

29
2)Modify your PL/SQL code in the previous question to let the user prompt the variables values
during execution.

3)Write Pl/Sql code to do the following:


 In declaration section define the following integer variables(a,b,c,d,m), and float
variable(f).
 In the execution section let the user prompt the variables values for a and b. Let c =
summation of a and b, d = the multiplication of a and b, f = the result of dividing a by b,
And m = the reminder of dividing a by b.
 Display on the screen all variables values.

PL/SQL If statement
syntax:
IF condition1 THEN
sequence_of_statements1
ELSIF condition2 THEN
sequence_of_statements2
ELSE
sequence_of_statements3
END IF;

Exercise2:

1)Write Pl/Sql code to do the following:


In declaration section define the 3 integer variables. In the execution section let the user
prompt the variables values, and display on the screen the largest value.

2)Write Pl/Sql code that :


Let the user prompt an integer value, and check if it’s odd or even and display the result on the
screen.

3)Write PL/SQL to ask the user to enter a grade and print


A if grade > 90
B if grade between 89- 70
C if grade between 69 - 55
F otherwise

30
4)Write a program to calculate the commission of sales employee based on the sales vales, such
that:
 If sales are above 20000 then commission is 0.1 of sales.
 If sales are between 20000 and 10000 then commission is 0.05 of sales.
 If sales are between 10000 and 2000 then commission is 0.03 of sales.
 Else commission is 0.02 of sales.

PL/SQL LOOP statement has the following structure:

LOOP
statements;
EXIT WHEN condition;
END LOOP loop_label;
Example:
DECLARE
counter NUMBER(1) := 0;
BEGIN
LOOP
counter := counter + 1;
EXIT WHEN counter > 3;
dbms_output.put_line( 'Inside loop: ' || counter ) ;
END LOOP;

dbms_output.put_line( 'After loop: ' || counter );


END;

PL/SQL while LOOP statement has the following structure:


WHILE condition
LOOP
statements;
END LOOP;

Example:
DECLARE
counter NUMBER(1) := 1;
BEGIN
WHILE counter <= 3
LOOP
DBMS_OUTPUT.PUT_LINE( 'Counter : ' || counter );
counter := counter + 1;
END LOOP;
dbms_output.put_line( 'After loop: ' || counter );
END;

31
PL/SQL FOR LOOP statement has the following structure:

FOR index IN lower_bound .. upper_bound


LOOP
statements;
END LOOP;

Note: The index is an implicit variable. It is local to the FOR LOOP statement. In other words,
you cannot reference it outside the loop. Inside the loop, you can reference index but you
cannot change its value. After the FOR LOOP statement executes, the index becomes undefined.

Example:
BEGIN
FOR counter IN 1..3
LOOP
DBMS_OUTPUT.PUT_LINE(counter );
END LOOP;

END;

Exercise3:
1)Write Pl/Sql code to display on the screen the numbers from 1 to 10.
 Using Loop.
 Using while Loop.
 Using For loop.

2)Write Pl/Sql code to display on the screen the numbers from 10 to 1.


 Using Loop.
 Using while Loop.
 Using For loop.

3)Write a pl/sql to find the factorial of a given integer entered by the user.

4)Write pl/Sql program to check if a given integer is prime or not.

5)Write a program to reverse a given number.


For example:
Number = 34589
Reverse of number = 98543

32
Database lab Worksheet 7

PL/SQL Cursor: is a pointer that points to the result set of the SQL query against database
tables.
1. Declaring cursor:
CURSOR cursor_name IS sql_select_statements;
2. Declare a Record (data type):
Record-name cursor-name%ROWTYPE;
3. Opening a Cursor: OPEN cursor_name;
4. Fetching Records from PL/SQL Cursor:
FETCH cursor_name INTO record or variables;
i. You can test the cursor’s attribute %FOUND or %NOTFOUND
to check if the fetch against the cursor succeeded.
5. Close a Cursor: close cursor_name;

Example:

Declare cursor that contains first_name, last_name, and salary of the employees. Display on the
screen first name, last name, salary, high sal if salary greater than 10000 other wise low sal.

Declare
cursor c is select first_name,last_name,salary from employees;
r c%rowtype;
begin
open c;
loop
fetch c into r;
exit when c%notfound;
if r.salary>10000 then
dbms_output.put_line(r.first_name || ' , ' || 'has High salary');
else
dbms_output.put_line(r.first_name || ' , ' || 'has LOW salary');
end if;
end loop;
close c;
end;
/

33
Exercise: (From employees table in HR)

1)Declare a cursor that contains employee id and last name for all employees who work in
department 30, Display on the screen all information in the cursor.

2)Declare a cursor that contains employee id, last name, job id and job title for all employees
who work in department 30, Display on the screen all information in the cursor for employees
whose employee id ranged between 115 and 118.

3)Declare cursor that contains department name, department number of employees,


department maximum salary, and department minimum salary. Display on the screen all
information in the cursor. Hint: Declare variables not a record.

4)Declare cursor that contains department name, department number of employees,


department maximum salary, and department minimum salary. Display on the screen all
information in the cursor only for departments that start with A.
Hint: Declare variables not a record.

34

You might also like