0% found this document useful (0 votes)
14 views9 pages

Lab Manual 2

Uploaded by

shahzaib3769
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
14 views9 pages

Lab Manual 2

Uploaded by

shahzaib3769
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 9

CL2005 – Database Systems Lab Lab Manual – 02

National University of Computer & Emerging Sciences, Karachi


Computer Science Department
Fall 2024, Lab Manual – 02

Course Code: CL-2005 Course: Database Systems Lab

Instructor(s): Fatima Gado

Contents:
1. Use of Select Clause (DML/DQL).
2. Use of Column Alias, Concatenation Operator, DISTICNT, ALL keyword and Asterisk Operator.
3. Use of Row Selection Clause (Where).
4. Sorting Results (Use of Order By).
5. Built in Oracle Functions.

Simple Select Query:


The purpose of a SELECT statement is to display and retrieve data from one or more database tables.
SELECT is the most frequently used command in SQL, and is used to query the database tables. Usually a
simple SELECT query involves two more clauses i.e. FROM and WHERE. FROM is used to refer to the
tables to retrieve data from.

Syntax: SELECT <column1>, <column2>…..<column n> FROM <table1>;


Example: Display all columns of HR Database’s Employee table.

SELECT employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary,


commission_pct, manager_id, department_id FROM employees;
Task: Display any two columns from employees table.

Use of Column Alias:


A Column Alias is used to give column a name that is different than the name it is given in the
Table. A user usually provides a Column Alias through a special keyword “AS” to display the
column with a changed name i.e. Renamed Column.

Syntax: SELECT <column1> as “New Column Name” FROM <table1>;

Example: Display the column Employee_ID and Phone_Number from Employees table. Display the
column Phone Number as Contact Number.

SELECT employee_id, phone_number as “Contact Number” From employees;

Task: Display Hire_date from employees table, name it as Joining Date.

Use of Concatenation Operator:


A concatenation operator is denoted by a pipe || which is used to concatenate columns or strings
together. The pipe operator is independent of the data type of the column.

Syntax: SELECT <column1> || <column2> FROM <table1>.

Page 1 of 7
CL2005 – Database Systems Lab Lab Manual – 02

Example: Show the First Name and Salary of employees as a single column named “Employees and
Salaries”.

SELECT first_name || salary as “Employees and Salaries” FROM employees;

Task:Display the first_name, last_name of Employees together in one column named “FULL NAME”

Use of DISTINCT Keyword.


The distinct keyword is used to show unique records of a table. The SELECT does not eliminate duplicate
when it projects over one or more column. To eliminate the duplicates, we use DISTINCT keyword.

Syntax: SELECT DISTINCT <column1> FROM <table1>.


Example: Show unique departments of Employees Table.
SELECT DISTINCT(department_id) FROM employees;

Use of ALL Keyword:


A query with keyword ALL display all rows irrespective of the duplicate records found in the
table. In general it is the reverse of what DISTINCT keyword does.
Syntax: SELECT ALL <column1> FROM <table1>.
Example: Show all salaries of Employees.
SELECT ALL(salary) FROM employees;

Use of Asterisk Keyword:


Many SQL retrieval requires all columns to be displayed in the output, While doing so would be
hectic, we use Universal (*) operator to do the same. It is used to show all columns of a table at
once.
Syntax: SELECT * FROM <table1>.
Example: Show all columns of table DEPARTMENTS.
SELECT * FROM departments;

Row Selection Using WHERE Clause:


We often need to restrict the number of rows retrieved from the table. This can be done using
WHERE clause. The clause uses a search condition or set of search conditions to filter the rows.
Syntax: SELECT <column1>...<column(n)> FROM <table1> WHERE <column1> = ;
Example: Show the first_name, salary of Employee whose employee id is 100.
SELECT first_name, salary FROM employees WHERE employee_id = 100;

There are Five Possible Types of Search Condition and Operators to be Used:

(a) Comparison Search Condition: The comparison search condition involves comparison between
the column’s actual value and desired value and returns the results filtered using comparison
operators (<, >, <=, >= , <> , !=, =). These conditions may involve the use of Logical Operators
(AND, OR, NOT) with parameters if needed to show order of evaluation. A search that involves
comparison and logical operators together is called Compound Comparison Search Condition.
Example: List all employees having monthly salaries greater than 20,000 and deptno: 100.
SELECT * FROM employees WHERE salary > 20,000 and department_id =100;

(b) Range Search Condition: The range search uses BETWEEN and NOT BETWEEN operators to
filter the rows on the basis of range of elements. The Between operator includes the endpoints too
for search output.

