0% found this document useful (0 votes)
35 views22 pages

DBMS 6,7,8,9

Uploaded by

717821e248
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)
35 views22 pages

DBMS 6,7,8,9

Uploaded by

717821e248
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
You are on page 1/ 22

EX.

NO : 6
QUERYING USING ANY, ALL, IN, EXISTS, NOT EXISTS,UNION,
INTERSECT
DATE:

AIM
To write SQL queries using ANY, ALL, IN, EXISTS, NOT EXISTS, UNION, and INTERSECT
operators.

PROCEDURE
1. Use the ANY operator to compare a value to any value in a list.
2. Use the ALL operator to compare a value to all values in a list.
3. Use the IN operator to check if a value exists in a list.
4. Use the EXISTS operator to check the existence of a subquery result.
5. Use the NOT EXISTS operator to check the non-existence of a subquery result.
6. Use the UNION operator to combine the results of two queries.
7. Use the INTERSECT operator to return the common results of two queries.
8. Document the SQL queries used for each operator.
9. Execute the queries in the SQL environment.
10. Validate the results by checking the retrieved data.

QUERIES:
CREATE A TABLE OF EMPLOYEES:
Code:
CREATE TABLE employees
( employee_id INT PRIMARY
KEY, employee_name
VARCHAR(100),
department_id INT,
salary DECIMAL(10,
2)
);

INSERT THE DATA IN TO THE EMPLOYEES TABLE:


Code:
INSERT INTO employees (employee_id, employee_name, department_id, salary) VALUES (101,
'Alice', 1, 55000),
(102, 'Bob', 2, 60000),
(103, 'Charlie', 3, 45000), (104,
'David', 1, 48000),
(105, 'Eva', 2, 70000),
(106, 'Frank', 3, 52000),
(107, 'Grace', 1, 51000);

SHOW THE TABLE OF EMPLOYEES:


Code:
SELECT * FROM employees;

19 717823F137
OUTPUT:

CREATE A TABLE OF DEPARTMENT:


Code:
CREATE TABLE departments
( department_id INT PRIMARY
KEY, department_name
VARCHAR(100)
);

INSERT THR DATA INTO THE DEPARTMENT:


Code:
INSERT INTO departments (department_id, department_name) VALUES
(1, 'HR'),
(2, 'IT'),
(3, 'Finance');

SHOW THE TABLE OF DEPARTMENT:


Code:
SELECT * FROM departments;

OUTPUT:

ANY OPERATOR:
Code:
SELECT
employee_name FROM
employees
WHERE salary > ANY (SELECT salary FROM employees WHERE department_id = 1);

OUTPUT:

20 717823F137
ALL OPERATOR:
Code:
SELECT
employee_name FROM
employees
WHERE salary > ALL (SELECT salary FROM employees WHERE department = 'HR');

OUTPUT:

IN OPERATOR:
Code:
SELECT employee_name, department_id
FROM employees
WHERE department_id IN ('HR', 'Finance', 'IT');

OUTPUT:

EXISTS OPERATOR:
Code:
SELECT
employee_name FROM
employees e
WHERE EXISTS (SELECT 1 FROM departments d WHERE d.department_id = e.department_id AND
d.department_name = 'HR');

OUTPUT:

NOT EXISTS OPERATOR:


Code:
21 717823F137
SELECT
employee_name FROM
employees e

22 717823F137
WHERE NOT EXISTS (SELECT 1 FROM departments d WHERE d.department_id = e.department_id
AND d.department_name = 'HR');

OUTPUT:

UNION OPERATOR:
Code:
SELECT
e.employee_name FROM
employees e
JOIN departments d ON e.department_id = d.department_id
WHERE d.department_name = 'HR'
UNION
SELECT
e.employee_name FROM
employees e
JOIN departments d ON e.department_id = d.department_id
WHERE d.department_name = 'IT';

OUTPUT:

RESULT:
Thus, we created sql queries to implement data querying using any, all, in, exists, not exists,union,
intersect
23 717823F137
EX.NO : 7
QUERYING USING AGGREGATE FUNCTIONS (COUNT, SUM,
AVG, MAX, AND
DATE:
MIN)

