6 Sql And Query Processing

Database Management System · Unit 6

SQL and Query Processing

Exam-focused notes for SQL and Query Processing (Database Management System, BIT202): what the TU syllabus asks and how it has actually been tested, with 9 solved past questions from this unit.

SQL and Query Processing in short

SQL (Structured Query Language) is the standard language to create, change, and query relational databases. Relational algebra is the mathematical base behind SQL queries. All examples here use these two tables.

SQL and Query Processing: notes

Department

DeptIDDeptName
10Sales
20HR
30IT

Employee

EmpIDNameSalaryDeptID
1Asha5000010
2Bikram4000010
3Chandra6000020
4Dipa30000NULL

SQL data definition language

DDL statements define and change the structure of the database. They do not work on individual rows.

  • CREATE: makes a table, view, or index.
  • ALTER: changes an existing table.
  • DROP: removes a table and its data completely.
  • TRUNCATE: removes all rows but keeps the table structure.
ALTER TABLE Employee ADD Email VARCHAR(80);
ALTER TABLE Employee MODIFY Salary DECIMAL(12,2);
ALTER TABLE Employee DROP COLUMN Email;
TRUNCATE TABLE Employee;
DROP TABLE Employee;

MODIFY is the MySQL and Oracle form. SQL Server uses ALTER COLUMN, and PostgreSQL uses ALTER COLUMN ... TYPE.

SQL data manipulation language

DML statements work on the rows: SELECT, INSERT, UPDATE, and DELETE.

INSERT INTO Employee (EmpID, Name, Salary, DeptID)
VALUES (5, 'Esha', 45000, 30);

SELECT Name, Salary
FROM Employee
WHERE Salary > 35000
ORDER BY Salary DESC;

The second query gives Chandra 60000, Asha 50000, and Bikram 40000.

Useful clauses and operators:

  • WHERE filters rows. AND, OR, NOT, BETWEEN, IN, and LIKE build conditions.
  • ORDER BY sorts the result. DISTINCT removes duplicates.
  • Aggregate functions are COUNT, SUM, AVG, MIN, and MAX.
  • To test for NULL, use IS NULL. The test = NULL never works.

A subquery is a query inside another query:

SELECT Name
FROM Employee
WHERE Salary > (SELECT AVG(Salary) FROM Employee);

The average salary is 45000, so the result is Chandra only. An inner join links two tables:

SELECT e.Name, d.DeptName
FROM Employee e
JOIN Department d ON e.DeptID = d.DeptID;

This gives Asha-Sales, Bikram-Sales, and Chandra-HR. Dipa has no department, so she is left out.

What this unit covers

  • SQL data definition language
  • SQL data manipulation language
  • Create table statements
  • Update and delete operations
  • Cascade on delete
  • Outer joins
  • Group by and having clauses
  • Views and view creation
  • Relational algebra operations

SQL data definition language

2082 · 5 marks

Write SQL statements to create a table and update value in a table. Also mention the use of cascade on delete while creating the table. Use your own assumption for the table and update conditions. [5]

Explanation of each clause: Clause Purpose ------ PRIMARY KEY Uniquely identifies each row in the table NOT NULL Ensures the column cannot have a NULL value FOREIGN KEY Creates a referential link between Employee.deptid and Department.deptid ON DELETE CASCADE Automatically deletes all related row...

Open this answer on its own page →

Group by and having clauses

2082 · 5 marks

How is the Group By Having clause used in SQL statements? Mention the syntax and example. [5]

The GROUP BY clause is used to arrange identical data into groups. It is typically used with aggregate functions (COUNT, SUM, AVG, MAX, MIN) to perform calculations on each group of rows. The HAVING clause is used to filter groups based on a condition. It is similar to the WHERE clause, but: - WH...

Open this answer on its own page →

Views and view creation

2082 · 5 marks

What is the view? How can you create a view in SQL? Illustrate with an example. [5]

Show solved answer

Views in SQL

What is a View?

A view is a virtual table that is derived from one or more base tables (or other views) using a SQL query. It does not physically store data itself; instead, it stores the query definition, and the data is retrieved dynamically whenever the view is accessed.

Key characteristics of a view:

  • It behaves like a table (can be queried using SELECT)
  • It simplifies complex queries
  • It provides data security by restricting access to specific rows/columns
  • It provides logical data independence

