Lab Manual 2
Lab Manual 2
DATABASE
SYSTEM LAB
Hina Farooq
Course Title: Database System Lab
SQL
SQL, or Structured Query Language, is a standardized language for managing relational
databases. It includes commands for querying, updating, and controlling access to data. With its
concise syntax and powerful capabilities, SQL is essential for database management,
development, and analysis.
Experiment No: 1
• Alter table
ALTER TABLE Employees ADD Email VARCHAR(100);
• Drop Table
1
DROP TABLE Employees;
DATA TYPES:
1. CHAR (Size)
3. NUMBER (P, S)
4. DATE
5. LONG
6. RAW
SQL language is sub-divided into several language elements, including:
▪ Clauses, which are in some cases optional, constituent components of statements and
queries.
▪ Expressions, which can produce either scalar values or tables consisting of columns and
rows of data.
▪ Predicates which specify conditions that can be evaluated to SQL three-valued logic
(3VL) Boolean truth values and which are used to limit the effects of statements and
▪ Statements which may have a persistent effect on schemas and data, or which may control
▪ SQL statements also include the semicolon (";") statement terminator. Though not
2
▪ Insignificant white space is generally ignored in SQL statements and queries, making it
1. CREATE:
Syntax:
CREATE TABLE table_name (
column1 datatype constraints,
column2 datatype constraints,
...
columnN datatype constraints
);
Example:
CREATE TABLE Products (
ProductID INT PRIMARY KEY AUTO_INCREMENT,
ProductName VARCHAR(100) NOT NULL,
Category VARCHAR(50),
3
Price DECIMAL(8, 2) CHECK (Price > 0),
Stock INT DEFAULT 0
);
2. ALTER:
3. Syntax:
ALTER TABLE table_name ADD column_name datatype;
4. DROP TABLE:
Syntax:
DROP TABLE table_name;
Example:
DROP TABLE Employees;
4
5. Modify the column width of the job field of emp table
Solution
1. CREATE TABLE EMPLOYEE (
Experiment No:2
• Update table
UPDATE employees
SET salary = 55000
WHERE id = 101;
5
• Delete Table
DELETE FROM employees
WHERE id = 101;
Theory :
6
(2, 'Preehan', 'Malik', '[email protected]'),
(3, 'Seerat', 'Akbar', '[email protected]');
2. UPDATE-SET-WHERE:
Example:
UPDATE employees
SET email=’[email protected]'
WHERE id = 1;
3. DELETE-FROM:
Syntax:
DELETE FROM table_name
WHERE condition;
Example:
DELETE FROM employees
WHERE id = 1
4. TRUNCATE: This command will remove the data permanently. But structure will not be removed.
Syntax:
TRUNCATE TABLE <Table name>
Example
TRUNCATE TABLE student;
Purpose:
DELETE: Removes specific rows based on a condition.
TRUNCATE: Removes all rows from a table.
Condition:
DELETE: Can use a WHERE clause to specify rows
TRUNCATE: Does not allow a WHERE clause.
7
Logging:
DELETE: Logs each row deletion, can be rolled back.
TRUNCATE: Minimally logs page deallocations, generally cannot be rolled back.
Performance:
DELETE: Slower for large datasets.
TRUNCATE: Faster due to page-level deallocation.
Triggers:
DELETE: Activates AFTER DELETE triggers.
TRUNCATE: Does not activate triggers.
Identity Reset:
DELETE: Does not reset identity columns.
TRUNCATE: Resets identity columns to the seed value.
Foreign Key Constraints:
DELETE: Can be used on tables with foreign keys.
TRUNCATE: Cannot be used if the table is referenced by foreign keys.
2. SELECT - FROM -WHERE: This query is used to display a selected set of fields for a
selected set of records of a relation.
Syntax:
SELECT a set of fields FROM relation_name WHERE condition;
Example:
8
SQL> select * FROM dept WHERE deptno<=20;
DEPTNO DNAME LOC
------ ----------- ------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
Solution
1. CREATE TABLE EMPLOYEE (
Emp_no INT PRIMARY KEY,
E_name VARCHAR(50),
E_address VARCHAR(100),
E_ph_no VARCHAR(15),
Dept_no VARCHAR(10),
Dept_name VARCHAR(50),
Job_id INT,
9
Salary DECIMAL(10, 2)
);
2. INSERT INTO EMPLOYEE (Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name,
Job_id, Salary)
VALUES
(1, 'John Doe', '123 Elm St, CityA', '123-456-7890', 'D10', 'SALES', 101, 50000.00),
(2, 'Jane Smith', '456 Oak St, CityB', '234-567-8901', 'D20', 'HR', 102, 55000.00),
(3, 'Emily Johnson', '789 Pine St, CityC', '345-678-9012', 'D10', 'SALES', 103, 60000.00),
(4, 'Michael Brown', '321 Birch St, CityD', '456-789-0123', 'D30', 'MECH', 104, 65000.00),
(5, 'James Wilson', '654 Maple St, CityE', '567-890-1234', 'D40', 'IT', 105, 70000.00);
3. SELECT * FROM EMPLOYEE;
4. SELECT * FROM EMPLOYEE WHERE Dept_no = 'D10';
5. UPDATE EMPLOYEE
SET E_address = 'Nagpur'
WHERE Emp_no = 12;
6. SELECT * FROM EMPLOYEE WHERE Dept_name = 'MECH';
7. DELETE FROM EMPLOYEE
WHERE E_name = 'James Wilson';
8. SELECT * FROM EMPLOYEE WHERE Dept_name = 'SALES';
Experiment No: 3
10
SELECT FLOOR(123.456) AS floor_number; -- Result: 123
▪ Aggregate Function
SELECT SUM(Salary) AS total_salary FROM EMPLOYEE;
SELECT AVG(Salary) AS average_salary FROM EMPLOYEE;
SELECT MAX(Salary) AS highest_salary FROM EMPLOYEE;
SELECT MIN(Salary) AS lowest_salary FROM EMPLOYEE;
SELECT COUNT(*) AS total_employees FROM EMPLOYEE;
▪ Character Function
SELECT UPPER(E_name) AS upper_name FROM EMPLOYEE;
SELECT LOWER(E_name) AS lower_name FROM EMPLOYEE;
SELECT SUBSTRING(E_name, 1, 3) AS substring_name FROM EMPLOYEE;
SELECT LENGTH(E_name) AS name_length FROM EMPLOYEE;
▪ Conversion Function
SELECT CAST(Salary AS VARCHAR(20)) AS salary_string FROM EMPLOYEE;
SELECT CONVERT(INT, '123') AS converted_number;
▪ ▪ Date Function
SELECT GETDATE() AS current_date_time;
SELECT DATEADD(DAY, 10, GETDATE()) AS date_plus_10_days;
SELECT DATEDIFF(DAY, '2023-01-01', GETDATE()) AS days_since_new_year;
SELECT FORMAT(GETDATE(), 'yyyy-MM-dd') AS formatted_date;
Objective:
NUMBER FUNCTION:
Aggregative operators: In addition to simply retrieving data, we often want to perform some
computation or summarization. SQL allows the use of arithmetic expressions. We now consider
a powerful class of constructs for computing aggregate values such as MIN and SUM.
1. Count:
Syntax:
SELECT COUNT(column_name) AS count_alias
FROM table_name
WHERE condition;
Example:
11
SELECT COUNT(Emp_no) AS total_employees
FROM EMPLOYEE
2. SUM:
Syntax:
SELECT SUM(column_name) AS sum_alias
FROM table_name
WHERE condition;
Example:
SELECT SUM(Salary) AS total_salary
FROM EMPLOYEE;
3. AVG:
Syntax:
SELECT AVG(column_name) AS avg_alias
FROM table_name
WHERE condition;
Example:
SELECT AVG(Salary) AS average_salary
FROM EMPLOYEE;
4. MAX:
Syntax:
SELECT MAX(column_name) AS max_alias
FROM table_name
WHERE condition;
Example:
SELECT MAX(Salary) AS highest_salary
FROM EMPLOYEE;
12
5. MIN:
Syntax:
SELECT MIN(column_name) AS min_alias
FROM table_name
WHERE condition;
Example:
SELECT MIN(Salary) AS lowest_salary
FROM EMPLOYEE;
2. Display all the details of the employee whose salary is more than the Sal of any IT
PROFF..
3. List the employees in the ascending order of Designations of those joined after 1981.
4. List the employees along with their Experience and Daily Salary.
7. List the employees who are working for the Deptno 10 or20.
9. Dislay the name as well as the first five characters of name(s) starting with ‘H’
10. List all the emps except ‘PRESIDENT’ & ‘MGR” in asc order of Salaries.
13
Solution
1. CREATE TABLE EMPLOYEE (
Emp_no INT PRIMARY KEY,
E_name VARCHAR(50),
E_address VARCHAR(100),
E_ph_no VARCHAR(15),
Dept_no INT,
Dept_name VARCHAR(50),
Job_id INT,
Designation VARCHAR(50),
Salary DECIMAL(10, 2),
Joining_date DATE
);
3. SELECT *
FROM EMPLOYEE
WHERE Salary > (SELECT MAX(Salary) FROM EMPLOYEE WHERE Designation = 'IT
PROF');
4. SELECT *
FROM EMPLOYEE
WHERE Joining_date > '1981-01-01'
ORDER BY Designation ASC;
6. SELECT *
FROM EMPLOYEE
WHERE Designation IN ('CLERK', 'ANALYST');
7. SELECT *
FROM EMPLOYEE
WHERE Joining_date IN ('1981-05-01', '1981-12-03', '1981-12-17', '1980-01-19');
8. SELECT *
FROM EMPLOYEE
WHERE Dept_no IN (10, 20);
14
9. SELECT E_name
FROM EMPLOYEE
WHERE E_name LIKE 'S%';
11. SELECT *
FROM EMPLOYEE
WHERE Designation NOT IN ('PRESIDENT', 'MGR')
ORDER BY Salary ASC;
Experiment No: 4
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations on numeric values.
2. Logical Operators
Logical operators are used to combine multiple conditions.
15
3. Comparison Operators
Comparison operators are used to compare values.
4. Special Operators
Special operators are used for special purposes like pattern matching and checking for NULL
values.
2. Display all the dept numbers available with the dept and emp tables.
SELECT Dept_no FROM dept
UNION
SELECT Dept_no FROM emp;
3. Display all the dept numbers available in emp and not in dept tables and vice versa.
16
SELECT DISTINCT Dept_no FROM emp
WHERE Dept_no NOT IN (SELECT Dept_no FROM dept)
UNION
Experiment No: 5
• Outer Join
Syntax
SELECT columns
FROM table1
FULL JOIN table2 ON table1.column_name = table2.column_name;
Example
SELECT employees.EmployeeID, employees.LastName,
departments.DepartmentName
FROM employees
FULL JOIN departments ON employees.DepartmentID = departments.DepartmentID;
17
• Natural Join.
Syntax
SELECT columns
FROM table1
NATURAL JOIN table2;
Example
SELECT employees.EmployeeID, employees.LastName,
departments.DepartmentName
FROM employees
NATURAL JOIN departments;
Syntax
SELECT columns
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
SELECT columns
FROM table1
SELECT columns
FROM table1
18
LAB PRACTICE ASSIGNMENT:
Consider the following schema:
Sailors (sid, sname, rating, age)
Boats (bid, bname, color)
Reserves (sid, bid, day(date))
1. Find all information of sailors who have reserved boat number 101.
2. Find the name of boat reserved by Bob.
3. Find the names of sailors who have reserved a red boat, and list in the order of age.
4. Find the names of sailors who have reserved at least one boat.
5. Find the ids and names of sailors who have reserved two different boats on the
same day.
6. Find the ids of sailors who have reserved a red boat or a green boat.
7. Find the name and the age of the youngest sailor.
8. Count the number of different sailor names.
9. Find the average age of sailors for each rating level.
10. Find the average age of sailors for each rating level that has at least two sailors.
Solution
1. SELECT *
FROM Sailors
WHERE sid IN (SELECT sid FROM Reserves WHERE bid = 101);
2. SELECT bname
FROM Boats
WHERE bid = (SELECT bid FROM Reserves WHERE sid = (SELECT sid FROM Sailors
WHERE sname = 'Bob'));
3. SELECT sname
FROM Sailors
WHERE sid IN (SELECT sid FROM Reserves WHERE bid IN (SELECT bid FROM Boats
WHERE color = 'red'))
ORDER BY age;
19
4. SELECT DISTINCT sname
FROM Sailors
WHERE sid IN (SELECT sid FROM Reserves);
5. SELECT s.sid, s.sname
FROM Sailors s
JOIN Reserves r1 ON s.sid = r1.sid
JOIN Reserves r2 ON r1.sid = r2.sid
WHERE r1.day = r2.day AND r1.bid <> r2.bid;
6. SELECT DISTINCT sid
FROM Reserves
WHERE bid IN (SELECT bid FROM Boats WHERE color IN ('red', 'green'));
7. SELECT sname, age
FROM Sailors
WHERE age = (SELECT MIN(age) FROM Sailors);
8. SELECT COUNT(DISTINCT sname) AS num_sailors
FROM Sailors;
9. SELECT rating, AVG(age) AS avg_age
FROM Sailors
GROUP BY rating;
10. SELECT rating, AVG(age) AS avg_age
FROM Sailors
GROUP BY rating
HAVING COUNT(*) >= 2;
20
Experiment No: 6
Syntax
SELECT column1, column2, aggregate_function(column3)
FROM table_name
GROUP BY column1, column2;
Example
Syntax
FROM table_name
HAVING condition;
Example
FROM Orders
GROUP BY CustomerID
21
• Order by Clause
ORDER BY is used to sort the result set based on one or more columns.
Syntax
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC|DESC, column2 ASC|DESC;
Example
SELECT CustomerID, COUNT(*) AS NumOrders, SUM(TotalAmount) AS TotalSpent
FROM Orders
GROUP BY CustomerID
ORDER BY TotalSpent DESC;
5. Show the record of employee earning salary greater than 16000 in each
department.
Solution
1. SELECT Job_id, SUM(Salary) AS TotalSalary
FROM EMPLOYEE
GROUP BY Job_id;
22
2. SELECT ManagerID, MIN(Salary) AS LowestSalary
FROM EMPLOYEE
GROUP BY ManagerID;
3. SELECT Dept_no, COUNT(*) AS NumEmployees, Dept_name
FROM EMPLOYEE
GROUP BY Dept_no, Dept_name;
4. SELECT *
FROM EMPLOYEE
ORDER BY Salary ASC;
5. SELECT *
FROM EMPLOYEE
WHERE Salary > 16000
ORDER BY Dept_no;
Experiment No: 8
Theory:
CONSTRAINTS:
Constraints are used to specify rules for the data in a table. If there is any violation between the
constraint and the data action, the action is aborted by the constraint. It can be specified when
the table is created (using CREATE TABLE statement) or after the table is created (using
ALTER TABLE statement).
1. NOT NULL: When a column is defined as NOTNULL, then that column becomes a
mandatory column. It implies that a value must be entered into the column if the record is to be
accepted for storage in the table.
Syntax:
CREATE TABLE Table_Name (column_name data_type (size) NOT NULL, );
Example:
23
CREATE TABLE student (sno NUMBER(3)NOT NULL, name CHAR(10));
2. UNIQUE: The purpose of a unique key is to ensure that information in the column(s) is
unique i.e. a value entered in column(s) defined in the unique constraint must not be repeated
across the column(s). A table may have many unique keys.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) UNIQUE, ….);
Example:
CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10));
3. CHECK: Specifies a condition that each row in the table must satisfy. To satisfy the
constraint, each row in the table must make the condition either TRUE or unknown (due to a
null).
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) CHECK(logical
expression), ….); Example:
CREATE TABLE student (sno NUMBER (3), name CHAR(10),class
CHAR(5),CHECK(class IN(‘CSE’,’CAD’,’VLSI’));
24
Example:
CREATE TABLE faculty (fcode NUMBER(3) PRIMARY KEY, fname
CHAR(10));
5. FOREIGN KEY: It is a table level constraint. We cannot add this at column level. To
reference any primary key column from other table this constraint can be used. The table in
which the foreign key is defined is called a detail table. The table that defines the primary key
and is referenced by the foreign key is called the master table.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size)
FOREIGN KEY(column_name) REFERENCES table_name); Example:
CREATE TABLE subject (scode NUMBER (3) PRIMARY KEY, subname
CHAR(10),fcode NUMBER(3), FOREIGN KEY(fcode) REFERENCE faculty );
Name Type
Soultion
1. CREATE TABLE EMP (
25
EMPNO NUMBER(6) CONSTRAINT chk_empno CHECK (EMPNO > 100),
ENAME VARCHAR2(20) NOT NULL,
JOB VARCHAR2(10) NOT NULL,
DEPTNO NUMBER(3),
SAL NUMBER(7,2),
CONSTRAINT uk_deptno UNIQUE (DEPTNO),
CONSTRAINT pk_emp PRIMARY KEY (EMPNO)
);
2. INSERT INTO EMP (EMPNO, ENAME, JOB, DEPTNO, SAL) VALUES (101, 'John',
'Manager', 10, 5000);
INSERT INTO EMP (EMPNO, ENAME, JOB, DEPTNO, SAL) VALUES (102, 'Alice',
'Analyst', 20, 4000);
3. INSERT INTO EMP (EMPNO, ENAME, JOB, DEPTNO, SAL) VALUES (99, 'Bob', 'Clerk',
30, 3000); -- This should fail
4. INSERT INTO EMP (EMPNO, ENAME, JOB, DEPTNO, SAL) VALUES (103, 'Emily',
'Clerk', 10, 3500); -- This should fail
5.
VIVA-VOCE
1. Define DCL?
DCL stands for Data Control Language, which is a component of SQL (Structured Query
Language). DCL is used to control access to data stored in a database and manage
permissions. The primary commands in DCL are:
GRANT: This command is used to provide specific privileges to users or roles. For
example, granting a user permission to access certain data or perform specific actions
like SELECT, INSERT, UPDATE, or DELETE.
REVOKE: This command is used to remove previously granted privileges from users or
roles.
26
REVOKE SELECT, INSERT ON table_name FROM user_name;
GRANT privilege_list
ON object_name
TO user_or_role
Transaction Control Language (TCL) commands in SQL are crucial for managing
database transactions, ensuring data integrity and consistency. The primary TCL
commands are COMMIT, ROLLBACK, SAVEPOINT, RELEASE SAVEPOINT, and SET
TRANSACTION. COMMIT saves all changes made during the current transaction
permanently, while ROLLBACK undoes changes, reverting the database to the last
committed state. SAVEPOINT allows setting a point within a transaction to which one can
rollback, and RELEASE SAVEPOINT deletes a specified savepoint. SET TRANSACTION
defines transaction properties like the isolation level
A single row function or scalar function returns only one value for every row queries
in table. Single row function can appear in a select command and can also be
included in a where clause. The single row function can be broadly classified as,
* Date Function * Conversion Function
* Numeric Function * Miscellaneous Function
*Character Function
6. List some character functions
1)Upper 2)Lower 3)Intcap 4)Length 5)Trim 6)Replace 7)Ascii 8)Substr
7. What is a view?
A view is a logical table based on a table or another view. A view contains no data of its
own but is like a window through which data from tables can be viewed or changed.
8. List any two advantages of view?
1. Hides data complexity.
2. Simplifies the usage by combining multiple tables into a single table
27
10. What is the use of sub Queries?
28