4.1 Sorting Data: Function Output
4.1 Sorting Data: Function Output
4.1 Sorting Data: Function Output
Learning objectives:
Sort the data in the resulting query
Apply SQL aggregate functions
Apply GROUP BY clause
ORDER BY Clause
Sorts the result-set in ascending or descending order.
Default is ascending order, use the DESC keyword otherwise.
Listed last in the select command sequence.
Lists null columns first (Depends on DBMS)
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... [ASC|DESC];
Show contact name and country from the "Customers" table, sorted by the "Country" column:
SELECT ContactName, Country FROM Customers
ORDER BY Country;
Show contact name and country from the "Customers" table in DESCENDING order by the
"Country" column:
SELECT ContactName, Country FROM Customers
ORDER BY Country DESC;
Function Output
MIN The minimum attribute value encountered in a given column
MAX The maximum attribute value encountered in a given column
COUNT The number of rows containing non-null values
AVG The arithmetic mean (average) for a specified column
SUM The sum of all values for a given column
Find the minimum price among all products from the “Products” table.
SELECT MIN(UnitPrice) FROM Products;
Find the maximum price among all products from the “Products” table.
SELECT MAX(UnitPrice) FROM Products;
Find the average price of all products from the “Products” table.
SELECT AVG(UnitPrice) FROM Products;
Find the total price of all products from the “Products” table.
SELECT SUM(UnitPrice) FROM Products;
Find the average price of all products from the “Products” table without using AVG function.
SELECT (SUM(UnitPrice)/COUNT(ProductID)) from products;
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);