Creating a View in SQL

Syntax:

CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Example

Consider a base table:

Employee table:

EmpIDEmpNameDepartmentSalary
101AliceIT60000
102BobHR45000
103CarolIT70000
104DavidFinance50000

Step 1: Create a View

Suppose we want to create a view that shows only IT department employees without exposing their salary:

CREATE VIEW IT_Employees AS
SELECT EmpID, EmpName, Department
FROM Employee
WHERE Department = 'IT';

Step 2: Query the View

SELECT * FROM IT_Employees;

Output:

EmpIDEmpNameDepartment
101AliceIT
103CarolIT

Dropping a View

DROP VIEW IT_Employees;

Summary

FeatureDescription
Virtual TableDoes not store data physically
Based on QueryDefined using SELECT statement
SecurityHides sensitive columns (e.g., Salary)
SimplicitySimplifies repeated complex queries

A view thus acts as a saved query that can be treated as a table, providing security, simplicity, and abstraction over the underlying data.

Open this answer on its own page →

Relational algebra operations

2082 · 5 marks

Given following relations, write relational algebra statements for Person(Pid, pname, dob, paid) and Doctor(Did, pid, dname, dspeciality). a. Retrieving name of person who is doctor b. Retrieving all doctors whose speciality is pediatric. [5]

  • Person (Pid, pname, dob, paid) - Doctor (Did, pid, dname, dspeciality) Note: Standard relational algebra operations are used below, consistent with Tribhuvan University CSIT curriculum. --- To find the names of persons who are also doctors, we need to join the Person and Doctor relations on the...
Open this answer on its own page →

2079 · 5 marks

Retrieve the Employee Name, Department Number and Department Name of "John Smith" using Relational Algebra. The relations are given below. a. EMPLOYEE (Ssn, Fname, Lname, Bdate, Address, Sex, Salary, SuperSSN, Dno), b. PROJECT (Pnumber, Pname, Plocation, Dnum), c. WORKS ON (Essn, Pno, Hours), d. DEPARTMENT (Dname, Dnumber, Mgr_ssn, Mgr Start date) [5]

  • EMPLOYEE (Ssn, Fname, Lname, Bdate, Address, Sex, Salary, SuperSSN, Dno) - DEPARTMENT (Dname, Dnumber, Mgr\ssn, Mgr\Start\date) Note: Only EMPLOYEE and DEPARTMENT relations are needed for this query. --- We need: Employee Name (Fname, Lname), Department Number (Dno), Department Name (Dname) for...
Open this answer on its own page →

SQL data manipulation language

2080 · 10 marks

From the relations given below, answer the following questions EMPLOYEE (Ssn, Ename, Bdate, Address, Sex, Salary, Super_ssn, Dno), DEPARTMENT (Dname, Dnumber, Mgr_ssn, Mgr_start_date), PROJECT (Pname, Pnumber, Plocation, Dnum), DEPENDENT (Essn, Dependent_name, Sex, Bdate, Relationship), DEPT_LOCATIONS (Dnumber, Dlocation): a. Retrieve the name and address of all employees who work for the 'Computer' department in SQL, b. For each Department, retrieve the department number, the number of employees in the department, and their average salary using SQL, c. Retrieve the employees name and their Dname and Pname ordered by the employee's Dname, d. Retrieve the name and salary of all employees who work in department number 5 using Relational Algebra, e. Retrieve the name of the manager of each department using Relational Algebra.Following the above statement answer the following question.[10+0]

  • EMPLOYEE (Ssn, Ename, Bdate, Address, Sex, Salary, Superssn, Dno) - DEPARTMENT (Dname, Dnumber, Mgrssn, Mgrstartdate) - PROJECT (Pname, Pnumber, Plocation, Dnum) - DEPENDENT (Essn, Dependentname, Sex, Bdate, Relationship) - DEPTLOCATIONS (Dnumber, Dlocation) --- Explanation: - Join EMPLOYEE wit...
Open this answer on its own page →

2078 · 10 marks

