1741273670348
1741273670348
World Examples
SQL Functions Explained with a Retail Store Example
SUM()
•What it does: Calculates the sum of a column.
•Real-World Example: You want to calculate the total revenue from all sales.
•SQL: SELECT SUM(Quantity * Price) AS TotalRevenue FROM Sales;
•This calculates the total revenue by multiplying Quantity and Price for each sale and summing them up.
@sandeepsajjanapu
AVG()
•What it does: Calculates the average of a column.
•Real-World Example: You want to find the average sale amount per transaction.
•SQL: SELECT AVG(Quantity * Price) AS AverageSale FROM Sales;
•This calculates the average revenue per sale.
MIN()
•What it does: Finds the minimum value in a column.
•Real-World Example: You want to find the cheapest product sold.
•SQL: SELECT MIN(Price) AS CheapestProduct FROM Sales;
•This retrieves the minimum value in the Price column.
MAX()
•What it does: Finds the maximum value in a column.
•Real-World Example: You want to find the most expensive product sold.
•SQL: SELECT MAX(Price) AS MostExpensiveProduct FROM Sales;
•This retrieves the maximum value in the Price column.
@sandeepsajjanapu
2. Scalar Functions
These functions operate on a single value and return a single value.
UPPER()
•What it does: Converts text to uppercase.
•Real-World Example: You want to display customer names in uppercase for a report.
•SQL: SELECT UPPER(Name) AS UppercaseName FROM Customers;
•This converts the Name column to uppercase.
LOWER()
•What it does: Converts text to lowercase.
•Real-World Example: You want to standardize email addresses to lowercase.
•SQL: SELECT LOWER(Email) AS LowercaseEmail FROM Customers;
•This converts the Email column to lowercase.
@sandeepsajjanapu
LENGTH()
•What it does: Returns the length of a string.
•Real-World Example: You want to find customers with short names (e.g., less than 5 characters).
•SQL: SELECT Name FROM Customers WHERE LENGTH(Name) < 5;
•This retrieves names with fewer than 5 characters.
ROUND()
•What it does: Rounds a numeric value.
•Real-World Example: You want to round the total revenue to 2 decimal places.
•SQL: SELECT ROUND(SUM(Quantity * Price), 2) AS RoundedRevenue FROM Sales;
•This rounds the total revenue to 2 decimal places.
DATE()
•What it does: Extracts the date part of a datetime value.
•Real-World Example: You want to extract the date from the SaleDate column.
•SQL: SELECT DATE(SaleDate) AS SaleDateOnly FROM Sales;
•This extracts only the date part from the SaleDate column.
@sandeepsajjanapu
Analogy
Think of the retail store database as a sales and customer management system:
•Aggregate Functions are like calculators that help you summarize data
(e.g., total revenue, average sale).
•Scalar Functions are like tools that help you clean and format data
(e.g., converting text to uppercase, rounding numbers).
@sandeepsajjanapu