AIM
To write SQL queries using aggregate functions COUNT, SUM, AVG, MAX, and MIN to perform
calculations on data.

PROCEDURE
1. Use the COUNT function to count the number of rows in a table.
2. Use the SUM function to calculate the total of a numeric column.
3. Use the AVG function to calculate the average value of a numeric column.
4. Use the MAX function to find the maximum value in a column.
5. Use the MIN function to find the minimum value in a column.
6. Combine aggregate functions with GROUP BY to calculate grouped data.
7. Document the SQL queries used for each aggregate function.
8. Execute the queries in the SQL environment.
9. Validate the results by checking the calculated data.
10. Ensure the queries perform as expected with various data sets.

QUERIES:
CREATE THE SALES_DATA TABLE:
CREATE TABLE sales_data (
id INT PRIMARY KEY AUTO_INCREMENT,
product_name VARCHAR(100),
category VARCHAR(50), price
DECIMAL(10, 2),
quantity INT,
sale_date DATE
);

INSERT SAMPLE DATA:


INSERT INTO sales_data (product_name, category, price, quantity, sale_date)
VALUES
('Laptop', 'Electronics', 800.00, 5, '2024-09-01'),
('Smartphone', 'Electronics', 600.00, 10, '2024-09-02'),
('Chair', 'Furniture', 150.00, 20, '2024-09-03'),
('Desk', 'Furniture', 300.00, 15, '2024-09-01'),
('Shoes', 'Apparel', 80.00, 50, '2024-09-04'),
('Shirt', 'Apparel', 40.00, 100, '2024-09-05');

SHOW THE TABLE OF SALES DATA:


Code:
SELECT * FROM sales_data;

24 717823F137
OUTPUT:

USE THE COUNT FUNCTION:


Code:
-- Count the number of rows in the table
SELECT COUNT(*) AS row_count FROM sales_data;

OUTPUT:

USE THE SUM FUNCTION:


Code:
-- Calculate the total quantity of products sold
SELECT SUM(quantity) AS total_quantity_sold FROM sales_data;

-- Calculate the total revenue from product sales (price * quantity) SELECT
SUM(price * quantity) AS total_revenue FROM sales_data;

OUTPUT:

USE THE AVG FUNCTION:


Code:
-- Calculate the average price of products
SELECT AVG(price) AS average_price FROM sales_data;

OUTPUT:

-- Calculate the average quantity sold


25 717823F137
SELECT AVG(quantity) AS average_quantity_sold FROM sales_data;

26 717823F137
OUTPUT:

USE THE MAX FUNCTION:


Code:
-- Find the maximum price of any product
SELECT MAX(price) AS max_price FROM sales_data;

-- Find the maximum quantity sold for a product


SELECT MAX(quantity) AS max_quantity_sold FROM sales_data;

OUTPUT:

USE THE MIN FUNCTION:

Code:
-- Find the minimum price of any product
SELECT MIN(price) AS min_price FROM sales_data;

-- Find the minimum quantity sold for a product


SELECT MIN(quantity) AS min_quantity_sold FROM sales_data; OUTPUT:

COMBINE AGGREGATE FUNCTIONS WITH GROUP BY:

Code:
-- Calculate the total quantity and average price for each product category
SELECT category, SUM(quantity) AS total_quantity, AVG(price) AS
average_price FROM sales_data
GROUP BY category;

27 717823F137
OUTPUT:

DOCUMENTATION OF SQL QUERIES:

Code:
-- Count the number of rows in the sales_data table SELECT
COUNT(*) AS row_count FROM sales_data;

OUTPUT:

RESULT:
Thus, we created sql queries to querying using aggregate functions (count, sum, avg, max, and min)

28 717823F137
EX.NO : 8
QUERYING USING GROUP BY, HAVING
DATE:

AIM
To write SQL queries using GROUP BY and HAVING clauses to group and filter data.

