SQL - Aggregare - Functions - GroupBy - Having
SQL - Aggregare - Functions - GroupBy - Having
Introduction to Databases
MIN() and MAX() Functions
• The MIN() function returns the smallest value of the selected column.
• The MAX() function returns the largest value of the selected column.
• SELECT MIN(column_name)
FROM table_name
WHERE condition;
• SELECT MAX(column_name)
FROM table_name
WHERE condition;
Example
• SELECT COUNT(column_name)
FROM table_name
WHERE condition;
• SELECT COUNT(ProductID)
FROM Products;
Count(*)
• COUNT(*) returns the number of rows in a specified table
• It preserves duplicate rows. It counts each row separately.
• This includes rows that contain null values.
• COUNT(*) without GROUP BY returns the cardinality (number of
rows) in the result set. This includes rows comprised of all-NULL
values and duplicates.
• COUNT(*) with GROUP BY returns the number of rows in each group.
This includes NULL values and duplicates.
Count(*)
• COUNT(ALL <expression>) evaluates expression for each row in a
group, and returns the number of non null values.
• COUNT(DISTINCT *expression*) evaluates expression for each row in
a group, and returns the number of unique, non null values.
Example
• SELECT COUNT(*) FROM HumanResources.Employee;
• Output:
290
• Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Example
• SELECT AVG(Price)
FROM Products;
MySQL SUM()
• The SUM() function returns the total sum of a numeric column.
• Returns the sum of all the values, or only the DISTINCT values, in the
expression.
• SUM can be used with numeric columns only.
• Null values are ignored.
• Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Example
• SELECT SUM(Quantity)
FROM OrderDetails;
• OR
Example:
SELECT ProductName, UnitPrice * (UnitsInStock +
IFNULL(UnitsOnOrder, 0))
FROM Products;
ORDER BY Clause
• The ORDER BY clause can be used in the SELECT query to sort the
result in ascending or descending order of one or more columns.
• The ORDER BY keyword is used to sort the result-set in ascending or
descending order.
• The ORDER BY keyword sorts the records in ascending order by
default.
• To sort the records in descending order, use the DESC keyword.
Order By Syntax|Example
• SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;