DBWorksheet Update
DBWorksheet Update
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.
2
Login to hr account in SQL plus
3
Exercise:
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.
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 multiple columns to an existing table, the SQL ALTER TABLE syntax is:
To modify a columns’ data type in an existing table, the SQL ALTER TABLE syntax is:
To modify multiple columns(Data Type) in an existing table, the SQL ALTER TABLE syntax is:
6
5)DROP COLUMN IN TABLE
To drop a column in an existing table, the SQL ALTER TABLE syntax is:
To rename a column in an existing table, the SQL ALTER TABLE syntax is:
7)RENAME TABLE
To rename a table, the SQL ALTER TABLE syntax is:
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:
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;
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;
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.
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
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;
Syntax:
SELECT DISTINCT column1 FROM table_name ;
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.
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;
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’;
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.
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.
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.
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.
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.
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';
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.
18
Exercise3: (from dual table).
19
Example:
Select TO_CHAR(sysdate, 'yyyy/mm/dd') from dual;
Result: '2020/07/09'
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.
4- Write a SQL command to insert the following row into employees table.
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
Example:
What is the output, after executing the following SQL commands?
1-SELECT MIN(salary) FROM employees;
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'.
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.
2)Write a query to display department number, maximum salaries for those departments with
a maximum salary greater than 10000$.
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.
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.
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:
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.
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:
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;
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’.
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
1)Alter table emp by adding foreign key constraint on column dept_Id referenced by id of dept
table.
28
Database lab Worksheet 6
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.
PL/SQL If statement
syntax:
IF condition1 THEN
sequence_of_statements1
ELSIF condition2 THEN
sequence_of_statements2
ELSE
sequence_of_statements3
END IF;
Exercise2:
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.
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;
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:
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.
3)Write a pl/sql to find the factorial of a given integer entered by the user.
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.
34