PROCEDURE
1. Use the GROUP BY clause to group rows that have the same values in specified columns.
2. Use aggregate functions with GROUP BY to calculate grouped data.
3. Use the HAVING clause to filter groups based on a specified condition.
4. Document the SQL queries used for GROUP BY and HAVING.
5. Execute the queries in the SQL environment.
6. Validate the results by checking the grouped and filtered data.
7. Combine GROUP BY with different aggregate functions.
8. Ensure the queries perform as expected with various data sets.
9. Optimize the queries for better performance.
10. Test the queries with different group by columns.

QUERIES:

CREATE THE SALES TABLE:


Code:
CREATE TABLE Sales (
SaleID INT PRIMARY KEY
AUTO_INCREMENT, Product VARCHAR(100)
NOT NULL,
SaleDate DATE NOT NULL,
QuantitySold INT NOT
NULL,
PricePerUnit DECIMAL(10, 2) NOT NULL,
TotalAmount DECIMAL(10, 2) AS (QuantitySold * PricePerUnit) STORED
);

INSERT SAMPLE DATA:


Code:
INSERT INTO Sales (Product, SaleDate, QuantitySold,
PricePerUnit) VALUES
('Laptop', '2024-09-01', 5, 1000.00),
('Smartphone', '2024-09-02', 10, 500.00),
('Tablet', '2024-09-03', 7, 300.00),
('Laptop', '2024-09-04', 2, 950.00),
('Smartphone', '2024-09-05', 3, 550.00),
('Headphones', '2024-09-06', 15, 75.00);

USE THE GROUP BY CLAUSE TO GROUP ROWS THAT HAVE THE SAME VALUES IN
SPECIFIED COLUMNS:

SELECT Product, SUM(QuantitySold) AS


TotalQuantity FROM Sales
GROUP BY Product;
29 717823F137
30 717823F137
SHOW THE TABLE OF SALES DATA:
Code:
SELECT * FROM sales;

OUTPUT:

USE AGGREGATE FUNCTIONS WITH GROUP BY TO CALCULATE GROUPED DATA:


Code:
SELECT Product, SUM(QuantitySold) AS TotalQuantity, COUNT(SaleID) AS SaleCount,
AVG(PricePerUnit) AS AvgPrice
FROM Sales
GROUP BY
Product;

OUTPUT:

USE THE HAVING CLAUSE TO FILTER GROUPS BASED ON A SPECIFIED CONDITION:


Code:
SELECT Product, SUM(QuantitySold) AS
TotalQuantity FROM Sales
GROUP BY Product
HAVING SUM(QuantitySold) > 10;

OUTPUT:

DOCUMENT THE SQL QUERIES USED FOR GROUP BY AND HAVING:


Code;
-- Group by Product and calculate the total quantity sold for each product
SELECT Product, SUM(QuantitySold) AS TotalQuantity
FROM Sales
GROUP BY
Product;
31 717823F137
-- Group by Product and filter only those products where the total quantity sold is greater than 10

32 717823F137
SELECT Product, SUM(QuantitySold) AS
TotalQuantity FROM Sales
GROUP BY Product
HAVING SUM(QuantitySold) > 10;

OUTPUT:

VALIDATE THE RESULTS BY CHECKING THE GROUPED AND FILTERED DATA:


Code:
SELECT Product, SUM(QuantitySold) AS
TotalQuantity FROM Sales
GROUP BY Product
HAVING SUM(QuantitySold) > 10;

OUTPUT:

COMBINE GROUP BY WITH DIFFERENT AGGREGATE FUNCTIONS:


Code:
SELECT Product, COUNT(SaleID) AS SaleCount, MAX(PricePerUnit) AS MaxPrice,
MIN(PricePerUnit) AS MinPrice, SUM(TotalAmount) AS TotalRevenue
FROM Sales
GROUP BY
Product;

OUTPUT:

OPTIMIZE THE QUERIES FOR BETTER PERFORMANCE:


33 717823F137
Code:

34 717823F137
CREATE INDEX idx_product ON Sales(Product);

TEST THE QUERIES WITH DIFFERENT GROUP BY COLUMNS:


Code:
SELECT SaleDate, SUM(QuantitySold) AS TotalQuantity, SUM(TotalAmount) AS TotalRevenue
FROM Sales
GROUP BY SaleDate;

OUTPUT:

RESULT:

EX.NO : 9
CREATE AND MANAGE VIEWS AND INTEGRITY
DATE: CONSTRAINTS
Thus, we created sql queries to implement querying using group by, having
35 717823F137
AIM:
To create and manage views and integrity constraints in a relational database.

PROCEDURE:
1. Use the CREATE VIEW command to create views.
2. Use the SELECT statement to query data from views.
3. Use the DROP VIEW command to delete views if needed.
4. Define integrity constraints such as PRIMARY KEY, FOREIGN KEY, UNIQUE, and CHECK.
5. Add constraints to existing tables using the ALTER TABLE command.
6. Verify the creation of views and constraints by querying the database metadata.
7. Document the SQL queries used for creating and managing views and constraints.
8. Execute the queries in the SQL environment.
9. Validate the results by checking the structure and data of the created views.
10. Ensure data integrity by testing different scenarios.

QUERIES:

CREATE A TABLE OF CUSTOMER:


Code:
CREATE TABLE customers (
customer_id INT AUTO_INCREMENT PRIMARY
KEY, first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,

email VARCHAR(100) UNIQUE NOT NULL,


phone_number VARCHAR(15),
CHECK (CHAR_LENGTH(phone_number) <= 15)
);

INSERT DATA IN TO CUSTOMER TABLE:


Code:
INSERT INTO customers (first_name, last_name, email, phone_number) VALUES
('Alice', 'Smith', '[email protected]', '1234567890'),
('Bob', 'Johnson', '[email protected]', '2345678901'),
('Charlie', 'Williams', '[email protected]', '3456789012'),
('Diana', 'Brown', '[email protected]', '4567890123');

SHOW THE TABLE OF CUSTOMERS:


Code:
SELECT * FROM customers;

36 717823F137
OUTPUT:

CREATE A TABLE OF ORDERS:

Code:
CREATE TABLE orders (
order_id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT, order_date DATE NOT NULL,
total_amount DECIMAL(10, 2) CHECK
(total_amount >= 0), FOREIGN KEY
(customer_id) REFERENCES customers(customer_id)
);

INSERT THE DATA INTO THE ORDERS TABLE:


Code:
INSERT INTO orders (customer_id, order_date,
total_amount) VALUES
(1, '2024-09-01', 250.00),
(1, '2024-09-15', 75.00),
(2, '2024-09-10', 120.00),
(3, '2024-09-12', 180.00),
(4, '2024-09-05', 300.00);

SHOW THE TABLE OF ORDERS:


Code:
SELECT * FROM orders;

OUTPUT:

CREATE A VIEW:
Code:
CREATE VIEW customer_orders
AS SELECT
c.customer_id
, c.first_name,

37 717823F137
c.last_name,

38 717823F137
o.order_id,
o.order_date,
o.total_amoun
t
FROM
customers c JOIN
orders o ON c.customer_id = o.customer_id;

SHOW THE VIEW DATA:


SELECT *
FROM customer_orders;

OUTPUT:

DROP VIEWS:
DROP VIEW customer_orders;

ADD CONSTRAINTS TO EXISTING TABLES:


ALTER TABLE customers
ADD CONSTRAINT unique_phone_number UNIQUE (phone_number);

SHOW THE TABLE OF CUSTOMERS:


Code:
SELECT * FROM customers;

OUTPUT:

VERIFY CREATION OF VIEWS AND CONSTRAINTS:


Code:
SELECT *
FROM information_schema.views
WHERE table_schema = 'your_database_name';

39 717823F137
CHECK CONSTRAINTS:
Code:
SELECT *
FROM information_schema.table_constraints
WHERE table_schema = 'your_database_name'
AND table_name IN ('customers', 'orders');

RESULT:
Thus, we created sql queries to implement create and manage views and integrity constraints

40 717823F137

You might also like