0% found this document useful (0 votes)
48 views6 pages

DBMS Lab Programs and Queries in SQL

The document outlines various DBMS lab programs focusing on SQL operations including creating, altering, and dropping tables with constraints, inserting data, and querying data using SELECT commands. It also covers advanced querying techniques using subqueries, aggregate functions, and the creation and dropping of views. Examples are provided for each operation, demonstrating the use of SQL commands for managing and retrieving data effectively.

Uploaded by

likhithakonda28
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views6 pages

DBMS Lab Programs and Queries in SQL

The document outlines various DBMS lab programs focusing on SQL operations including creating, altering, and dropping tables with constraints, inserting data, and querying data using SELECT commands. It also covers advanced querying techniques using subqueries, aggregate functions, and the creation and dropping of views. Examples are provided for each operation, demonstrating the use of SQL commands for managing and retrieving data effectively.

Uploaded by

likhithakonda28
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

DBMS LAB PROGRAMS

[Link], altering and droping of tables and inserting rows into a table (use
constraints while creating tables) examples using SELECT command.
1. Create Table with Constraints

Create a table Employees with constraints like PRIMARY KEY, NOT NULL, and UNIQUE:

CREATE TABLE Employees (


EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Email VARCHAR(100) UNIQUE,
DepartmentID INT NOT NULL
);

CREATE TABLE Departments (


DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(50) UNIQUE NOT NULL
);

2. Insert Rows into Tables

Insert data into the Departments and Employees tables:

-- Insert into Departments


INSERT INTO Departments (DepartmentID, DepartmentName)
VALUES (1, 'HR'), (2, 'IT'), (3, 'Finance');

-- Insert into Employees


INSERT INTO Employees (EmployeeID, FirstName, LastName, Email, DepartmentID)
VALUES
(101, 'Alice', 'Smith', '[Link]@[Link]', 1),
(102, 'Bob', 'Brown', '[Link]@[Link]', 2),
(103, 'Carol', 'Taylor', '[Link]@[Link]', 3);

3. Use SELECT to Verify Data

Fetch the data using SELECT:

-- Select all data from Employees


SELECT * FROM Employees;

-- Select employees in a specific department (e.g., 'IT')


SELECT [Link], [Link], [Link]
FROM Employees e
JOIN Departments d ON [Link] = [Link]
WHERE [Link] = 'IT';

4. Alter Table to Add a New Column

Add a DateOfJoining column to the Employees table:

ALTER TABLE Employees


ADD DateOfJoining DATE;

-- Update existing rows to include joining dates


UPDATE Employees
SET DateOfJoining = '2022-01-15'
WHERE EmployeeID = 101;

UPDATE Employees
SET DateOfJoining = '2023-03-01'
WHERE EmployeeID = 102;

UPDATE Employees
SET DateOfJoining = '2021-07-20'
WHERE EmployeeID = 103;

-- Verify the change


SELECT * FROM Employees;

5. Drop a Table

Drop the Employees table:

DROP TABLE Employees;

2. Queries (along with sub Queries) using ANY, ALL, IN, EXISTS,
NOTEXISTS, UNION, INTERSET, Constraints. Example:- Select the roll
number and name of the student who secured fourth rank in the class.

1. Create Table with Constraints


CREATE TABLE Students (
RollNumber INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Marks INT NOT NULL,
Rank INT UNIQUE
);
2. Insert Sample Data
INSERT INTO Students (RollNumber, Name, Marks, Rank)
VALUES
(1, 'Alice', 95, 1),
(2, 'Bob', 90, 2),
(3, 'Carol', 85, 3),
(4, 'David', 80, 4),
(5, 'Eve', 75, 5);
3. Find the Roll Number and Name of the Student with the 4th Rank
Using Subquery:
SELECT RollNumber, Name
FROM Students
WHERE Rank = (SELECT MIN(Rank) FROM Students WHERE Rank > 3);
4. Using ANY
Find students who scored more than any student ranked below them:
SELECT Name
FROM Students
WHERE Marks > ANY (SELECT Marks FROM Students WHERE Rank > 5);
5. Using ALL
Find students who scored higher than all students ranked below them:
SELECT Name
FROM Students
WHERE Marks > ALL (SELECT Marks FROM Students WHERE Rank > Rank);
6. Using IN
Find students whose rank is in the top three:
SELECT Name, Rank
FROM Students
WHERE Rank IN (1, 2, 3);
7. Using EXISTS
Find students whose marks are greater than 80 (using EXISTS):
SELECT RollNumber, Name
FROM Students s
WHERE EXISTS (SELECT 1 FROM Students WHERE Marks > 80 AND RollNumber = [Link]);
8. Using NOT EXISTS
Find students who did not score below 80:
SELECT RollNumber, Name
FROM Students s