Page 2 of 7
CL2005 – Database Systems Lab Lab Manual – 02

Example: List the staff with the salary between 20,000 and 30,000.

SELECT * FROM employees WHERE salary BETWEEN 20,000 and 30,000;

(c) Set Membership Search Condition: The set membership test (IN) tests whether a data value
matches one of a list of values.
Example: List the salaries of Sales Manager and Purchasing Manager.

SELECT * FROM job WHERE job_title IN (‘Sales Manager’, ‘Purchasing Manager’);

(d) Pattern Match Search Condition: The search condition involves searching for a particular
character or string within a column value. Like Operator with the help of pattern matching symbols
( _, %) are used find patterns in the column’s value. ‘_’ represents a single character while ‘%’
represents a sequence of characters.

Example: List all the employees whose names contains an ‘a’ in their first names.

SELECT * FROM employees WHERE first_name LIKE ‘%a%’;

OR List all employees having L as second letter in their first names.

SELECT * FROM employees WHERE first_name LIKE ‘_a %’;

(e) NULL Search Condition: The NULL Search Condition uses NULL operator to filter fields that
have NULL values.
Example: Display all employees whose commission is not null.

SELECT * FROM employees WHERE commission_pct is not null;

Tasks:
1) List all Employees having annual salary greater 20, 000 and lesser than 30,000.
2) List employee_id and first_name of employees from department # 60 to department #100.
3) List all the Employees having an ‘ll’ in their first_names.
4) List all the employees with no commission.

Sorting Rows with Order by Clause:


Generally, the rows of an SQL query result table are not arranged in a particular order, however with
the use of Order By clause, the users can arrange the result in a particular ascending or descending
order (alphabetical or numerical) of values present in the fields. The Order By uses column identifiers.
Either these are column names or column numbers.

Syntax: SELECT <column1>..<column(n)> FROM <table1> Order By <column identifier>.

Example: Show all employees in order of their increasing salaries.

SELECT * FROM employees ORDER BY salary asc;

Task: List all employees in order of their decreasing salaries.

DUAL Table in Oracle:


This is a single row and single column dummy table provided by oracle. This is used to perform
mathematical calculations without using a table.

Syntax: SELECT * FROM DUAL

Page 3 of 7
CL2005 – Database Systems Lab Lab Manual – 02

Built In Oracle Functions:


Built In Functions area very powerful feature of SQL capable of: performing calculations,
modifying individual data, or output for group of rows, format dates and numbers and
conversion of column datatypes. There are two distinct types of functions:

• Single-row functions: Single Row or Scalar Functions return a value for every row that is
processed ina query.

• Aggregate Functions: The group functions are used to calculate aggregate values like total or
average,which return just one total or one average value after processing a group of rows.

There are four types of single row functions. They are:

Numeric Functions: These are functions that accept numeric input and return numeric values.

The Implementation of these Numeric Functions can be understood from following examples:

Tasks:
1. Find the absolute values of the salary differences between salary and a base amount of 5000 for employees with
IDs 100 and 101.
2. Round the salary of employees to the nearest whole number and to 2 decimal places.
3. Find the ceiling value of the salary of employees, showing how it rounds up to the nearest whole number.
4. Find the floor value of the salary of employees, showing how it rounds down to the nearest whole number.
5. Find the highest value between salary and commission_pct (converted to a percentage) for each employee.
Assume that commission_pct is a percentage value.
6. Find the lowest value between salary and commission_pct (converted to a percentage) for each employee.
Assume that commission_pct is a percentage value.

Character or Text Functions: These are functions that accept character input and
Page 4 of 7
CL2005 – Database Systems Lab Lab Manual – 02
can returnboth character and number values. Following are some frequently used
char functions:

Tasks : -

1. Concatenate the department_name and location_id from the departments table to create a string in the
format 'Department: [department_name] Location: [location_id]'.
2. Extract the first 4 characters of each job_title in the jobs table.
3. Find the length of the street_address field for each location in the locations table.
4. Convert all employees first name into uppercase
5. Convert all email addresses to lowercase in the employees table.
6. Convert the department_name field to title case, where the first letter of each word is capitalized.
7. Remove leading and trailing spaces from the first_name field, then convert it to UPPERCASE.
8. Pad the Salary field with leading zeros from left and right both sides separately so that all salary
amount have a length of 7 characters

Page 5 of 7
CL2005 – Database Systems Lab Lab Manual – 02

Following examples illustrate the usage of these functions.

Date Functions: These are functions that take values that are of data type DATE as input and
return values of data type DATE, except for the MONTHS_BETWEEN function, which returns a
number.

