dbms lab 4
dbms lab 4
Example
Function Description
Usage
COUNT(*) AS TotalOrders,
SUM(order_amount) AS TotalSales,
AVG(order_amount) AS AverageOrder,
MAX(order_amount) AS HighestOrder,
MIN(order_amount) AS LowestOrder
FROM Orders;
This query summarizes all orders: total number, total sales amount, average
order value, highest and lowest order value.
GROUP BY Clause
The GROUP BY clause is used to arrange identical data into groups, so
that aggregate functions can be applied per group, rather than across the
whole table.
Example Query with GROUP BY:
SELECT customer_id, COUNT(*) AS OrderCount
FROM Orders
GROUP BY customer_id;
HAVING Clause
The HAVING clause is used to filter the grouped data, based on
conditions involving aggregate functions. It's like a WHERE clause, but it
applies after grouping has taken place.
Example Query with GROUP BY and HAVING:
SELECT customer_id, COUNT(*) AS OrderCount
FROM Orders
GROUP BY customer_id
HAVING COUNT(*) > 5;
• This query filters out those customers who have placed 5 or fewer
orders.
• Only customers with more than 5 orders are shown in the result.
HAVING: The HAVING clause is very similar to WHERE clause except the
statements within it is of an aggregate nature
Example: To display the average salary for all departments employing
more than three people.
• This filters orders of the current year only and shows monthly
order counts.
Scalar Functions in SQL
Scalar functions operate on individual values and return a single value per
row.
Function Description