WHERE NOT EXISTS (SELECT 1 FROM Students WHERE Marks < 80 AND RollNumber = [Link]);
9. Using UNION
Combine students scoring above 90 and those ranked in the top 2:
SELECT Name, Marks FROM Students WHERE Marks > 90
UNION
SELECT Name, Marks FROM Students WHERE Rank <= 2;
10. Using INTERSECT
Find students scoring above 85 who are also ranked in the top 3:
SELECT Name FROM Students WHERE Marks > 85
INTERSECT
SELECT Name FROM Students WHERE Rank <= 3;
______________________________________________________________________________

[Link] using Aggregate functions (COUNT, SUM, AVG, MAX and MIN),
GROUP BY, HAVING and Creation and dropping of Views.

1. Aggregate Functions with Example Queries

Example Table: Sales

CREATE TABLE Sales (


SaleID INT PRIMARY KEY,
ProductName VARCHAR(100),
Quantity INT,
Price DECIMAL(10, 2),
SaleDate DATE
);

-- Inserting some data into the Sales table


INSERT INTO Sales (SaleID, ProductName, Quantity, Price, SaleDate)
VALUES
(1, 'Laptop', 2, 1200.00, '2025-01-01'),
(2, 'Smartphone', 5, 500.00, '2025-01-02'),
(3, 'Tablet', 3, 300.00, '2025-01-03'),
(4, 'Laptop', 1, 1200.00, '2025-01-04'),
(5, 'Smartphone', 2, 500.00, '2025-01-05');

Example Queries:

● COUNT: Find the number of sales made.

SELECT COUNT(SaleID) AS NumberOfSales FROM Sales;

● SUM: Calculate the total sales revenue (Quantity * Price).

SELECT SUM(Quantity * Price) AS TotalRevenue FROM Sales;

● AVG: Find the average price of all products sold.

SELECT AVG(Price) AS AveragePrice FROM Sales;

● MAX: Find the highest price of a product sold.

SELECT MAX(Price) AS MaxPrice FROM Sales;

● MIN: Find the lowest quantity of products sold in a transaction.


SELECT MIN(Quantity) AS MinQuantity FROM Sales;

2. GROUP BY and HAVING with Aggregate Functions

● GROUP BY: Find the total quantity sold for each product.

SELECT ProductName, SUM(Quantity) AS TotalQuantity


FROM Sales
GROUP BY ProductName;

● HAVING: Find products that have sold more than 3 units.

SELECT ProductName, SUM(Quantity) AS TotalQuantity


FROM Sales
GROUP BY ProductName
HAVING SUM(Quantity) > 3;

3. Creation and Dropping of Views

Creating a View: You can create a view to simplify complex queries. For example, create a
view to get the total revenue per product:

CREATE VIEW TotalRevenueView AS


SELECT ProductName, SUM(Quantity * Price) AS TotalRevenue
FROM Sales
GROUP BY ProductName;

You can then query this view as if it were a regular table:

SELECT * FROM TotalRevenueView;

Dropping a View: If you no longer need the view, you can drop it:

DROP VIEW TotalRevenueView;

4. Final Query Example (Combining Aggregate Functions and Grouping)

Find the total sales revenue and average price for each product, but only for products with
total sales greater than $2000:

SELECT ProductName, SUM(Quantity * Price) AS TotalRevenue, AVG(Price) AS AveragePrice


FROM Sales
GROUP BY ProductName
HAVING SUM(Quantity * Price) > 2000;

