DBMS Practical
DBMS Practical
Theory:
What is MySQL?
SELECT VERSION();
SHOW DATABASES;
3. Creating a Database
4. Selecting a Database
USE college_db;
5. Creating a Table
A table stores structured data inside a database. The following query creates a students table in
college_db:
SHOW TABLES;
DESCRIBE students;
UPDATE students
SET age = 21
WHERE student_id = 1;
Conclusion:
This experiment introduced the basics of MySQL, including database creation, table management,
data manipulation, and basic commands. Understanding these concepts is essential for managing
relational databases efficiently.
Experiment 2: Data Definition Language (DDL)
Commands
Objective: To understand DDL Commands.
Theory: DDL (Data Definition Language) consists of SQL commands used to define, modify, and
delete database structures such as tables, indexes, and schemas. It does not deal with the
manipulation of data but rather with the structure of database objects.
1. CREATE Command
The CREATE command is used to define new database objects such as databases, tables,
indexes, and views.
Creating a Database:
USE college_db;
This command selects college_db as the active database for executing further operations.
Creating a Table:
CREATE TABLE students (student_id INT PRIMARY KEY,name VARCHAR(50) NOT NULL,age
INT CHECK (age > 17),course_id INT,email VARCHAR(100) UNIQUE);
Creates a students table with constraints such as PRIMARY KEY, NOT NULL, CHECK, and
UNIQUE.
2. ALTER Command
The ALTER command is used to modify the structure of an existing database object, such as
adding or deleting columns in a table.
Adding a Column:
Changes the data type of the age column from INT to SMALLINT.
Renaming a Column:
Dropping a Column:
3. DROP Command
The DROP command is used to delete an entire database, table, or other database object
permanently.
Dropping a Table:
Dropping a Database:
The TRUNCATE command is used to delete all records from a table without removing the
structure of the table.
It is faster than DELETE because it does not log individual row deletions.
Truncating a Table:
Removes all records from the students table but keeps the table structure intact.
5. RENAME Command
Renaming a Table:
student_records.
Conclusion
DDL commands help in defining and managing database structures effectively. They ensure proper
schema organization, facilitate modifications, and provide control over database objects. Unlike
DML commands, DDL commands primarily focus on structure rather than data manipulation.
Practice Questions:
Q1. Write an SQL query to create an employees table with the following columns:
employee_id (Primary Key), name (VARCHAR of length 50, Not Null), age (INTEGER, /* with a
CHECK constraint that age should be greater than 18*/), department_id (INTEGER, Foreign Key
referencing departments table), email (VARCHAR of length 100, Unique), salary (DECIMAL(10,2),
should not be NULL)
Q2. Write an SQL query to add a new column phone_number (VARCHAR 15) to the
employees table.
Q3. Write an SQL query to modify the phone_number column to make it NOT NULL.
Q5. Write an SQL query to remove the phone_number column from the employees
table. Q6. Write an SQL query to create an index on the email column of the employees
table. Q7. Write an SQL query to delete the employees table completely from the
database.
Q8. Write an SQL query to remove all records from the employees table without deleting the
structure.
Q9. Write an SQL query to create a departments table with a default_budget column that has a
default value of 50000.
Q10. Write an SQL query to create a payroll table with the following constraints:
payroll_id as Primary Key, employee_id as Foreign Key referencing employees, pay_date should
not be NULL, payment_status should only allow values 'Pending', 'Completed', 'Failed'
Experiment 3: Data Manipulation Language (DML)
Objective: To understand DML Commands.
Theory:
DML commands are used to manage data stored in database tables. They allow users to insert,
update, delete, and retrieve data.
The WHERE clause is used in SQL to filter records that meet specific conditions. It is primarily
used with SELECT, UPDATE, DELETE, and other SQL statements to restrict the number of rows
affected by a query.
Explanation: Here, age and email are not provided, so they will either be NULL or take default
values.
Deleting All Rows from the Table (But Keeping Table Structure)
DELETE FROM students;
Explanation: This removes all records and resets any auto-incrementing columns.
Explanation: Groups students by course and counts how many are in each course.
Conclusion: DML commands allow efficient manipulation of data within tables, enabling dynamic
data handling.
Practice Questions:
1. Insert a new employee into the employees table with the following details:
(Employee ID: 101, Name: Alice Age: 30, Department ID: 5, Email:
[email protected])
2. Retrieve all employee details from the employees table.
3. Update the age of the employee with employee_id = 101 to 32.
4. Delete the record of the employee with employee_id = 101.
5. Fetch the names and email addresses of employees who belong to department_id = 3.
6. Retrieve all employee details sorted by age in descending order.
7. Retrieve the top 5 youngest employees from the employees table.
8. Fetch details of employees working in department 2, 4, or 6.
9. Retrieve employees whose names start with "A".
10. Fetch details of employees whose age is between 25 and 40.
Experiment 5: To implement concept of Joins.
Objective: To implement concept of Joins.
Theory:
Subqueries and joins are essential SQL concepts used for retrieving data from multiple tables
based on related columns.
Joins combine rows from two or more tables based on a related column, allowing
efficient data retrieval and analysis.
SQL Operators like AND, OR, NOT, EXISTS, UNION, and SET operators enhance
query functionality and filtering capabilities.
Types of Joins:
Join Examples:
2. LEFT JOIN – Retrieve all students and their course names (if enrolled):
3. RIGHT JOIN – Retrieve all courses and the students enrolled in them:
4. FULL JOIN – Retrieve all students and courses (including unmatched ones):
The UNION operator combines the results of two SELECT queries, removing duplicates.
SELECT name FROM students UNION ALL SELECT name FROM instructors;
2. INTERSECT – Retrieve names that exist in both students and instructors tables
(not supported in MySQL, alternative approach using INNER JOIN):
SELECT students.name FROM students
INNER JOIN instructors ON students.name = instructors.name;
3. MINUS (Not directly supported in MySQL, alternative approach using LEFT JOIN):
Conclusion:
Joins allow combining data across multiple tables efficiently.
SQL operators like AND, OR, NOT, EXISTS, UNION, and SET Operators enhance
query performance and flexibility
Practice Questions:
1. Display employee names along with their department names by joining the
employees and departments tables.
2. Retrieve all employees along with their project names, ensuring that employees
without a project are also displayed.
3. Retrieve all projects along with the names of employees assigned to them, ensuring
that projects without employees are also included.
4. Retrieve a list of all employees and all projects, including those that do not have a
match in either table (simulate a FULL JOIN using UNION).
5. Retrieve employees who are assigned to at least one project using the EXISTS operator.
6. Retrieve a combined list of all employees and all clients without duplicates
using UNION.
7. Retrieve the names of employees who are also listed as clients using an INNER
JOIN (since MySQL does not support INTERSECT)
Experiment 7: Subqueries
Theory:
Subqueries and joins are essential SQL concepts used for retrieving data from multiple tables
based on related columns.
Subqueries (or nested queries) are queries within another SQL query. They return results
that are used by the main (outer) query.
.
Types of Subqueries:
1. Single-row subqueries – Returns a single value.
2. Multi-row subqueries – Returns multiple values.
3. Correlated subqueries – The inner query depends on the outer query for each row.
Subquery Examples:
Practice Questions:
1. Retrieve the names of employees who work in the same department as 'John' using
a subquery.
2. Find employees who earn more than the average salary of all employees.
3. Retrieve employees who have been assigned at least one project using a
correlated subquery.
4. Display employee names along with their department names by joining the
employees and departments tables.
5. Retrieve all employees along with their project names, ensuring that employees
without a project are also displayed.
Theory:
A View is a virtual table that does not store data itself but presents data retrieved from one or more
underlying tables through a SELECT query. Views are used to simplify complex queries, enhance
security, and improve readability.
1. Simplicity – Views allow users to interact with complex queries as if they were simple
tables.
2. Security – Views restrict access to specific columns or rows, hiding sensitive data
from unauthorized users.
3. Data Abstraction – The structure of the underlying tables can change without
affecting queries that use views.
4. Reusability – Views can be used repeatedly in queries without rewriting complex joins
or filters.
A view can be created using the CREATE VIEW statement. The following example creates a view
displaying student names, ages, and course details from the students table.
CREATE VIEW student_details AS
SELECT name, age, course_id FROM students;
2. Accessing Data from a View
To retrieve data from a view, we use a SELECT statement just like we would for a normal table.
SELECT * FROM student_details;
Views can be created using JOIN to combine data from multiple tables. The following query creates
a view showing student names along with their enrolled course names.
CREATE VIEW student_course_details AS
SELECT students.name, students.age, courses.course_name
FROM students
INNER JOIN courses ON students.course_id = courses.course_id;
A view can include conditions to restrict data. The following query creates a view that includes only
students from the Computer Science course.
A view can include aggregate functions like COUNT, SUM, AVG, etc. The following example
creates a view that displays the total number of students in each course.
If a view is created from a single table without aggregate functions, it can be updated using an
UPDATE statement.
Note: If a view contains JOIN, GROUP BY, or DISTINCT, updating it directly might not be
allowed.
Views simplify complex queries by allowing users to access pre-defined query results
as tables.
They enhance security by restricting direct access to certain columns or rows.
Views are useful for creating reports and hiding complex joins from end-users.
Updating or deleting data through views is possible, but not all views are updatable due
to their complexity.
Practice Questions:
1. Create a view to display employee name, age, and salary.
2. Create a view to display employee name and department name by joining
employees and departments tables.
3. Create a view to display employees who earn more than 55000.
4. Create a view that shows the total number of employees in each department.
5. Create a view that shows the average salary in each department.
6. Create a view that includes employees above the age of 30.
7. Create a view for employees working in the IT or Finance department using the
IN operator.
8. Create a view that excludes employees from the HR department using NOT IN.
9. Update the high_salary_employees view to change the salary of Alice to 65000.
Drop the view high_salary_employees
Theory: In this chapter, we will discuss the Basic Syntax of PL/SQL which is
a block-structured language; this means that the PL/SQL programs are
divided and written in logical blocks of code. Each block consists of three sub-
parts −
S.N
Sections & Description
o
Declarations
1 This section starts with the keyword DECLARE. It is an optional section and defines
all variables, cursors, subprograms, and other elements to be used in the program.
Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory
2 section. It consists of the executable PL/SQL statements of the program. It should have
at least one executable line of code, which may be just a NULL command to
indicate that nothing should be executed.
Exception Handling
3 This section starts with the keyword EXCEPTION. This optional section
contains exception(s) that handle errors in the program.
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be
nested within other PL/SQL blocks using BEGIN and END. Following is the
basic structure of a PL/SQL block −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
The end; line signals the end of the PL/SQL block. To run the code from the
SQL command line, you may need to type / at the beginning of the first blank
line after the last line of the code. When the above code is executed at the
SQL prompt, it produces the following result −
Hello World
A View is a virtual table that does not store data itself but presents data retrieved from one or more
underlying tables through a SELECT query. Views are used to simplify complex queries, enhance
security, and improve readability.