Functions Description
Returns a date value after adding ‘n’ months to
ADD_MONTHS(date, n)
date ‘x’.
MONTHS_BETWEEN(x1,x2) Returns the number of months between date 1&
date 2
ROUND(x, date_format) Returns the date ‘x’ rounded off to the nearest
century, year, month, date, hour, minute, or
second as specified by the ‘date_format’
TRUNC(x, date_format) Return the date ’x’ lesser than or equal to
nearest century, year, month, date, hour, minute,
or second as specified by the ‘date_format’
NEXT_DAY(x, week_day) Returns the next date of the date ‘week_day’ on
or after the date ’x’ occurs.
LAST_DAY(x) It is used to determine the number of days
remaining in a month from the date ‘x’ specified
SYSDATE() Returns the systems current date and time.
NEW_TIME(x, zone1, zone2) Returns the date and time in zone2 if date ‘x’
represents the time in zone1.

Implementation:

Functions Examples Return Value


ADD_MONTHS() ADD_MONTHS (‘16-Sep-81’,3) 16-DEC-81
MONTHS_BETWEEN() MONTHS_BETWEEN(’16-SEP- 3
81’, ’16-DEC-81’)

Page 6 of 7
CL2005 – Database Systems Lab Lab Manual – 02

NEXT_DAY() NEXT_DAY(’01-JUN-08’, 04-JUN-08


‘Wednesday’)
LAST_DAY() LAST_DAY(’01-JUN-08’) 30-JUN-08
NEW_TIME() NEW_TIME(’01-JUN-08’, ‘ISL’, 31-MAY-08
‘EST’)

Tasks : -
1. Display the Current Date.
2. Calculate the Number of Months Between Today and Each Employee’s Hire
Date.
3. Find the Next Monday After Each Employee’s Hire Date.
4. Find the Last Day of the Month for Each Employee’s Hire Date
Conversion Functions: These are functions that help us to convert a value in one form to
another form. For Example: a null value into an actual value, or a value from one datatype
toanother datatype like NVL, TO_CHAR, TO_NUMBER, TO_DATE etc.
You can combine more than one function together in an expression. This is known as nesting
offunctions.

Following are few examples of conversion functions available in oracle.

Implementation:

Tasks:

1) Print an employee name (first letter capital) and job_title (lower Case)
2) For all employees employed for more than 100 months, display the employee number, hire
date,number of months employed, first Friday after hire date and last day of the month hired.
3) Comparing the hire dates for all employees who started in 2003, display the employee number, hire
date, and month started using the conversion and date functions.
4) To display the employee number, the month number and year of hiring.
5) To display the employee name and hire date for all employees. The hire date appears as
16September, 2021.
6) Display the salary of employee STEVEN with $ sign
preceded.7) Find the next ‘Monday’ considering today’s date as
date.
8) List all Employees who have an ‘A’ in their last
names.9) Show all employees’ last three letters of first
name

Page 7 of 7
CL2005 – Database Systems Lab Lab Manual – 02

Aggregate Functions (Group Functions):


A group function is an Oracle SQL function that returns a single result based on many rows, as opposed
to single-row functions. These functions are: AVG, COUNT, MIN, MAX, STDDEV, SUM,
VARIANCE, etc. Grouping functions may include either of the keywords DISTINCT or ALL.ALL is the
default if neither is specified and uses all selected rows in the calculation. DISTINCT uses only one row
for each value in the
calculations. Note: Group Functions like AVG do not include NULL valued rows. For that we can nest a
NULL function into AVG function.
Some Group Functions available in Oracle are:

Examples:
1) Show the average salary, minimum salary, maximum salary and count of employees in the
organization.
SELECT AVG(salary), MIN(salary), MAX(salary), COUNT(employee_id) FROM employees;

2) Show the earliest and latest hire date of employees.


SELECT MAX(hire_date), MIN(hire_date) FROM employees;

3) Compute the difference between the minimum and maximum


salary.SELECT MAX(salary) - MIN(salary) FROM employees;

4) To show total number of rows in a


table. SELECT COUNT (*) FROM
employees;

Tasks:
1) To display the employee number, name, salary of employee before and after 15% increment in the
yearly salary. Name the calculated new salary as “Incremented Salary”. Do calculate the difference
between two salaries. Name the increased amount to be “Incremented Amount”.
2) List the name, hire date, and day of the week (labeled DAY) on which job was started. Order the
resultby day of week starting with Monday.
3) Display the department and manager id wise avg commission for all employees. Round the
commission up to 1 decimals.
Page 8 of 7
CL2005 – Database Systems Lab Lab Manual – 02

Page 9 of 7

You might also like