DBMS Ex1to5
DBMS Ex1to5
1
PRACTICE ON DDL AND DML COMMANDS
AIM:
To create a database table, add constraints (primary key, unique, check, not null), insert rows, update
and delete rows using SQL DDL and DML commands.
DDL COMMANDS:
DDL is an abbreviation for Data Definition Language. It is concerned with database schemas and
descriptions of how data should be stored in the database. DDL statements are auto-committed,
meaning the changes are immediately made to the database and cannot be rolled back.
DDL is used to:
Create an object
Alter the structure of an object
Drop the object created.
The commands used are: Create, Alter, Drop, Truncate
CREATE DATABASE
It creates a database with the given name. An error occurs if the database exists and you did not
specify IF NOT EXISTS.
USE
Creating a database does not select it for use. It must be done explicitly.
CREATE TABLE
It is used to create a table. To set default value for a column DEFAULT keyword is used.
CONSTRAINTS
Constraints are certain conditions or restrictions applied to the columns on the table. Some of
the constraints are
PRIMARY KEY
UNIQUE
CHECK
NOT NULL
PRIMARY KEY
A primary key is the column or set of columns that contain values that uniquely identify each row
in a table.
UNIQUE
Unique ensures there are no duplicate values stored in a particular column or a set of
columns.
CHECK
Check constraint ensures to enter only those values which fulfill the specified condition.
NOT NULL
The not null constraint is used to ensure that a given column of a table is never assigned the null
value.
Example: create table stud_001(sno int primary key, sname varchar(20) not null, email varchar(30)
unique, age int check (age >= 16), sdob date default '2001-01-01', sm1 float, sm2 float,
sm3 float);
ALTER
Alter command is used to
Add a column.
Syntax: Alter table table_name add column_name datatype;
Example: Alter table stud_001 add (sm4 float);
Drop a column
Syntax: Alter table table_name drop column column_name;
Example: Alter table stud_001 drop column age;
DROP
Drop table will delete the table structure.
TRUNCATE
If there is no further use of records stored in a table and the structure has to be retained then the
records alone can be deleted.
DML COMMANDS:
DML commands are the most frequently used SQL commands and is used to query and
manipulate the existing database objects. Some of the commands are Insert, Select, Update,
Delete
INSERT
Insert Statement is used to insert new records into the database table.
SELECT
Select statement is used to retrieve data from tables.
UPDATE
Update statement is used to modify the existing values of records present in the
database table.
Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ...[WHERE condition];
DELETE
Delete statement is used to delete the existing records present in the database table.
Syntax: DELETE FROM table_name [where condition];
6. Update the email id of the employee whose employee_id is 1234. After update retrieve the
records.
8. Update the value of the column created with 5% of the salary. After update retrieve the
records.
9. Delete the column whose bonus falls below 600. After delete retrieve the records.
AIM:
To create a set of tables, add foreign key constraints and incorporate referential integrity.
REFERENTIAL INTEGRITY
Referential integrity is a property of data stating that all its references are valid. Referential integrity
refers to the accuracy and consistency of the relationship between tables. It is achieved with the help
of foreign key.
FOREIGN KEY
Foreign keys link data in one table to the data in another table. A foreign key column in a table
points to a column with unique values in another table (often the primary key column) to create a
way of cross-referencing the two tables. The table with the foreign key is called the child table, and
the table with the primary key is called the referenced or parent table.
1 1
Country Capital of City
Alter table country add constraint fk_capcode foreign key (capital) references city(citycode);
m 1
Employee Works for Department
alter table emp_001 add constraint fk_deptno foreign key (deptno) references dept_001(deptno);
m n
Author writes Book
Alter table au_writes add constraint fk_rel1 foreign key (authorid) references author(authorid);
Alter table au_writes add constraint fk_rel2 foreign key (isbn) references book(isbn);
Worksheet 2
1. Draw the ER diagram for the following hospital management system and convert them to
relations
Hospital staff consist of doctors.
Each doctor has a empid, name (first name, middle name, and last name), and phone
numbers, date of joining, specialization.
Each doctor belongs to a specific department in the hospital.
Doctors treat patients.
Patient information collected by the hospital consists of patientID, name, phonenumber,
date of registration.
A patient can undergo a number of tests.
Doctors perform tests.
Each test has a unique ID, name, a result, and a date and time the test was performed.
AIM
To query the database tables using different ‘where’ clause conditions and aggregate functions.
AGGREGATE FUNCTIONS
An aggregate function performs a calculation on a set of values and returns a single value. These
functions can be used with the SELECT statement to generate summary information, such as the
number of rows in a table or the average value of a column. Some of the aggregate functions are
AVG, COUNT, SUM, MAX, MIN
values.
SUM Return the summation of all non- select sum(m4) from sum(m4)
NULL values a set. student_marks; 130
MAX Return the highest value (maximum) select max(m1) from max(m1)
in a set of non-NULL values. student_marks; 42
MIN Return the lowest value (minimum) select min(m2) from min(m2)
in a set of non-NULL values. student_marks; 23
GROUP BY
The GROUP BY clause groups a set of rows into a set of summary rows based on column values or
expressions. It returns one row for each group and reduces the number of rows in the result set.
The group by clause is an optional part of the select statement.
HAVING
The HAVING clause is used in conjunction with the GROUP BY clause to filter the groups based on
a specified condition. The HAVING clause allows you to apply a condition to the groups returned by
the GROUP BY clause and only include groups that meet the specified condition.
ORDER BY
The ORDER BY keyword is used to sort the result-set in ascending or descending
order.The ORDER BY keyword sorts the records in ascending order by default. To sort the records
in descending order, use the DESC keyword.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
[ORDER BY column_name(s)];
dept count(*)
cse 2
ece 1
dept c
cse 2
dept c
cse 2
ece 1
To retrieve the count of students in each department displayed in descending order of dept
select dept,count(*) as c from student_marks group by dept order by dept desc;
dept c
ece 1
cse 2
Worksheet 3
2. Display the details of employees whose salary is in the range 15000 to 20000.
3. Display the details of employees who works in ‘CSE’ department and get salary above
15000.
4. Display the details of employees who works in ‘CSE’ department or ‘ECE’ department.
5. Display the details of manager, electrician and technician.
6. Display the name of employees whose name ends with ‘an’.
7. Display the name of employees whose name does not have ‘n’ as the fourth character.
8. Display the details of employees whose Date_of_birth is left blank.
9. Display the lowest and highest salary of the employees.
10. Display the number of employees in the organization.
11. Display the number of employees in each department.
12. Display the average salary of employees in each department
13. Display the total salary of all the employees in each department
14. Calculate the age of each employee.
15. Calculate the years of experience (approximately) of each employee.
Ex. No. 4
PRACTICE ON SUBQUERIES
AIM
To query the database tables and explore sub queries.
SUBQUERY
A subquery is a query that is used within another SQL query embedded in the WHERE clause. They
allow us to select specific rows that satisfy certain conditions at the run time. They are also known as
the inner query or inner select, and the query that contains them is known as the outer query or outer
select. Subqueries are majorly used in SELECT, INSERT, UPDATE, DELETE, FROM and
WHERE clauses. The subqueries are used wherever an expression is allowed. The data returned by
the subquery is used by the outer statement in the same way a literal value would be used.
TYPES OF SUBQUERY
Single row subquery
Multi row subquery
Multi column subquery
Nested subquery
Correlated subquery
ISBN title
Authorid name
price
m n
Author writes Book
Author
authorid name
123 ccc
124 ddd
125 eee
126 fff
Book
isbn title price
1 b1 1000
2 b2 1500
3 b3 2000
Au_writes
authorid isbn
123 1
124 1
125 2
123 3
Example: To retrieve the details of the book whose price is less than or equal to the average
price of all books
select * from book where price <= (select avg(price) from book);
Output:
isbn title price
1 b1 1000
2 b2 1500
The subquery in the above example retrieves only one average price(1500) which is used in the
where clause.
Select * from author where authorid in (select authorid from auwrites where isbn=1);
Output:
authorid name
123 ccc
124 ddd
Since many author can write one book, the subquery in the above example retrieves more than one
authorid which is used in the where clause.
Example: To retrieve the details of the book whose price is less than or equal to the average
price of all books
Select * from book where (isbn,price) in (select isbn,price from book where price <= (select
avg(price) from book));
Output:
isbn title price
1 b1 1000
2 b2 1500
The subquery in the above example retrieves multiple column namely isbn,price which is used in the
where clause.
NESTED SUBQUERY
Subqueries that are inside another subquery are called nested subqueries. Subqueries are executed
level by level. The innermost is executed first, and then the outer ones.
Example: To retrieve the details of the author who wrote the book that cost the least
Select * from author where authorid in (select authorid from au_writes where isbn in (select isbn
from book where price = (select min(price) from book)));
Output:
authorid name
123 ccc
124 ddd
In the above example there are three levels of nested where the execution of outer query depends on
inner query.
CORRELATED SUBQUERY
A correlated subquery is a subquery that depends on the outer query and is evaluated for each
instance of the outer query.
Example: To retrieve the details of the author along with the number of books written by them
In the above example, for each row in the author table, the subquery is executed by matching their
authorid.
Example: To retrieve the details of the author who have written at least one book
Output:
authorid name
123 ccc
124 ddd
125 eee
Example: To retrieve the details of the author who have not written any book
Select * from author where not exists (select * from au_writes where
author.authorid=au_writes.authorid);
Output:
authorid name
126 fff
Worksheet 4
Queries
1. Display the details of the account holder who have more number of loans.
2. Display the details of the account holder who have not taken any loan.
3. Display the loanno, loan amount, number of installments of the loan holder who have
paid EMI on December 3rd 2023.
4. Display the loanno, loanamount and total EMI paid for all the loan holders
5. Add thousand rupees to the EMI of loan holder whose account balance is greater
than 50000
Ex. No. 5
PRACTICE ON JOINS
AIM
To query the database tables and explore cross join, inner join, equi join, non-equi join, self join,
natural join and outer joins.
JOIN OPEARTION
Joins are mostly used when a user is trying to retrieve data from multiple tables at one time. The join
keyword merges two or more tables and creates a temporary image of the merged table. Then
according to the conditions provided, it extracts the required data from the image table, and once
data is fetched, the temporary image of the merged tables is dumped.
TYPES OF JOIN
Cross join
Inner join
o Equi join
o Non-Equi join
o Self join
o Natural join
Outer join
o Left outer join
o Right outer join
o Full outer join
CROSS JOIN
The CROSS JOIN is used to generate a paired combination of each row of the first table with each
row of the second table. This join type is also known as cartesian product.
Output:
authorid name isbn title price
123 ccc 3 b3 2000
123 ccc 2 b2 1500
123 ccc 1 b1 1000
124 ddd 3 b3 2000
124 ddd 2 b2 1500
124 ddd 1 b1 1000
125 eee 3 b3 2000
125 eee 2 b2 1500
125 eee 1 b1 1000
126 fff 3 b3 2000
126 fff 2 b2 1500
126 fff 1 b1 1000
INNER JOIN
The inner join retrieves the records that matches a condition from the result of the cartesian product.
EQUI JOIN
EQUI JOIN creates a JOIN for equality or matching column(s) values of the relative tables. EQUI
JOIN also create JOIN by using JOIN with ON and then providing the names of the columns with
their relative tables to check equality using equal sign (=).
SELF JOIN
A self join is an inner join where a table is joined with itself.
Syntax: select column_name(s) from table1 t1 inner join table1 t2 where condition;
Here t1 and t2 are different table aliases for the same table.
Output:
authorid name authorid name
123 ccc 123 ccc
124 ddd 124 ddd
125 eee 125 eee
126 fff 126 fff
Natural join
Natural Join is a type of Inner join based on the condition that columns having the same name and
datatype are present in both the tables to be joined.
Output:
authorid name isbn
123 ccc 1
123 ccc 3
124 ddd 1
125 eee 2
OUTER JOIN
Outer join return all records matching from both tables. It can detect records having no match in
joined table. It returns NULL values for records of joined table if no match is found.
Output:
authorid name authorid isbn
123 ccc 123 1
123 ccc 123 3
124 ddd 124 1
125 eee 125 2
126 fff NULL NULL
Output:
authorid isbn authorid name
123 1 123 ccc
123 3 123 ccc
124 1 124 ddd
125 2 125 eee
NULL NULL 126 fff
Syntax: Select column_list from table1 left join table2 on join_condition union Select column_list
from table1 right join table2 on join_condition;
Output:
authorid name authorid isbn
123 ccc 123 1
123 ccc 123 3
124 ddd 124 1
125 eee 125 2
126 fff NULL NULL