DBMS Record
DBMS Record
WEEK 6
Date: 09/03/24
Aggregate functions
Grouping (Group by, Having)
Sorting
AGGREGATE FUNCTIONS:
Syntax :
consider a table;
The GROUP BY clause is used in SQL to group rows that have the same values into summary rows. It is often
used in conjunction with aggregate functions like SUM, COUNT, AVG, MAX, and MIN.
Syntax:
Employees Table:
a. Get the total salary for each department where the total salary is greater than $500:
select department, sum(salary) as total_salary from employees group by department having sum(salary) >
500;
b. Get the number of orders and the total order amount for each employee who has placed more
than 1 orders:
228W1A12J1
Syntax :
SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC |
DESC];
228W1A12J1
WEEK 7
Date: 16/03/24
Task-1:
I.Consider the following schema for a Library Database:
BOOK (Book_id p, Title, Publisher_Name f, Pub_Year)
Library_branch tale:
Publisher table:
Book1 table:
Book_copies table:
Book_lending table:
mysql> create table book_lending(card_no int(50) primary key,date_out date, due_date date,book_id
varchar(50),branch_id int(50),foreign key(book_id) references book1(book_id),foreign key(branch_id)
references library_branch(branch_id));
Book_author table:
1. Retrieve details of all books in the library – id, title, name of publisher, authors, number of
copies in each branch, etc.
mysql> select book1.book_id, book1.title, book1.publisher_name, book_copies.no_of_copies,
book_author.author_name from book1, book_copies,book_author where
book1.book_id=book_copies.book_id and book1.book_id=book_author.book_id;
228W1A12J1
2. Get the particulars of borrowers who have borrowed more than 3 books, but from Jan 2017 to
Jun 2017
mysql> select b.card_no,count(*) as borrowed from book_lending b where b.date_out between '2024.01.01'
and '2024.06.01' group by b.card_no having count(*)>=1;
3. Delete a book in BOOK table. Update the contents of other tables to reflect this data
manipulation operation.
mysql> delete from book_copies where book_id='1188';
4. Partition the BOOK table based on year of publication. Demonstrate its working with a simple
query.
mysql> create view yr2000 as select * from book1 where pub_year='2000';
5. Create a view of all books and its number of copies that are currently available in the Library.
mysql> create view view1 as select b.book_id,c.no_of_copies from book1 b,book_copies c where
b.book_id=c.book_id;
Task-2:
SALESMAN(Salesman_id p,Name,City,Commission)
CUSTOMER (Customer_idp,Cust_Name,City,Grade,Salesman_id f)
Database creation:
customer table:
mysql> create table customer (c_id varchar(10) primary key,c_name varchar(100),city varchar(15),grade
int(1),s_id varchar(10),foreign key(s_id) references salesman(s_id));
mysql> insert into customer values ("234","rosie","ohoi","4","789"),("567","emma","mexico",'5',"123"),
('890','luna','mexico','3','123'),('999','olivia','sweden','3','456');
mysql> select * from customer;
228W1A12J1
orders table:
mysql> create table orders1 (o_no int primary key,p_am decimal(10,5),o_date date,c_id varchar(10),s_id
varchar(10), foreign key(c_id) references customer(c_id), foreign key(s_id) references salesman(s_id));
mysql> insert into orders1 values (45,'120000.78','2024.01.03','234','789'),
(77,'30000','2024.02.11','567','123'),(89,'23000.09','2023.12.12','890','123'),
(101,'56000','2023.11.12','999','456');
mysql> select * from orders1;
mysql> select count(*) as above_grades from customer where grade>(select avg(grade) from customer
where city="mexico") and city!="mexico";
2. Find the name and numbers of all salesmen who had more than one customer.
228W1A12J1
mysql> select s.s_name,count(*) as total_customers from salesman s,customer c where s.s_id=c.s_id group
by s.s_id having count(*)>1;
3. List all salesmen and indicate those who have and don’t have customers in their cities (Use UNION
operation.)
mysql> select s.s_id,s.s_name,"has customer" as status from salesman s where s.s_id in (select distinct s_id
from customer) union select s.s_id,s.s_name,"no customer" as status from salesman s where s.s_id in (select
distinct s_id from customer);
4. Create a view that finds the salesman who has the customer with the highest order of a day.
mysql> create view view4 as select s.s_name,max(o.p_am) from salesman s,orders1 o where s.s_id=o.s_id
group by s_name;
mysql> select * from view4;
+-----------+--------------------+
| s_name | max(o.p_am) |
+-----------+-------------------+
| Don | 99999.99999 |
| David | 30000.00000 |
| Rheo | 56000.00000 |
+-----------+-------------------+
5. Demonstrate the DELETE operation by removing salesman with id 1000.All his orders must also
be deleted.
mysql> delete from orders1 where s_id="123";
mysql> delete from customer where s_id="123";
mysql> delete from salesman where s_id="123";
mysql> select * from orders1;
228W1A12J1
Task-3:
III. Create the following tables with appropriate data types and Integrity constraints:
PERSON(driver_id, name, address)
Person table:
mysql> create table person1 (d_id char(10) primary key,d_name char(100),address char(100));
Participate table:
2. Display the ids of drivers whose damage_amount is > 50000 and who belongs to Vijayawada
mysql> select o.d_id from person1 o,participate p where p.damage_amount>10000 and o.address like "%,vij"
and o.d_id=p.d_id;
Task-4:
CAR(regno, model,year )
Person table:
mysql> create table person (driver_id int primary key,name varchar(50),address varchar(100),carregno
varchar(10), gender char(1),foreign key(carregno) references car(regno));
Car table:
mysql> create table car (regno varchar(50) primary key, model varchar(20),year year);
2. Display the names and driver ids of persons who had a car model before year 2020
WEEK 8
228W1A12J1
Date: 23/03/24
select e.first_name, e.last_name, e.dept_id, d.location from employee e, department d where e.dept_id =
d.dept_id and e.dept_id <> d.location;
2. Find all employees who salaries are greater than the average salary of all employees
select first_name, last_name, salary from employee where salary > (select avg(salary) from employee);
228W1A12J1
3. Find all departments which have at least one employee with the salary is greater than 10,000
select distinct d.dept_name from department d where exists ( select 1 from employee e where e.dept_id =
d.dept_id and e.salary > 10000 );
4. Retrieve the lowest salary by department SELECT departname-id, MIN(salary) FROM employees
GROUP BY department_id ORDER BY MIN(salary)DESC;
5. Get all employees whose salaries are greater than the lowest salary of every department
select first_name, last_name, salary from employee e1 where e1.salary > ( select min(salary) from employee
e2 where e2.dept_id = e1.dept_id );
228W1A12J1
6. Find all employees whose salaries are greater than or equal to the highest salary of every
department.
select first_name, last_name, salary from employee e1 where e1.salary >= ( select max(salary) from
employee e2 where e2.dept_id = e1.dept_id );
7. Retrieve the salaries of all employees, their average salary, and the difference between the salary
of each employee and the average salary.
select salary, (select avg(salary) from employee) as avg_salary, salary - (select avg(salary) from employee) as
diff_from_avg from employee;
select first_name, last_name, salary from employee where salary = ( select max(salary) from employee);
228W1A12J1
9. Find all departments that do not have any employee with the salary greater than 10,000
select dept_name from department d where not exists ( select 1 from employee e where e.dept_id =
d.dept_id and e.salary > 10000 );
WEEK 9
Date: 06.04.24
a. ANY operator
returns a boolean value as a result , returns TRUE if ANY of the subquery values meet the condition
ANY means that the condition will be true if the operation is true for any of the values in the range.
ANY Syntax
SELECT column_name(s) FROM table_name WHERE column_name operator ANY (SELECT column_name
FROM table_name WHERE condition);
Command:
select all employees who have a salary greater than ANY of the salaries of employees in the "IT" department
b. All:
SELECT column_name(s) FROM table_name WHERE column_name operator ALL (SELECT column_name
FROM table_name WHERE condition);
Command:
selects all employee names from the "employees" table where the salary is greater than 50000.
c. Some:
SOME operator evaluates the condition between the outer and inner tables and evaluates to true if the final
result returns any one row. If not, then it evaluates to false.
The SOME and ANY comparison conditions are similar to each other and are completely interchangeable.
SOME must match at least one row in the subquery and must be preceded by comparison operators.
Syntax:
Command:
selects the names of employees whose salary is greater than at least one salary in the HR department.
228W1A12J1
d. Exists:
The EXISTS operator is used to test for the existence of any record in a subquery.
The EXISTS operator returns TRUE if the subquery returns one or more records.
EXISTS Syntax
SELECT column_name(s) FROM table_name WHERE EXISTS (SELECT column_name FROM table_name WHERE
condition);
Command:
select the names of employees who have a salary greater than 60000
e. IN :
Syntax :
NOT IN
Command:
228W1A12J1
selects all columns from the "employees" table where the department is either 'HR' or 'IT'.
selects all columns from the "employees" table where the department is located in India, based on the
"departments" table
selects all columns from the "employees" table where the department is located in India, based on the
"departments" table.
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.
228W1A12J1
GROUP BY Syntax
The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate
functions.
HAVING Syntax
Command:
Between
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2;
command:
selects all columns from the "employees" table where the salary falls within the range of 50000 to 70000
228W1A12J1
SQL Operators:
The SQL Set operation is used to combine the two or more SQL SELECT statements.
1. Union
2. UnionAll
3. Intersect
4. Minus
1.Union:
The SQL Union operation is used to combine the result of two or more SQL SELECT queries. In the union
operation, all the number of datatype and columns must be same in both the tables on which UNION
operation is being applied. The union operation eliminates the duplicate rows from its resultset.
Syntax
2.Union All:
Union All operation is equal to the Union operation. It returns the set without removing duplication and
sorting the data.
Syntax:
SELECT column_name FROM table1 UNION ALL SELECT column_name FROM table2;
3. Intersect:
It is used to combine two SELECT statements. The Intersect operation returns the common rows from both
the SELECT statements. In the Intersect operation, the number of datatype and columns must be the same. It
has no duplicates and it arranges the data in ascending order by default.
Syntax
4.Minus:
It combines the result of two SELECT statements. Minus operator is used to display the rows which are
present in the first query but absent in the second query. It has no duplicates and data arranged in ascending
order by default.
Syntax:
WEEK 10
Date: 13/04/2024
AIM:
Implement advanced queries using joins and grouping (Group by, Having)
Queries:
Equi Join:
Non-Equi Join:
select e.*, d.department_name from employees e join departments d on e.salary> (select avg(salary) from
employees);
Self-Join:
Group by , having:
create table student(sid int primary key,sname varchar(20),sadd varchar(30),sage int(2),sphn int);
Find out names of STUDENTs who have either enrolled in „DSA‟ or „DBMS
select s.sname from student s where s.sidin( select sc.sid from studentcoursesc where sc.cidin( select c.cid
from course c where c.cname='dsa' or c.cname='dbms') );
Find out S_IDs of STUDENTs who have neither enrolled in „DSA‟ nor in „DBMS‟
select s.sid from student s where s.sidin( select sc.sid from studentcoursesc where sc.cid in ( select c.cid
from course c where c.cname<>'dsa' and c.cname<>'dbms' ) );
228W1A12J1
select s.sname from student s where s.sidin ( select sc.sid from studentcourses c where sc.cidin ( select c.cid
from course c wherec.cid='c1'));
228W1A12J1
WEEK 11
Date: 20.04.24
First let us create the database, relations and insert the values into the relations:
Database Company:
Department table:
Employee table:
salary_grade table:
mysql> create table salary_grade (grade integer primary key,min_salary integer,max_salary integer);
Practice queries:
4. find those employees with hire date in the format like February 22, 1991
11. Identify those employees whose salaries exceed 3000 after receiving a 25% salary increase.
16. find those employees whose salaries are less than 3500
17. find those employees who joined before 1st April 1991
mysql> select emp_name from employee where date_format(hire_date,'%est %M %Y')<'1st April 1991';
19. find out which employees earn more than 100 per day as a salary.
21. find those employees whose designation is ‘CLERK’ and work in the department ID 2001
22. find those employees who are either CLERK or MANAGER and identify those employees who joined
in any month other than February
23. Search for all employees with an annual salary between 24000 and 50000
mysql> select emp_name from employee where salary between 24000 and 50000;
24. find out which employees are working under the managers 63679, 68319, 66564, or 69000
mysql> select emp_name from employee where year(hire_date) between 1990 and 1999;
26. find those managers who are in the department 1001 or 2001
mysql> select emp_name from employee where job_name="manager" and dep_id in(1001,2001);
28. identify employees whose salaries are higher than their managers' salaries
29. find those employees whose salary is between 2000 and 5000 (Begin and end values are included.)
and location is PERTH
mysql> SELECT * FROM employee WHERE salary BETWEEN 2000 AND 5000 AND dep_id = (SELECT dep_id
FROM department WHERE dep_loc = 'PERTH');
WEEK-12
27/04/2024
Aim: ER diagrams
Bank Entity : Attributes of Bank Entity are Bank Name, Code and Address.
Code is Primary Key for Bank Entity.
Customer Entity : Attributes of Customer Entity are Customer_id, Name, Phone Number and
Address.
Customer_id is Primary Key for Customer Entity.
Branch Entity : Attributes of Branch Entity are Branch_id, Name and Address.
Branch_id is Primary Key for Branch Entity.
Account Entity : Attributes of Account Entity are Account_number, Account_Type and Balance.
Account_number is Primary Key for Account Entity.
Loan Entity : Attributes of Loan Entity are Loan_id, Loan_Type and Amount.
Loan_id is Primary Key for Loan Entity.
Relationships are :
Hotel management:
1. Hotel: The main physical establishment providing lodging and hospitality services to guests.
2. Rooms: Space within the hotel premises for guest accommodation, typically equipped with furniture
and amenities.
3. Departments: Segments within the hotel organization responsible for specific functions such as
housekeeping, food and beverage, maintenance, and management. Some of the departments may be
as:
4. Guests: Individuals or groups who rent the hotel or accommodation facility.
5. Reservation: The process of securing a room or accommodation for a specific period in advance.
6. Staff: Employees of the hotel who carry out various roles and responsibilities, including management,
reception, housekeeping, and catering.
1. Guest:
2. Hotel:
3. Reservation:
4. Department:
5. Staff:
6. Room:
One hotel can have many rooms, but each room belongs to only one hotel.
228W1A12J1
The relationship between the hotel and its rooms is a one-to-many relationship.
A guest can make multiple reservations, but each reservation is made by only one guest.
A reservation is for one room, but each of the rooms can be reserved multiple times.
Each staff member works in one department, but each department can have multiple staff members.
Each hotel has multiple departments, such as Front Desk, Housekeeping, Food and Beverage,
Maintenance, and Management.
This is a one-to-many relationship, as one hotel can have multiple departments, but each department
belongs to only one hotel.