SQL Practical
SQL Practical
Sales Table
The Sales table records information about product
sales, including the quantity sold, sale date,
and total price for each sale. It serves as a
transactional data source for analyzing sales trends.
Query:
-- Create Sales table
Output:
Sales Table
2. Products Table
Output:
Products Table
Query:
SELECT * FROM Sales;
Output:
sale_i
d product_id quantity_sold sale_date total_price
Explanation:
This SQL query selects all columns from the Sales
table, denoted by the asterisk (*) wildcard. It
retrieves every row and all associated columns from
the Sales table.
Query:
SELECT product_name, unit_price FROM Products;
Output:
product_name unit_price
Laptop 500.00
Smartphone 300.00
Headphones 30.00
Keyboard 20.00
product_name unit_price
Mouse 15.00
Explanation:
This SQL query selects
the product_name and unit_price columns from the
Products table. It retrieves every row but only the
specified columns, which are product_name and
unit_price.
Query:
SELECT sale_id, sale_date FROM Sales;
Output:
sale_id sale_date
1 2024-01-01
2 2024-01-02
3 2024-01-02
4 2024-01-03
sale_id sale_date
5 2024-01-03
Explanation:
This SQL query selects the sale_id and sale_date
columns from the Sales table. It retrieves every row
but only the specified columns, which are sale_id and
sale_date.
Query:
SELECT * FROM Sales WHERE total_price > 100;
Output:
sale_i
d product_id quantity_sold sale_date total_price
Explanation:
This SQL query selects all columns from the Sales
table but only returns rows where the total_price
column is greater than 100. It filters out sales with a
total_price less than or equal to $100.
Query:
SELECT * FROM Products WHERE category = 'Electronics';
Output:
product_id product_name category unit_price
Electronic
101 Laptop 500.00
s
Electronic
102 Smartphone 300.00
s
Electronic
103 Headphones 30.00
s
Electronic
104 Keyboard 20.00
s
Electronic
105 Mouse 15.00
s
Explanation:
This SQL query selects all columns from the Products
table but only returns rows where the category
column equals 'Electronics'. It filters out products that
do not belong to the 'Electronics' category.
Query:
SELECT sale_id, total_price
FROM Sales
WHERE sale_date = '2024-01-03';
Output:
sale_i
d total_price
4 80.00
5 90.00
Explanation:
This SQL query selects the sale_id and total_price
columns from the Sales table but only returns rows
where the sale_date is equal to '2024-01-03'. It filters
out sales made on any other date.
7. Retrieve the product_id and product_name
from the Products table for products with a
unit_price greater than $100.
Query:
SELECT product_id, product_name
FROM Products
WHERE unit_price > 100;
Output:
product_i
d product_name
101 Laptop
102 Smartphone
Explanation:
This SQL query selects the product_id and
product_name columns from the Products table but
only returns rows where the unit_price is greater than
$100. It filters out products with a unit_price less than
or equal to $100.
Query:
SELECT SUM(total_price) AS total_revenue
FROM Sales;
total_revenue
3630.00
Explanation:
This SQL query calculates the total revenue
generated from all sales by summing up the
total_price column in the Sales table using
the SUM() function.
Query:
SELECT AVG(unit_price) AS average_unit_price
FROM Products;
Output:
average_unit_price
173
Explanation:
This SQL query calculates the average unit_price of
products by averaging the values in the unit_price
column in the Products table using
the AVG() function.
10. Calculate the total quantity_sold from the
Sales table.
Query:
SELECT SUM(quantity_sold) AS total_quantity_sold
FROM Sales;
Output:
total_quantity_sold
20
Explanation:
This SQL query calculates the total quantity_sold by
summing up the quantity_sold column in the Sales
table using the SUM() function.
Query:
SELECT sale_date, COUNT(*) AS sales_count
FROM Sales
GROUP BY sale_date
ORDER BY sale_date;
Output:
sale_date sales_count
2024-01-01 1
sale_date sales_count
2024-01-02 2
2024-01-03 2
Explanation:
This query groups sales by date and counts the
number of transactions per day, enabling analysis of
daily sales patterns.
Output:
product_name unit_price
Laptop 500.00
Explanation:
This query sorts the Products table by unit_price in
descending order and retrieves the product with the
highest price using the LIMIT clause.
13. Retrieve the sale_id, product_id, and
total_price from the Sales table for sales with
a quantity_sold greater than 4.
Query:
SELECT sale_id, product_id, total_price
FROM Sales
WHERE quantity_sold > 4;
Output:
product_i
sale_id d total_price
1 101 2500.00
5 105 90.00
Explanation:
This SQL query selects the sale_id, product_id, and
total_price columns from the Sales table but only
returns rows where the quantity_sold is greater than
4.
Query:
SELECT product_name, unit_price
FROM Products
ORDER BY unit_price DESC;
Output:
product_name unit_price
Laptop 500.00
Smartphone 300.00
Headphones 30.00
Keyboard 20.00
Mouse 15.00
Explanation:
This SQL query selects the product_name and
unit_price columns from the Products table and
orders the results by unit_price in descending order
using the ORDER BY clause with the DESC keyword.
Query:
SELECT ROUND(SUM(total_price), 2) AS total_sales
FROM Sales;
Output:
total_sales
3630.00
Explanation:
This SQL query calculates the total sales revenu by
summing up the total_price column in the Sales table
and rounds the result to two decimal places using
the ROUND() function.
Query:
SELECT AVG(total_price) AS average_total_price
FROM Sales;
Output:
average_total_price
726.000000
Explanation:
This SQL query calculates the average total_price of
sales by averaging the values in the total_price
column in the Sales table using the AVG() function.
17. Retrieve the sale_id and sale_date from
the Sales table, formatting the sale_date as
'YYYY-MM-DD'.
Query:
SELECT sale_id, DATE_FORMAT(sale_date, '%Y-%m-%d') AS
formatted_date
FROM Sales;
Output:
sale_i
d formatted_date
1 2024-01-01
2 2024-01-02
3 2024-01-02
4 2024-01-03
5 2024-01-03
Explanation:
This SQL query selects the sale_id and sale_date
columns from the Sales table and formats the
sale_date using the DATE_FORMAT() function to
display it in 'YYYY-MM-DD' format.
18. Calculate the total revenue generated
from sales of products in the 'Electronics'
category.
Query:
SELECT SUM(Sales.total_price) AS total_revenue
FROM Sales
JOIN Products ON Sales.product_id = Products.product_id
WHERE [Link] = 'Electronics';
Output:
total_revenue
3630.00
Explanation:
This SQL query calculates the total revenue
generated from sales of products in the 'Electronics'
category by joining the Sales table with the Products
table on the product_id column and filtering sales for
products in the 'Electronics' category.
Query:
SELECT product_name, unit_price
FROM Products
WHERE unit_price BETWEEN 20 AND 600;
Output:
product_name unit_price
Laptop 500.00
Smartphone 300.00
Headphones 30.00
Keyboard 20.00
Explanation:
This SQL query selects the product_name and
unit_price columns from the Products table but only
returns rows where the unit_price falls within the
range of $20 and $600 using the BETWEEN operator.
Query:
SELECT product_name, category
FROM Products
ORDER BY category ASC;
Output:
product_name category
Laptop Electronics
Smartphone Electronics
Headphones Electronics
Keyboard Electronics
Mouse Electronics
Explanation:
This SQL query selects the product_name and
category columns from the Products table and orders
the results by category in ascending order using the
ORDER BY clause with the ASC keyword.
Query:
SELECT SUM(quantity_sold) AS total_quantity_sold
FROM Sales
JOIN Products ON Sales.product_id = Products.product_id
WHERE [Link] = 'Electronics';
Output:
total_quantity_sold
20
Explanation:
This SQL query calculates the total quantity_sold of
products in the 'Electronics' category by joining the
Sales table with the Products table on the product_id
column and filtering sales for products in the
'Electronics' category.
Output:
product_name total_price
Laptop 2500.00
Smartphone 900.00
Headphones 60.00
Keyboard 80.00
Mouse 90.00
Explanation:
This SQL query retrieves the product_name from the
Sales table and calculates the total_price by
multiplying quantity_sold by unit_price, joining the
Sales table with the Products table on the product_id
column.
Output:
product_id sales_count
101 1
Explanation:
This query counts the number of sales for each
product (COUNT(*)) and identifies the product with the
highest sales count. It groups data by product_id, orders
it in descending order of sales, and limits the result to
the top record.
4. Find the Products Not Sold from Products
table
Query:
SELECT product_id, product_name
FROM Products
WHERE product_id NOT IN (SELECT DISTINCT product_id FROM Sales);
Output:
product_i
d product_name
None None
Explanation:
This query identifies products from the Products table
that do not have any sales records in the Sales table by
using a NOT IN subquery. It ensures a thorough
comparison to list unsold products.
Query:
SELECT [Link], SUM(s.total_price) AS total_revenue
FROM Sales s
JOIN Products p ON s.product_id = p.product_id
GROUP BY [Link];
Output:
category total_revenue
Electronic
3630.00
s
Explanation:
This query joins the Sales and Products tables on the
product_id column, groups the results by product
category, and calculates the total revenue for each
category by summing up the total_price.
Query:
SELECT category
FROM Products
GROUP BY category
ORDER BY AVG(unit_price) DESC
LIMIT 1;
Output:
category
Electronics
Explanation:
This query groups products by category, calculates
the average unit price for each category, orders the
results by the average unit price in descending order,
and selects the top category with the highest average
unit price using the LIMIT clause.
Query:
SELECT p.product_name
FROM Sales s
JOIN Products p ON s.product_id = p.product_id
GROUP BY p.product_name
HAVING SUM(s.total_price) > 30;
Output:
product_name
Headphones
Keyboard
Laptop
Mouse
Smartphone
Explanation:
This query joins the Sales and Products tables on the
product_id column, groups the results by product
name, calculates the total sales revenue for each
product, and selects products with total sales
exceeding 30 using the HAVING clause.
Query:
SELECT DATE_FORMAT(s.sale_date, '%Y-%m') AS month, COUNT(*) AS
sales_count
FROM Sales s
GROUP BY month;
Output:
month sales_count
2024-01 5
Explanation:
This query formats the sale_date column to extract
the month and year, groups the results by month, and
counts the number of sales made in each month.
Output:
sale_id product_name total_price
2 Smartphone 900.00
Explanation:
This query uses a LIKE clause to match products with
"Smart" in their name, joining the Sales and Products tables
to provide sales details for these products.
10. Determine the average quantity sold for
products with a unit price greater than $100.
Query:
SELECT AVG(s.quantity_sold) AS average_quantity_sold
FROM Sales s
JOIN Products p ON s.product_id = p.product_id
WHERE p.unit_price > 100;
Output:
average_quantity_sold
4.0000
Explanation:
This query joins the Sales and Products tables on the
product_id column, filters products with a unit price
greater than $100, and calculates the average
quantity sold for those products.
Query:
SELECT p.product_name, SUM(s.total_price) AS total_revenue
FROM Sales s
JOIN Products p ON s.product_id = p.product_id
GROUP BY p.product_name;
Output:
product_name total_revenue
Laptop 2500.00
Smartphone 900.00
Headphones 60.00
Keyboard 80.00
Mouse 90.00
Explanation:
This query joins the Sales and Products tables on the
product_id column, groups the results by product
name, and calculates the total sales revenue for each
product.
Query:
SELECT s.sale_id, p.product_name
FROM Sales s
JOIN Products p ON s.product_id = p.product_id;
Output:
sale_id product_name
1 Laptop
2 Smartphone
3 Headphones
4 Keyboard
5 Mouse
Explanation:
This query joins the Sales and Products tables on the
product_id column and retrieves the sale_id and
product_name for each sale.
Query:
SELECT [Link],
SUM(s.total_price) AS category_revenue,
(SUM(s.total_price) / (SELECT SUM(total_price) FROM
Sales)) * 100 AS revenue_percentage
FROM Sales s
JOIN Products p ON s.product_id = p.product_id
GROUP BY [Link]
ORDER BY revenue_percentage DESC
LIMIT 3;
Output:
category category_revenue revenue_percentage
Electronic
3630.00 100.000000
s
Explanation:
This query will give you the top three product
categories contributing to the highest percentage of
total revenue generated from sales. However, if you
only have one category (Electronics) as in the
provided sample data, it will be the only result.
Query:
SELECT p.product_name, SUM(s.total_price) AS total_revenue,
RANK() OVER (ORDER BY SUM(s.total_price) DESC) AS
revenue_rank
FROM Sales s
JOIN Products p ON s.product_id = p.product_id
GROUP BY p.product_name;
Output:
product_name total_revenue revenue_rank
Laptop 2500.00 1
product_name total_revenue revenue_rank
Smartphone 900.00 2
Mouse 90.00 3
Keyboard 80.00 4
Headphone
60.00 5
s
Explanation:
This query joins the Sales and Products tables on the
product_id column, groups the results by product
name, calculates the total sales revenue for each
product, and ranks products based on total sales
revenue using the RANK() window function.
Query:
SELECT [Link], p.product_name, s.sale_date,
SUM(s.total_price) OVER (PARTITION BY [Link] ORDER BY
s.sale_date) AS running_total_revenue
FROM Sales s
JOIN Products p ON s.product_id = p.product_id;
Output:
category product_name sale_date running_total_revenue
Electronic 2024-
Laptop 2500.00
s 01-01
Electronic 2024-
Smartphone 3460.00
s 01-02
Electronic 2024-
Headphones 3460.00
s 01-02
Electronic 2024-
Keyboard 3630.00
s 01-03
Electronic 2024-
Mouse 3630.00
s 01-03
Explanation:
This query joins the Sales and Products tables on the
product_id column, partitions the results by product
category, orders the results by sale date, and
calculates the running total revenue for each product
category using the SUM() window function.
Output:
sale_i
d sales_category
1 High
2 High
3 Low
4 Low
5 Low
Explanation:
This query categorizes sales based on total price
using a CASE statement. Sales with a total price
greater than $200 are categorized as "High", sales
with a total price between $100 and $200 are
categorized as "Medium", and sales with a total price
less than $100 are categorized as "Low".
17. Identify sales where the quantity sold is
greater than the average quantity sold.
Query:
SELECT *
FROM Sales
WHERE quantity_sold > (SELECT AVG(quantity_sold) FROM Sales);
Output:
sale_i
d product_id quantity_soldsale_date total_price
Explanation:
This query selects all sales where the quantity sold is
greater than the average quantity sold across all sales
in the Sales table.
Query:
SELECT CONCAT(YEAR(sale_date), '-', LPAD(MONTH(sale_date), 2,
'0')) AS month,
COUNT(*) AS sales_count
FROM Sales
GROUP BY YEAR(sale_date), MONTH(sale_date);
Output:
month sales_count
2024-01 5
Explanation:
This query extracts the year and month from
the sale_date column using YEAR() and MONTH(), formats them
as YYYY-MM using CONCAT() and LPAD() for proper padding, and
counts the number of sales (COUNT(*)) for each month.
Query:
SELECT sale_id, DATEDIFF(NOW(), sale_date) AS days_since_sale
FROM Sales;
Output:
sale_i
d days_since_sale
1 185
sale_i
d days_since_sale
2 184
3 184
4 183
5 183
Explanation:
This query calculates the number of days between the
current date and the sale date for each sale using
the DATEDIFF function.
Query:
SELECT sale_id,
CASE
WHEN DAYOFWEEK(sale_date) IN (1, 7) THEN 'Weekend'
ELSE 'Weekday'
END AS day_type
FROM Sales;
Output:
sale_id day_type
1 Weekday
2 Weekday
3 Weekday
4 Weekend
5 Weekend
Explanation:
This query categorizes sales based on the day of the
week using the DAYOFWEEK function. Sales made
on Sunday (1) or Saturday (7) are categorized as
"Weekend", while sales made on other days are
categorized as "Weekday".
Query:
SELECT p.product_name,
SUM(s.total_price) AS total_revenue,
(SUM(s.total_price) / (SELECT SUM(total_price) FROM
Sales)) * 100 AS revenue_percentage
FROM Sales s
JOIN Products p ON s.product_id = p.product_id
GROUP BY p.product_name
ORDER BY revenue_percentage DESC
LIMIT 3;
Output:
product_name total_revenue revenue_percentage
Explanation:
This query calculates the revenue percentage for each product and lists the
top 3 products by their contribution to total revenue, using SUM() and a
subquery for total sales.
Query:
CREATE VIEW Total_Sales AS
SELECT p.product_name, [Link], SUM(s.total_price) AS
total_sales_amount
FROM Products p
JOIN Sales s ON p.product_id = s.product_id
GROUP BY p.product_name, [Link];
SELECT * FROM Total_Sales;
Output:
product_name category total_sales_amount
Explanation:
This query creates a view named Total_Sales that displays the total sales
Query:
SELECT product_name, category, unit_price
FROM Products
WHERE product_id IN (
SELECT product_id
FROM Sales
GROUP BY product_id
HAVING SUM(quantity_sold) > (SELECT AVG(quantity_sold) FROM
Sales)
);
Output:
product_name category unit_price
Explanation:
This query retrieves the product details (name, category, unit price) for
products that have a quantity sold greater than the average quantity sold
across all products.
Query:
-- Create an index on the sale_date column
CREATE INDEX idx_sale_date ON Sales (sale_date);
Explanation:
With an index on the sale_date column, the database can quickly locate the
rows that match the specified date without scanning the entire table. The
index allows for efficient lookup of rows based on the sale_date value,
resulting in improved query performance.
Query:
ALTER TABLE Sales
ADD CONSTRAINT fk_product_id
FOREIGN KEY (product_id)
REFERENCES Products(product_id);
Output:
No output is generated, but the constraint is applied to the
table.
Explanation:
This query adds a foreign key constraint to the Sales table that references the
product_id column in the Products table, ensuring referential integrity between
the two tables.
Query:
CREATE VIEW Top_Products AS
SELECT p.product_name, SUM(s.quantity_sold) AS
total_quantity_sold
FROM Sales s
JOIN Products p ON s.product_id = p.product_id
GROUP BY p.product_name
ORDER BY total_quantity_sold DESC
LIMIT 3;
Output:
product_name total_quantity_sold
Mouse 6
product_name total_quantity_sold
Laptop 5
Keyboard 4
Explanation:
This query creates a view named Top_Products that lists the top 3 products
based on the total quantity sold.
Query:
START TRANSACTION; -- Begin the transaction
8. Create a query that lists the product names along with their
corresponding sales count.
Query:
SELECT p.product_name, COUNT(s.sale_id) AS sales_count
FROM Products p
LEFT JOIN Sales s ON p.product_id = s.product_id
GROUP BY p.product_name;
Output:
product_name sales_count
Headphones 1
Keyboard 1
Laptop 1
Mouse 1
Smartphone 1
Explanation:
This query selects the product names from the Products table and counts the
number of sales (using the COUNT() function) for each product by joining the
Sales table on the product_id. The results are grouped by product name using
the GROUP BY clause.
9. Write a query to find all sales where the total price is greater
than the average total price of all sales.
Query:
SELECT *
FROM Sales
WHERE total_price > (SELECT AVG(total_price) FROM Sales);
Output:
sale_id product_id quantity_soldsale_date total_price
Explanation:
The subquery (SELECT AVG(total_price) FROM Sales) calculates the
average total price of all sales. The main query selects all columns from the
Sales table where the total price is greater than the average total price
obtained from the subquery.
Query:
-- Query without indexing
EXPLAIN ANALYZE
SELECT *
FROM Sales
WHERE sale_date = '2024-01-01';
EXPLAIN ANALYZE
SELECT *
FROM Sales
WHERE sale_date = '2024-01-01';
Output:
Query without Indexing:
Operation Details
Explanation:
Without indexing, the query performs a full table scan, filtering rows based on
the sale date, which is less efficient. With indexing, the query uses the index
to quickly locate the relevant rows, significantly improving query performance.
Query:
ALTER TABLE Sales
ADD CONSTRAINT chk_quantity_sold CHECK (quantity_sold > 0);
-- Query to check if the constraint is applied successfully
SELECT * FROM Sales;
Output:
sale_id product_id quantity_soldsale_date total_price
Explanation:
All rows in the Sales table meet the condition of the check constraint, as each
quantity_sold value is greater than zero.
Query:
CREATE VIEW Product_Sales_Info AS
SELECT
p.product_id,
p.product_name,
[Link],
p.unit_price,
COUNT(s.sale_id) AS total_sales
FROM
Products p
LEFT JOIN
Sales s ON p.product_id = s.product_id
GROUP BY
p.product_id, p.product_name, [Link], p.unit_price;
Output:
product_id product_name category unit_pricetotal_sales
Electronic
101 Laptop 500.00 1
s
Electronic
102 Smartphone 300.00 1
s
Electronic
103 Headphones 30.00 1
s
Electronic
104 Keyboard 20.00 1
s
Electronic
105 Mouse 15.00 1
s
Explanation:
This view provides a concise and organized way to view product details
alongside their respective sales information, facilitating analysis and reporting
tasks.
Query:
DELIMITER //
DELIMITER ;
Output:
There is no direct output shown here as this is a stored
procedure definition
Explanation:
The above SQL code creates a stored procedure named Update_Unit_Price.
This stored procedure takes two parameters: p_product_id (the product ID for
which the unit price needs to be updated) and p_new_price (the new unit price
to set).
Query:
CREATE PROCEDURE Update_Unit_Price (
@product_id INT,
@new_unit_price DECIMAL(10, 2)
)
AS
BEGIN
UPDATE Products
SET unit_price = @new_unit_price
WHERE product_id = @product_id;
END;
Explanation:
This will update the unit price of the product with product_id 101 to 550.00 in
the Products table.
15. Write a query that calculates the total revenue generated from
each category of products for the year 2024.
Query:
SELECT
[Link],
SUM(s.total_price) AS total_revenue
FROM
Sales s
JOIN
Products p ON s.product_id = p.product_id
WHERE
strftime('%Y', s.sale_date) = '2024'
GROUP BY
[Link];
Output:
category total_revenue
Electronics 3630.00
Explanation:
When you execute this query, you will get the total revenue generated from
each category of products for the year 2024.