Common questions

Powered by AI

To ensure data integrity when creating tables in an RDBMS, you can use constraints such as PRIMARY KEY, NOT NULL, and UNIQUE. For example, when creating the Employees table, using a PRIMARY KEY constraint on EmployeeID ensures each row has a unique identifier. The NOT NULL constraint on FirstName and LastName ensures that these columns cannot contain NULL values, and the UNIQUE constraint on Email ensures that all email addresses are distinct .

You can retrieve such a list using the SQL ALL operator in a subquery. The query would look like: SELECT Name FROM Students WHERE Marks > ALL (SELECT Marks FROM Students WHERE Rank > Rank). This uses a subquery to compare a student's marks against each student ranked below them and returns only those students whose marks are greater than all such compared values .

You can use GROUP BY to organize data by product and the HAVING clause to filter groups that meet a certain condition. For example, to find products with total sales revenue exceeding $2000: SELECT ProductName, SUM(Quantity * Price) AS TotalRevenue FROM Sales GROUP BY ProductName HAVING SUM(Quantity * Price) > 2000. GROUP BY aggregates data per ProductName, and HAVING applies a condition only on groups where TotalRevenue exceeds $2000 .

To verify if any students scored more than 80 using EXISTS, you could use: SELECT RollNumber, Name FROM Students s WHERE EXISTS (SELECT 1 FROM Students WHERE Marks > 80 AND RollNumber = s.RollNumber). For NOT EXISTS, you can find students who did not score below 80: SELECT RollNumber, Name FROM Students s WHERE NOT EXISTS (SELECT 1 FROM Students WHERE Marks < 80 AND RollNumber = s.RollNumber).

When using DROP TABLE, consider its irreversible nature and potential data loss, as it deletes the table and all its data permanently. Ensure no dependencies, such as foreign keys or application processes rely on the table. Backup critical data before dropping a table. In a transaction environment, dropping a table may affect other operations, so transactional control is advisable to maintain integrity. Assess impacts thoroughly to prevent unintentional system disruptions .

Creating, querying, and dropping a view involves a sequence of commands. First, use CREATE VIEW to define a view, like example: CREATE VIEW TotalRevenueView AS SELECT ProductName, SUM(Quantity * Price) AS TotalRevenue FROM Sales GROUP BY ProductName. Then, query it like a table: SELECT * FROM TotalRevenueView. Finally, drop it when necessary to free up resources: DROP VIEW TotalRevenueView. This allows for modular use of complex queries .

The INTERSECT operator is directly related to the set theory concept of intersection, which identifies common elements between sets. In SQL, INTERSECT returns distinct rows from queries that appear in both result sets. For example, to find students scoring above 85 who are also ranked in the top 3, you'd use: SELECT Name FROM Students WHERE Marks > 85 INTERSECT SELECT Name FROM Students WHERE Rank <= 3. This provides a subset of students meeting both criteria, demonstrating its utility in filtering shared data points across conditions .

Aggregate functions can evaluate the performance by calculating metrics like total sales, average prices, and number of transactions. For instance, using SUM(Quantity * Price) calculates total revenue, AVG(Price) finds average product price, and COUNT(SaleID) counts total sales transactions. For detailed analysis over a time period, these can be combined with GROUP BY to segment data per product or date, offering insights into sales trends .

The UNION operator is beneficial when you need to merge results from multiple queries into a single result set while eliminating duplicates. It is useful when you want to gather related data from different sources or criteria. For example, combining students scoring above 90 and those ranked in the top 2: SELECT Name, Marks FROM Students WHERE Marks > 90 UNION SELECT Name, Marks FROM Students WHERE Rank <= 2. This avoids the need for separate processing of these data sets .

To add a new column to an existing table, you use the ALTER TABLE command. For example, adding a DateOfJoining column to the Employees table involves: ALTER TABLE Employees ADD DateOfJoining DATE. Subsequently, to update the column values, you use the UPDATE command, such as UPDATE Employees SET DateOfJoining = '2022-01-15' WHERE EmployeeID = 101, to assign specific dates to existing rows .

You might also like