Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Subject Code BC02001021 Subject Name Database Management System
Lab Exercise_1
1) Create table Student
create table Student (Student_Id integer primary key, Student_Name varchar (50));
2) Display structure of Student Table
describe Student;
3) Insert records into Student Table
insert into Student (Student_Id,Student_Name) values
(1,'Komal'), (2,’Nishant’), (3,’Jigar’);
4) Display all records of Student Table
select * from Student;
5) Add column DateOfBirth into Student Table
alter table Student add column DateOfBirth date;
6) Insert Record for DateOfBirth
update Student set DateOfBirth='2003-2-13' where Student_Id=1;
update Student set DateOfBirth='2003-7-3' where Student_Id=2;
update Student set DateOfBirth='2003-12-3' where Student_Id=3;
[Note: date format is 'yyyy-mm-dd']
7) Delete column DateOfBirth
alter table Student drop column DateOfBirth;
Lab Exercise_2
GTU Syllabus Set 1
DEPARTMENT (dept_no, dept_name, location)
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
1. Create the Simple DEPARTMENT Table.
2. Display structure of department table.
3. Insert below records into Department Table
4. Display all records of Department table
5. Display all department belonging to location 'NY'
6. Display details of Department 10
7. List all department names starting with 'A'
8. List all departments whose number is between 1 and 100
9. Delete 'TRG' department
10. Change department name 'EDP' to 'IT
Solution: Set 1: DEPARTMENT Table
1.Create the DEPARTMENT Table:
CREATE TABLE DEPARTMENT (
dept_no INT PRIMARY KEY,
dept_name VARCHAR (50),
location VARCHAR (50)
);
2. Display Structure:
DESCRIBE DEPARTMENT;
3. Insert Records:
INSERT INTO DEPARTMENT (dept_no, dept_name, location) VALUES
(10, 'Account', 'NY'),
(20, 'HR', 'NY'),
(30, 'Production', 'DL'),
(40, 'Sales', 'NY'),
(50, 'EDP', 'MU'),
(60, 'TRG', NULL),
(110, 'RND', 'AH');
4. Display All Records:
SELECT * FROM DEPARTMENT;
5. Departments in NY:
SELECT * FROM DEPARTMENT WHERE location = 'NY';
6. Details of Department 10:
SELECT * FROM DEPARTMENT WHERE dept_no = 10;
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
7. Departments Starting with 'A':
SELECT * FROM DEPARTMENT WHERE dept_name LIKE 'A%';
8. Departments with Number Between 1 and 100:
SELECT * FROM DEPARTMENT WHERE dept_no BETWEEN 1 AND 100;
9. Delete TRG Department:
DELETE FROM DEPARTMENT WHERE dept_name = 'TRG';
10. Rename EDP to IT:
UPDATE DEPARTMENT SET dept_name = 'IT' WHERE dept_name = 'EDP';
Lab Exercise_3
Based on SQL Constraints
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and
reliability of the data in the table. If there is any violation between the constraint and the data action,
the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and table
level constraints apply to the whole table.
The following constraints are commonly used in SQL:
• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each
row in a table
• FOREIGN KEY - Prevents actions that would destroy links between tables
• CHECK - Ensures that the values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column if no value is specified
• CREATE INDEX - Used to create and retrieve data from the database very quickly
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
1) By default, a column can hold NULL values.
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert a new
record, or update a record without adding a value to this field.
Apply Not null constraint while creating table:
• create table Persons (
Person_Id int not null,
First_Name varchar(50) not null,
Last_Name varchar(50) not null,
Person_Age int);
• describe Persons;
• insert into Persons values(1,"Vyas","Krupa",21);
insert into Persons values(2,"Patel","Jigar",31);
insert into Persons values(3,"Rana","Mahesh",21);
• select * from Persons;
Apply Not null constraint with alter table statement:
• alter table Persons modify column Person_age int not null;
2) The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness
for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.
Apply unique constraint while creating table:
CREATE TABLE Persons1 (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
Apply unique constraint with alter table statement:
ALTER TABLE Persons1
ADD UNIQUE (ID);
3) The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a column it will allow only certain values for this
column.
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
If you define a CHECK constraint on a table it can limit the values in certain columns based
on values in other columns in the row.
CREATE TABLE Persons2 (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
First check with
insert into persons2 values (1,"Patel","Jigar",7);
[Note: It will show an error about constraint violation.]
insert into persons2 values (1,"Patel","Jigar",27);
4) The DEFAULT constraint is used to set a default value for a column.
The default value will be added to all new records, if no other value is specified.
CREATE TABLE Persons3 (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Surat'
);
insert into persons3 values (1,"Patel","Jigar",23,"");
insert into persons3 values (2,"Kamara","Lokesh",23,"Ahmedabd");
Lab Exercise_4
Based on SQL Joins (Inner, Left, Right and Full Join)
SQL joins are the foundation of database management systems, enabling the combination of
data from multiple tables based on relationships between columns. Joins allow efficient data
retrieval, which is essential for generating meaningful observations and solving complex
business queries.
What is SQL Join?
SQL JOIN clause is used to query and access data from multiple tables by establishing logical
relationships between them. It can access data from multiple tables simultaneously using
common key values shared across different tables. We can use SQL JOIN with multiple tables.
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
It can also be paired with other clauses; the most popular use will be using JOIN with WHERE
clause to filter data retrieval.
Both these tables are connected by one common key (column) i.e ROLL_NO. We can perform a
JOIN operation using the given SQL query:
Student Table:
create table student(Roll_No integer primary key,
Name varchar(50),
Address varchar(100),
Phone double,
Age integer);
Insert into student values(1,"Ruchita","Satelite",1234567891,24);
Insert into student values(2,"Jagruti","Shahibag",1234567189,23);
Insert into student values(3,"Komal","Ranip",1234567289,23);
Roll_No Name Address Phone Age
Edit Copy Delete 1 Ruchita Satelite 798999999999 34
Edit Copy Delete 2 Komal Sabarmati 798999999999 24
Edit Copy Delete 3 Jagruti Shahibag 123456789 23
Course Table:
create table course (course_id integer primary key,
course_name varchar(100),
Roll_No integer references student(Roll_No)
);
insert into course values(1,"DBMS",1);
insert into course values(2,"AWS",2);
insert into course values(3,"AWS",3);
course_id course_name Roll_No
Edit Copy Delete 1 DBMS 1
Edit Copy Delete 2 AWS 2
Edit Copy Delete 3 AWS 3
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Join Query:
select s.Roll_No,s.Name,s.Address,s.phone,s.age,c.course_id,c.course_name from student s,
course c where s.Roll_No=c.Roll_No;
Output
Roll_No Name Address phone age course_id course_name
1 Ruchita Satelite 798999999999 34 1 DBMS
2 Komal Sabarmati 798999999999 24 2 AWS
3 Jagruti Shahibag 123456789 23 3 AWS
Solve by yourself – Exercise – 1
Create Table Customers
CustomerID CustomerName ContactName Country
1 Komal Jani Maria Anders Germany
2 Arpita Shah Ana Phillip Mexico
3 Juliana Andrew Hiren Vasa Mexico
Create Table Orders
OrderID CustomerID OrderDate
10308 1 2024-09-18
10309 2 2024-09-12
10310 3 2024-09-05
Write down Join Query and give Output as below:
OrderID CustomerName OrderDate
10308 Komal Jani 2024-09-18
10309 Arpita Shah 2024-09-12
10310 Juliana Andrew 2024-09-05
1) List Customers data where customer country is Mexico.
2) List Customer Name where OrderDate is “2024-09-12”.
3) Perform join query for output given above.
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Solution:
create table customers (customer_id integer primary key,
customer_name varchar(50),
contact_name varchar(50),
country varchar(50));
create table orders (order_id integer primary key,
order_date date,
customer_id integer references
customers(customer_id));
insert into customers values(1,"Komal Jani","Maria Anders","Germany");
insert into customers values(2,"Arpita Shah","Ana Phillip","Mexico");
insert into customers values(3,"Juliana Andrew","Hiren Vasa","Mexico");
select * from customers
customer_id customer_name contact_name country
Edit Copy Delete 1 Komal Jani Maria Anders Germany
Edit Copy Delete 2 Arpita Shah Ana Phillip Mexico
Edit Copy Delete 3 Juliana Andrew Hiren Vasa Mexico
insert into orders values (10308,"2024-09-18",1);
insert into orders values (10309,"2024-09-12",2);
insert into orders values (10310,"2024-09-05",3);
select * from orders
order_id order_date customer_id
Edit Copy Delete 10308 2024-09-18 1
Edit Copy Delete 10309 2024-09-12 2
Edit Copy Delete 10310 2024-09-05 3
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
1) List Customers data where customer country is Mexico.
select * from customers where country="Mexico"
customer_id customer_name contact_name country
Edit Copy Delete 2 Arpita Shah Ana Phillip Mexico
Edit Copy Delete 3 Juliana Andrew Hiren Vasa Mexico
2) List Customer Name where OrderDate is “2024-09-12”.
select customer_name, o.order_date from customers c, orders o where
c.customer_id=o.customer_id and o.order_date="2024-09-12";
customer_name order_date
Arpita Shah 2024-09-12
3) Perform join query for output given below.
OrderID CustomerName OrderDate
10308 Komal Jani 2024-09-18
10309 Arpita Shah 2024-09-12
10310 Juliana Andrew 2024-09-05
select o.order_id,c.customer_name,o.order_date from customers c, orders o
where c.customer_id=o.customer_id;
order_id customer_name order_date
10308 Komal Jani 2024-09-18
10309 Arpita Shah 2024-09-12
10310 Juliana Andrew 2024-09-05
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Solve by yourself – Exercise – 2
Create Table Products
Product_id Product_name Category Unit_price
101 Laptop Electronics 50000
102 Smart Phone Electronics 30000
103 Head Phones Electronics 2000
104 Keyboards Electronics 5000
105 Mouse Electronics 1000
Create Table Sales
Sales_id Product_id Quantity_sold Sales_date
1 101 5 2024-01-01
2 102 3 2024-01-02
3 103 2 2024-01-02
4 104 4 2024-01-03
5 105 6 2024-01-03
Write down Join Query and give Output as below:
Sales_id Product_name Sales_date
1 Laptop 2024-01-01
2 Smart Phone 2024-01-02
3 Head Phones 2024-01-02
4 Keyboards 2024-01-03
5 Mouse 2024-01-03
1) List Products data where Category equal to Electronics.
2) List Productname where UnitPrice between 25000 and 50000.
3) List Products data where Quantity_sold >3.
4) Perform join query for output given above.
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Lab Exercise_5
SQL Aggregate Functions
An aggregate function is a function that performs a calculation on a set of
values, and returns a single value.
Aggregate functions are often used with the GROUP BY clause of
the SELECT statement. The GROUP BY clause splits the result-set into groups of
values and the aggregate function can be used to return a single value for each
group.
The most commonly used SQL aggregate functions are:
• MIN() - returns the smallest value within the selected column
• MAX() - returns the largest value within the selected column
• COUNT() - returns the number of rows in a set
• SUM() - returns the total sum of a numerical column
• AVG() - returns the average value of a numerical column
The SQL GROUP BY Statement
The GROUP BY statement groups rows that have the same values into summary
rows, like "find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more
columns.
SQL HAVING Clause
The HAVING clause was introduced in SQL to allow the filtering of query
results based on aggregate functions and groupings. Unlike the WHERE
clause, which filters individual rows before any grouping occurs, the HAVING
clause works on groups of data that have been aggregated using functions
like SUM(), AVG(), COUNT(), and others.
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
What is the SQL HAVING Clause?
The HAVING clause is used to filter the result of GROUP BY based on the
specified condition. The conditions are Boolean type i.e. use of logical
operators (AND, OR). This clause was included in SQL as the WHERE keyword
failed when we used it with aggregate expressions. Having is a very generally
used clause in SQL. Similar to WHERE it helps to apply conditions, but HAVING
works with groups. If you wish to filter a group, the HAVING clause comes into
action.
Some important points:
• Having clause is used to filter data according to the conditions provided.
• Having a clause is generally used in reports of large data.
• Having clause is only used with the SELECT clause.
• The expression in the syntax can only have constants.
• In the query, ORDER BY is to be placed after the HAVING clause, if any.
• HAVING Clause is implemented in column operation.
• Having clause is generally used after GROUP
BY.
Syntax:
SELECT col_1, function_name(col_2)
FROM tablename
GROUP BY column1, column2
HAVING Condition
Here, the function_name is the name of the function used, for example, SUM(),
and AVG().
SQL Having vs WHERE
Having Where
In the HAVING clause it will check the condition In the WHERE condition it will check or execute
in group of a row. at each row individual.
HAVING clause can only be used with aggregate The WHERE Clause cannot be used with
function. aggregate function like Having
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Having Where
Priority Wise HAVING Clause is executed after Priority Wise WHERE is executed before Group
Group By. By.
Examples:
Products Table:
Customers Table
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
create table products(product_id integer primary key,
product_name varchar(50),
quantity_in_stock integer,
unit_price decimal(10,2));
insert into products values(1,'Foam Dinner Plate',70,1.21);
insert into products values(2,'Pork - Bacon',49,4.65);
insert into products values(3,'Lettuce - Romaine',38,3.35);
select * from products
product_id product_name quantity_in_stock unit_price
Edit Copy Delete 1 Foam Dinner Plate 70 1.21
Edit Copy Delete 2 Pork - Bacon 49 4.65
Edit Copy Delete 3 Lettuce - Romaine 38 3.35
create table customers(customer_id integer primary key,
first_name varchar(50),
last_name varchar(50),
birth_date date,
phone double,
address varchar(100),
city varchar(50),
state varchar(50),
points integer);
insert into customers values(1,'Alfred','Maccaffrey','1906-03-
28',7819329754,'0 Sage Terrace','Hampton','MA',2273);
insert into customers values(2,'Ines','BrushField','1986-04-
13',8044279456,'14187 Commercial Trail','Hampton','VA',947);
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
insert into customers values(3,'Freddi','Bagey','1985-02-
07',8044279456,'14187 Commercial Trail','Colarado
Spring','CO',2967);
select * from customers
custome first_na last_na birth_d addres sta poin
phone city
r_id me me ate s te ts
E Co Del Maccaff 1906- 7819329 0 Sage Hamp 227
1 Alfred MA
dit py ete rey 03-28 754 Terrace ton 3
14187
E Co Del BrushFi 1986- 8044279 Comme Hamp
2 Ines VA 947
dit py ete eld 04-13 456 rcial ton
Trail
14187
Colar
E Co Del 1985- 8044279 Comme 296
3 Freddi Bagey ado CO
dit py ete 02-07 456 rcial 7
Spring
Trail
1) Count() - The COUNT() function returns the number of rows in a database
table.
Select count(product_id) from products;
Output:
count(product_id)
3
Select count(product_id) from products where unit_price>4;
Output:
count(product_id)
1
Select count(customer_id), city from customers group by city having
count(customer_id) >0;
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Output:
count(customer_id) city
Edit Copy Delete 1 Colarado Spring
Edit Copy Delete 2 Hampton
2) SUM() - The SUM() function returns the total sum of a numeric column.
Select sum(unit_price) from products;
sum(unit_price)
9.21
Select count(customer_id), city from customers group by city having
sum(points) > 3000;
Output:
count(customer_id) city
Edit Copy Delete 2 Hampton
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
3) Avg() - The AVG() function calculates the average of a set of values.
Select avg(quantity_in_stock) from products;
Output:
avg(quantity_in_stock)
52.3333
4) MIN() - The MIN() aggregate function returns the lowest value (minimum) in a
set of non-NULL values.
Select min(quantity_in_stock) from products;
min(quantity_in_stock)
38
5) MAX() - The MAX() aggregate function returns the highest value (maximum) in
a set of non-NULL values.
Select max(quantity_in_stock) from products;
max(quantity_in_stock)
70
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
SQL Aggregate Function Examples
1. COUNT() Example
Task: Count the total number of customers in the Customers table.
-- Create the Customers table
CREATE TABLE Customers (
CustomerID INTEGER,
Name VARCHAR(50),
City VARCHAR(50)
);
-- Insert data into Customers table
INSERT INTO Customers (CustomerID, Name, City) VALUES
(1, 'John Doe', 'New York'),
(2, 'Jane Smith', 'Los Angeles'),
(3, 'Sam Johnson', 'Chicago');
-- Count the number of customers
SELECT COUNT(*) AS total_customers
FROM Customers;
Output:
total_customers
---------------
3
2. SUM() Example
Task: Calculate the total sales (sum of price) from the Orders table.
-- Create the Orders table
CREATE TABLE Orders (
OrderID INTEGER,
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Product VARCHAR(50),
Price DECIMAL(10, 2)
);
-- Insert data into Orders table
INSERT INTO Orders (OrderID, Product, Price) VALUES
(1, 'Laptop', 1000.00),
(2, 'Smartphone', 500.00),
(3, 'Tablet', 300.00);
-- Calculate the total sales
SELECT SUM(Price) AS total_sales
FROM Orders;
Output:
total_sales
------------
1800.00
3. AVG() Example
Task: Find the average salary from the Employees table.
-- Create the Employees table
CREATE TABLE Employees (
EmployeeID INTEGER,
Name VARCHAR(50),
Salary DECIMAL(10, 2)
);
-- Insert data into Employees table
INSERT INTO Employees (EmployeeID, Name, Salary) VALUES
(1, 'Alice Brown', 50000.00),
(2, 'Bob White', 60000.00),
(3, 'Charlie Green', 70000.00);
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
-- Calculate the average salary
SELECT AVG(Salary) AS average_salary
FROM Employees;
Output:
average_salary
---------------
60000.00
4. MIN() Example
Task: Find the youngest employee (minimum age) from the
Employees table.
-- Create the Employees table with an age column
CREATE TABLE Employees (
EmployeeID INTEGER,
Name VARCHAR(50),
Age INT
);
-- Insert data into Employees table
INSERT INTO Employees (EmployeeID, Name, Age) VALUES
(1, 'Alice Brown', 35),
(2, 'Bob White', 40),
(3, 'Charlie Green', 28);
-- Find the youngest employee
SELECT MIN(Age) AS youngest_employee
FROM Employees;
Output:
youngest_employee
-----------------
28
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
5. MAX() Example
Task: Find the highest salary from the Employees table.
-- Create the Employees table with salary
CREATE TABLE Employees (
EmployeeID INTEGER,
Name VARCHAR(50),
Salary DECIMAL(10, 2)
);
-- Insert data into Employees table
INSERT INTO Employees (EmployeeID, Name, Salary) VALUES
(1, 'Alice Brown', 50000.00),
(2, 'Bob White', 75000.00),
(3, 'Charlie Green', 60000.00);
-- Find the highest salary
SELECT MAX(Salary) AS highest_salary
FROM Employees;
Output:
highest_salary
--------------
75000.00
Examples of GROUP BY
Employee Table:
CREATE TABLE emp (
emp_no INT PRIMARY KEY,
name VARCHAR(50),
sal DECIMAL(10,2),
age INTEGER
);
INSERT INTO emp (emp_no, name, sal, age) VALUES
(1, 'Aarav', 50000.00, 25),
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
(2, 'Aditi', 60000.50, 30),
(3, 'Aarav', 75000.75, 35),
(4, 'Anjali', 45000.25, 28),
(5, 'Chetan', 80000.00, 32),
(6, 'Divya', 65000.00, 27),
(7, 'Gaurav', 55000.50, 29),
(8, 'Divya', 72000.75, 31),
(9, 'Gaurav', 48000.25, 26),
(10, 'Divya', 83000.00, 33);
SELECT * from emp;
Output:
Student Table:
CREATE TABLE student (
name VARCHAR(50),
year INTEGER,
subject VARCHAR(50)
);
INSERT INTO student (name, year, subject) VALUES
('Alice', 1, 'Mathematics'),
('Bob', 2, 'English'),
('Charlie', 3, 'Science'),
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
('David', 1, 'Mathematics'),
('Emily', 2, 'English'),
('Frank', 3, 'Science');
Output:
Example 1: Group By Single Column
Query:
SELECT name, SUM(sal) FROM emp
GROUP BY name;
The above query will produce the below output:
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Example 2: Group By Multiple Columns
Query:
SELECT SUBJECT, YEAR, Count(*)
FROM Student
GROUP BY SUBJECT, YEAR;
Output:
Example 3: HAVING Clause in GROUP BY Clause
SELECT NAME, SUM(sal) FROM Emp
GROUP BY name
HAVING SUM(sal)>50000;
Output:
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
SQL HAVING Clause Examples
Creating a table
-- Create the Employee table with appropriate data types
CREATE TABLE Employee (
EmployeeId int,
Name varchar(50),
Gender varchar(10),
Salary integer,
Department varchar(20),
Experience int -- Changed to int for years of experience
);
-- Insert multiple rows into the Employee table in a single query
INSERT INTO Employee (EmployeeId, Name, Gender, Salary, Department,
Experience)
VALUES
(5, 'Priya Sharma', 'Female', 45000, 'IT', 2),
(6, 'Rahul Patel', 'Male', 65000, 'Sales', 5),
(7, 'Nisha Gupta', 'Female', 55000, 'Marketing', 4),
(8, 'Vikram Singh', 'Male', 75000, 'Finance', 7),
(9, 'Aarti Desai', 'Female', 50000, 'IT', 3);
The final table is:
SELECT * FROM Employee;
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Output:
Example 1: Using HAVING to Filter Aggregated Results
SELECT Department, sum(Salary) as Salary
FROM Employee
GROUP BY department;
Output:
Now if we need to display the departments where the sum of salaries is 50,000 or more.
In this condition, we will use the HAVING Clause.
SELECT Department, sum(Salary) as Salary
FROM Employee
GROUP BY department
HAVING SUM(Salary) >= 50000;
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Output
Example 2: Using HAVING with Multiple Conditions
If we want to find the departments where the total salary is greater than or
equal to $50,000, and the average salary is greater than $55,000. We can use
the HAVING clause to apply both conditions.
Query
SELECT Department, SUM(Salary) AS Total_Salary, AVG(Salary) AS
Average_Salary
FROM Employee
GROUP BY Department
HAVING SUM(Salary) >= 50000 AND AVG(Salary) > 55000;
Output:
Department Total_Salary Average_Salary
Finance 75000 75000
Sales 65000 65000
Example 3: Using HAVING with COUNT()
If we want to find departments where there are more than two employees. For
this, we can use the COUNT() aggregate function along with the HAVING
clause.
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Query:
SELECT Department, COUNT(EmployeeId) AS Employee_Count
FROM Employee
GROUP BY Department
HAVING COUNT(EmployeeId) >= 2;
Output:
Department Employee_Count
IT 2
This query counts the number of employees in each department and uses the
HAVING clause to filter for departments with more than two employees.
Example 4: Using HAVING with AVG()
Find out the average salary for each department and use the HAVING clause
to display only those departments where the average salary is greater than
$50,000.
Query:
SELECT Department, AVG(Salary) AS Average_Salary
FROM Employee
GROUP BY Department
HAVING AVG(Salary) > 50000;
Output:
Department Average_Salary
Finance 75000
Marketing 55000
Sales 65000
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Lab Exercise_6
SQL IN Operator
• The SQL IN operator filters data based on a list of specific values.
• In general, we can only use one condition in the WHERE clause, but the IN operator
allows us to specify multiple values.
IN Operator
• The IN Operator in SQL is used to specify multiple values/sub-queries in
the WHERE clause.
• It provides an easy way to handle multiple OR conditions.
• We only pass a single condition in the WHERE clause, however there might be situations
where we need to select data based on multiple conditions. For such cases, the IN
operator is used.
SQL IN Syntax
The Syntax of the IN operator is as follows:
SELECT column_name FROM table_name
WHERE condition IN (condition_value1, condition_value2 …..);
Here, we select the column column_name from the table table_name where the condition is
checked in all the condition_values passed with the IN operator.
DEMO SQL Database
We will use the following SQL table for our examples below:
Fname Lname Ssn Bdate Address Sex Salary
Chiranjeev Singh 1 2002-07-31 Delhi M 1111789.00
Harry Stark 2 1990-07-31 Delhi M 3333.00
Meghna Gururaani 5 2002-04-04 Almora F 3433.00
Aniket Bhardwaj 6 2001-05-05 Ponta M 56564.00
Vritti Goel 7 2002-03-05 Delhi F 7565.00
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Fname Lname Ssn Bdate Address Sex Salary
Aashish Kumar 8 2002-08-04 Himachal M 44657.00
Siddharth Chaturvedi 9 2003-11-10 Lucknow M 244322.00
CREATE TABLE Employee (
Fname VARCHAR(50),
Lname VARCHAR(50),
Ssn INT,
Bdate DATE,
Address VARCHAR(100),
Sex CHAR(1),
Salary DECIMAL(10, 2)
);
INSERT INTO Employee (Fname, Lname, Ssn, Bdate, Address, Sex, Salary) VALUES
('Chiranjeev', 'Singh', 1, '2002-07-31', 'Delhi', 'M', 1111789.00),
('Harry', 'Stark', 2, '1990-07-31', 'Delhi', 'M', 3333.00),
('Meghna', 'Gururaani', 5, '2002-04-04', 'Almora', 'F', 3433.00),
('Aniket', 'Bhardwaj', 6, '2001-05-05', 'Ponta', 'M', 56564.00),
('Vritti', 'Goel', 7, '2002-03-05', 'Delhi', 'F', 7565.00),
('Aashish', 'Kumar', 8, '2002-08-04', 'Himachal', 'M', 44657.00),
('Siddharth', 'Chaturvedi', 9, '2003-11-10', 'Lucknow', 'M', 244322.00);
SQL IN Operator Examples
Example 1:
SQL Query to get Fname and Lname of employees who have address in Delhi and Himachal
Query:
SELECT Fname, Lname FROM employee
WHERE Address IN ('Delhi','Himachal');
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Output:
Fname Lname
Chiranjeev Singh
Harry Stark
Vritti Goel
Aashish Kumar
Example 2: SQL IN and NOT IN Operators
We can use the SQL IN with the NOT operator to exclude specified data from our result.
Query:
SELECT Fname FROM employee
WHERE Address NOT IN ('Delhi', 'Lucknow');
Output:
Fname
Meghna
Aniket
Aashish
Here, we have created a query to fetch the Fname of all employees whose address is neither
Delhi nor Lucknow. We used the NOT operator with IN to exclude these values.
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Lab Exercise_7
GTU Syllabus Set 2
EMPLOYEE (emp_id, emp_name, birth_date, gender, dept_no, address, designation, salary,
experience, email)
DEPARTMENT (dept_no, dept_name, location) Do as directed:
1. Create the EMP Table with all necessary constraints such as In EMP TABLE:
Employee id should be primary key, Department no should be Foreign key,
Salary should be greater than zero, email should have (@ and dot) sign in address,
Designation of employee can be “manager”, “clerk”, “leader”, “analyst”, “designer”, “coder”,
“tester”.
2. Create DEPT table with necessary constraint such as
Department no should be primary key; department name should be unique.
4. After creation of above tables, modify Employee table by adding the constraints as
‘Male’ or ‘Female’ in gender field and display the structure.
5. Insert proper data (at least 5 appropriate records) in all the tables.
6. Describe the structure of table created.
7. List all records of each table in ascending order.
8. Delete the department whose location is Ahmedabad.
9. Display female employee list.
10. Display Departname wise employee Names.
11. Find the names of the employee who has salary less than 5000 and greater than 2000.
12. Display the names and the designation of all female employee in descending order.
13. Display the names of all the employees who names starts with ‘A’ ends with ‘A’.
14. Find the name of employee and salary for those who had obtain minimum salary.
15. Add 10% raise in salary of all employees whose department is ‘IT’.
16. Count total number of employees of ‘IT’ department.
17. List all employees who born in the current month.
18. Print the record of employee and dept table as “Employee works in department ‘MBA’.
19. List names of employees who are fresher’s (less than 1 year of experience).
20. List department wise names of employees who has more than 5 years of experience.
21. List department having no employees.
GTU Syllabus Set 2 - Solution
1. Create EMP Table with Constraints:
CREATE TABLE EMPLOYEE (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50) NOT NULL,
birth_date DATE NOT NULL,
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
gender VARCHAR(6),
dept_no INT,
address VARCHAR(100),
designation VARCHAR(20) CHECK (designation IN ('manager', 'clerk', 'leader', 'analyst',
'designer', 'coder', 'tester')),
salary DECIMAL(10, 2) CHECK (salary > 0),
experience DECIMAL(4, 2),
email VARCHAR(100) CHECK (email LIKE '%@%.%'),
FOREIGN KEY (dept_no) REFERENCES DEPARTMENT(dept_no) ON DELETE CASCADE
);
2. Create DEPT Table with Constraints:
CREATE TABLE DEPARTMENT (
dept_no INT PRIMARY KEY,
dept_name VARCHAR(50) UNIQUE,
location VARCHAR(50)
);
3. Modify EMP Table to Add Gender Constraint:
ALTER TABLE EMPLOYEE
ADD CONSTRAINT gender_check CHECK (gender IN ('Male', 'Female'));
4. Insert data into tables:
INSERT INTO DEPARTMENT VALUES (1, 'HR', 'Mumbai');
INSERT INTO DEPARTMENT VALUES (2, 'Sales', 'Delhi');
INSERT INTO DEPARTMENT VALUES (3, 'IT', 'Bangalore');
INSERT INTO EMPLOYEE VALUES (101, 'Alice', '1995-05-10', 'Female', 1, 'Mumbai',
'manager', 6000, 3.5, '
[email protected]');
INSERT INTO EMPLOYEE VALUES (102, 'Bob', '1998-08-15', 'Male', 3, 'Bangalore', 'coder',
4000, 1.0, '
[email protected]');
INSERT INTO EMPLOYEE VALUES (103, 'Charlie', '1997-12-20', 'Male', 2, 'Delhi', 'analyst',
4500, 2.5, '
[email protected]');
INSERT INTO EMPLOYEE VALUES (104, 'Diana', '2001-03-10', 'Female', 3, 'Bangalore',
'designer', 3000, 0.8, '
[email protected]');
INSERT INTO EMPLOYEE VALUES (105, 'Eve', '1999-06-30', 'Female', 1, 'Mumbai', 'tester',
5000, 5.0, '
[email protected]');
select * from department;
dept_no dept_name location
Edit Copy Delete 1 HR Mumbai
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
dept_no dept_name location
Edit Copy Delete 2 Sales Delhi
Edit Copy Delete 3 IT Bangalore
select * from employee;
em
emp_ birth gen dept addr design sala exper
p_i email
name _date der _no ess ation ry ience
d
C Fe
E De 101 Alice 1995- Mum manag 600 alice@comp
op mal 1 3.50
dit lete 05-10 bai er 0.00 any.com
y e
C 1998- Mal Bang 400 bob@compa
E De 102 Bob 3 coder 1.00
op 08-15 e alore 0.00 ny.com
dit lete
y
C
E De 103 Charli 1997- Mal
2 Delhi
analys 450
2.50
charlie@co
op e 12-20 e t 0.00 mpany.com
dit lete
y
C Fe
E De 104 Diana 2001- mal 3 Bang design 300
0.80
diana@com
op 03-10 alore er 0.00 pany.com
dit lete e
y
C Fe
E De 105 Eve 1999- Mum 500 eve@compa
op mal 1 tester 5.00
dit lete 06-30 bai 0.00 ny.com
y e
5. Describe Tables:
DESCRIBE EMPLOYEE;
Field Type Null Key Default Extra
emp_id int(11) NO PRI NULL
emp_name varchar(50) NO NULL
birth_date date NO NULL
gender varchar(6) YES NULL
dept_no int(11) YES MUL NULL
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
Field Type Null Key Default Extra
address varchar(100) YES NULL
designation varchar(20) YES NULL
salary decimal(10,2) YES NULL
experience decimal(4,2) YES NULL
email varchar(100) YES NULL
DESCRIBE DEPARTMENT;
Field Type Null Key Default Extra
dept_no int(11) NO PRI NULL
dept_name varchar(50) YES UNI NULL
location varchar(50) YES NULL
6. List Records in Ascending Order:
SELECT * FROM EMPLOYEE ORDER BY emp_name;
em
emp_n birth_ gen dept addr design sala experi
p_i email
ame 1 date der _no ess ation ry ence
d
C Fe
E Del 101 1995- Mum manag 600 alice@comp
op Alice mal 1 3.50
dit ete 05-10 bai er 0.00 any.com
y e
C 1998- Mal Bang 400 bob@compa
E Del 102 Bob 3 coder 1.00
op 08-15 e alore 0.00 ny.com
dit ete
y
C 1997- Mal 450 charlie@com
E Del 103 Charlie 2 Delhi analyst 2.50
op 12-20 e 0.00 pany.com
dit ete
y
C Fe
E Del 104 2001- Bang design 300 diana@comp
op Diana mal 3 0.80
dit ete 03-10 alore er 0.00 any.com
y e
C Fe
E Del 105 1999- Mum 500 eve@compa
op Eve mal 1 tester 5.00
dit ete 06-30 bai 0.00 ny.com
y e
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
SELECT * FROM DEPARTMENT ORDER BY dept_name;
dept_no dept_name 1 location
Edit Copy Delete 1 HR Mumbai
Edit Copy Delete 3 IT Bangalore
Edit Copy Delete 2 Sales Delhi
7. Delete Department in Ahmedabad:
DELETE FROM DEPARTMENT WHERE location = 'Ahmedabad';
8. Display female employee list
SELECT * FROM EMPLOYEE WHERE gender = 'Female';
emp emp_ birth_ gen dept addre design sala experi
email
_id name date der _no ss ation ry ence
E Co Del 101 1995- Fem Mum manag 600 alice@comp
Alice 1 3.50
dit py ete 05-10 ale bai er 0.00 any.com
E Co Del 104 2001- Fem Bang design 300 diana@com
Diana 3 0.80
dit py ete 03-10 ale alore er 0.00 pany.com
E Co Del 105 1999- Fem Mum 500 eve@compa
Eve 1 tester 5.00
dit py ete 06-30 ale bai 0.00 ny.com
9. Department-wise employee names
SELECT D.dept_name, E.emp_name
FROM DEPARTMENT D
JOIN EMPLOYEE E ON D.dept_no = E.dept_no;
dept_name emp_name
HR Alice
IT Bob
Sales Charlie
IT Diana
HR Eve
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
10. Employees with salary between 2000 and 5000
SELECT emp_name FROM EMPLOYEE WHERE salary BETWEEN 2000 AND 5000;
emp_name
Edit Copy Delete Bob
Edit Copy Delete Charlie
Edit Copy Delete Diana
Edit Copy Delete Eve
11. Female employees in descending order
SELECT emp_name, designation FROM EMPLOYEE WHERE gender = 'Female' ORDER BY
emp_name DESC;
emp_name 1 designation
Edit Copy Delete Eve tester
Edit Copy Delete Diana designer
Edit Copy Delete Alice manager
12. Names starting and ending with 'A'
SELECT emp_name FROM EMPLOYEE WHERE emp_name LIKE 'A%A';
13. Minimum salary employee
SELECT emp_name, salary FROM EMPLOYEE WHERE salary = (SELECT MIN(salary) FROM
EMPLOYEE);
emp_name salary
Edit Copy Delete Diana 3000.00
14. Raise salary by 10% for IT department
UPDATE EMPLOYEE
SET salary = salary * 1.10
WHERE dept_no = (SELECT dept_no FROM DEPARTMENT WHERE dept_name = 'IT');
15. Count IT department employees
SELECT COUNT(*) AS total_employees
FROM EMPLOYEE WHERE dept_no = (SELECT dept_no FROM DEPARTMENT WHERE dept_name = 'IT');
Lokmanya BBA BCA College-318
Practical List
Dec 2024 – April 2025
Semester –II
total_employees
2
16. Employees born in the current month
SELECT * FROM EMPLOYEE
WHERE EXTRACT(MONTH FROM birth_date) = EXTRACT(MONTH FROM SYSDATE());
17. Employee and department info
SELECT CONCAT(emp_name, ' works in department ', dept_name) AS record
FROM EMPLOYEE E
JOIN DEPARTMENT D ON E.dept_no = D.dept_no;
record
Alice works in department HR
Bob works in department IT
Charlie works in department Sales
Diana works in department IT
Eve works in department HR
18. Employees with less than 1 year experience
SELECT emp_name FROM EMPLOYEE WHERE experience < 1;
emp_name
Edit Copy Delete Diana
19. Employees with more than 5 years experience (department-wise)
SELECT D.dept_name, E.emp_name
FROM DEPARTMENT D
JOIN EMPLOYEE E ON D.dept_no = E.dept_no
WHERE E.experience > 5;
20. List departments with no employees
SELECT dept_name
FROM DEPARTMENT D
LEFT JOIN EMPLOYEE E ON D.dept_no = E.dept_no
WHERE E.emp_id IS NULL;