0% found this document useful (0 votes)
18 views

Lab Manual 02 (Basics)

This document is a lab manual for a database systems lab course. It provides instructions and examples for using basic SQL commands like SELECT, WHERE, ORDER BY, and built-in functions. The document explains how to select columns, use aliases, concatenate values, filter rows, sort results, and calculate values. It includes examples querying the employees table to retrieve, filter, and manipulate data. Tasks at the end provide practice writing SQL statements to select, filter, and sort rows from database tables.

Uploaded by

Shahmir Raza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Lab Manual 02 (Basics)

This document is a lab manual for a database systems lab course. It provides instructions and examples for using basic SQL commands like SELECT, WHERE, ORDER BY, and built-in functions. The document explains how to select columns, use aliases, concatenate values, filter rows, sort results, and calculate values. It includes examples querying the employees table to retrieve, filter, and manipulate data. Tasks at the end provide practice writing SQL statements to select, filter, and sort rows from database tables.

Uploaded by

Shahmir Raza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

CL2005 – Database Systems Lab Lab Manual – 02

National University of Computer & Emerging Sciences, Karachi


Computer Science Department
Spring 2023, Lab Manual – 02

Course Code: CL-2005 Course: Database Systems Lab


Instructor(s): Shaheer Ahmad Khan

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.

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

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>.


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 condi tions
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;

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

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.

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 (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 ‘_l%’;

OR list all employees having ‘A’ as first 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 todepartment #100.
3) List all the Employees belonging to cities like Toronto, Hiroshima and Sydney.
4) List all the Employees having an ‘ll’ in their first_names.
5) List all the employees with no commission.

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

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

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 data types. There are two distinct types of
functions:

• Single-row functions: Single Row or Scalar Functions return a value for every row that
is processed in a 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:

Page 4 of 8
CL2005 – Database Systems Lab Lab Manual – 02

Character or Text Functions: These are functions that accept character input and can
return both character and number values. Following are some frequently used char
functions:

Following examples illustrate the usage of these functions.

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

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’
ADD_MONTHS(date, n) months to date ‘x’.
MONTHS_BETWEEN(x1,x2) Returns the number of months between
date 1& date 2
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.

Extract() The EXTRACT() function extracts a part


from a given date.

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’)
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’, ‘AST’, 31-MAY-08
‘EST’)
Extract SELECT EXTRACT(Month FROM 09
sysdate);
SELECT EXTRACT(Year FROM 2021
sysdate);

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 to
another 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 of functions. Following are few examples of conversion functions available in
oracle.

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

Implementation:

• select nvl(commission_pct ,1) from EMPLOYEES;


• select DECODE (&a, &b, 'a-b equal', &d, 'a-d equal', 'FAIL') from dual;
• select to_char(to_date(sysdate,'DD-MM-YY'),'WW') from dual;

Tasks:
1) Print an employee name (first letter capital) and job title (lower Case)
2) Display employee name and job title together, length of employee name and thenumeric position of
letter A in employee name, for all employees who are in sales.
Hint: For finding position you need to use string function “instr()”, this function workedas INSTR(string1,
string2)(s1:sreaching string, s2:string/char you’re searching for).

3) Comparing the hire dates for all employees who started in 2003, display the employeenumber, 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’s name and hire date for all employees. The hire dateappears as 16
September, 2021.
6) Display the salary of employee Neena 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.
10) For all employees employed for more than 100 months, display the employee number, hire date,
number of months employed, first Friday after hire date andlastday of the month hired.

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:

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

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) Write a SQL statement to display all the information of table Jobs.


2) Write a SQL query to find min and max salary of the Job table with Job title ‘President’ from Jobs table.
3) Write a SQL query to find those employees whose Salaries is 20000 from Employees table.
4) Write a SQL query to find the Jobs whose salary are higher than or equal to $15000 from Employees table.
5) Write a query to find the list of jobs whose min salary is greater than 8000 and less than 15,000 from job
table.
6) Write a query to find list of phone with DEPARTMENT_ID ‘90’ but not with job_id ‘IT_PROG’ from Employees
table.
7) Write a query to find the list of employees who are hired after '12-Dec-07' from employee table.
8) Write a query to find the list of employees who are hired after '12-Dec-07' in Department with
DEPARTMENT_ID=100 from employee table.
9) Write a query to find the list of employees who are hired after '12-Dec-07' but not in Department with
DEPARTMENT_ID=100 from employee table.
10) 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
before and after salaries & name thisamount as “Incremented Amount”.
11) List the name, hire date, and day of the week (labeled DAY) on which job was started. Order the result
by day of week starting with Monday.
12) Display the department and manager id for all employees and round the commissionup to 1 decimal.
13) Write a query to find the list of employees whose COMMISSION_PCT>0 and they do not belong to
DEPARTMENT_ID 90 or 100 from Employees table
14) Write a query to find the employees who are hired in year 2010 from Employees table.
15) Write a query to find the list of jobs whose min salary is greater than 8000 and less than 15,000 and commission = 0
from job table.
16) Write a query to find employee whose ID are greater than 100 and less than 150 and their department_id is
greater than 90 and less than 100 along with their first_name, Last_name & Job ID.
1) Write a query to find total salary (Total salary formula = salary + (commission_pct* salary)) as “Total
Salary”, commission_pct where commission_pct is not equal to null.

Page 8 of 8

You might also like