From the relation given below, answer the following questions. EMPLOYEE (Ssn, Fname, Mnit, Name, Bdate, Address, Sex, Salary, Super_ssn, Dno) DEPARTMENT (Dname, Dnumber, Mgr_ssn, Mgr_start_date) PROJECT (Pname, Pnumber, Plocation, Dnum) DEPENDENT (Essn, Dependent_name, Sex, Bdate, Relationship) DEPT_LOCATIONS (Dnumber, Dlocation): a. Retrieve all the attributes of employees who work for the 'Computer' department department no 5 using SQL, b. For each Department, retrieve the department number, the number of employees in department, and their average salary using SQL, c. For each project on which more than two employees work, retrieve the project number, name, and the number of employees who work on that project using SQL, d. Select the EMPLOYEE tuples whose department is 10, or those whose salary is greater than Rs 50,000 using Relational Algebra, e. Retrieve the names of employees who have no dependents using Relational Algebra.[10]

  • EMPLOYEE (Ssn, Fname, Mnit, Name, Bdate, Address, Sex, Salary, Superssn, Dno) - DEPARTMENT (Dname, Dnumber, Mgrssn, Mgrstartdate) - PROJECT (Pname, Pnumber, Plocation, Dnum) - DEPENDENT (Essn, Dependentname, Sex, Bdate, Relationship) - WORKSON (Essn, Pno, Hours) (assumed standard relation for e...
Open this answer on its own page →

0 · 10 marks

Consider a database system with following schemas; Hospital(hname, haddress, hspecilaity) Doctor(did, dname, dspecilization, ) Worksat(did, hname, workinghrs) Pharmacy(phname, hname, no_of_sales, total_revenue) Now write SQL statements and relational algebra statements for following queries: a. Select name of all doctors having specialization 'gyno', b. Select the name and address of hospital where working hours is 'day', c. Using natural join select the name of doctors whose working hours are 'night', d. Find the average salary of the doctors, e. Find names of hospital and their pharmacy which generate revenue more than 10000. Sort the result in descending order on the basis of pharmacy name.[10]

--- SQL: Relational Algebra: First apply selection on dspecialization = 'gyno', then project dname. --- SQL: Relational Algebra: Join Hospital and Worksat on hname, apply selection on workinghrs = 'day', then project required attributes. --- SQL: Note: Natural join automatically joins on the comm...

Open this answer on its own page →

Outer joins

0 · 5 marks

Define Outer Join in SQL. Given following relations, show the results of left and right outer joins.

Employee:

EidEnameAddressDno
1RamKTM111
2RitaPKR222
3HariKTM333

Department:

DnoDname
111HRM
222Admin
444Account

[5]

Show solved answer

Outer Join in SQL

Given

Employee (E):

EidEnameAddressDno
1RamKTM111
2RitaPKR222
3HariKTM333

Department (D):

DnoDname
111HRM
222Admin
444Account

Join condition: E.Dno = D.Dno


Solution

Definition

An Outer Join returns all rows from one or both tables even when there is no matching row in the other table. Unmatched attributes are filled with NULL. Types:

  • Left Outer Join - all rows of the left table plus matching rows of the right table.
  • Right Outer Join - all rows of the right table plus matching rows of the left table.
  • Full Outer Join - all rows from both tables.

Matching analysis

  • E.Dno = 111 matches D.Dno = 111 (HRM)
  • E.Dno = 222 matches D.Dno = 222 (Admin)
  • E.Dno = 333 has no match in D
  • D.Dno = 444 (Account) has no match in E

Left Outer Join

SELECT * FROM Employee E LEFT OUTER JOIN Department D ON E.Dno = D.Dno;

All Employee rows kept; Hari (333) has no department, so NULLs.

EidEnameAddressE.DnoD.DnoDname
1RamKTM111111HRM
2RitaPKR222222Admin
3HariKTM333NULLNULL

Right Outer Join

SELECT * FROM Employee E RIGHT OUTER JOIN Department D ON E.Dno = D.Dno;

All Department rows kept; Account (444) has no employee, so NULLs.

EidEnameAddressE.DnoD.DnoDname
1RamKTM111111HRM
2RitaPKR222222Admin
NULLNULLNULLNULL444Account

Summary

Join TypeRows RetainedExtra NULL Row
Left Outer JoinAll Employee rowsHari (Dno 333)
Right Outer JoinAll Department rowsAccount (Dno 444)
Open this answer on its own page →