SQL Aggregate Functions
SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:
Example
SELECT AVG(Price) AS PriceAverage FROM Products;
The COUNT() function returns the number of rows that matches a specified criteria.
Example
SELECT COUNT(CustomerID) AS OrdersFromCustomerID7 FROM Orders
WHERE CustomerID=7;
Example
SELECT COUNT(*) AS NumberOfOrders FROM Orders;
The following SQL statement counts the number of unique customers in the "Orders"
table:
Example
SELECT COUNT(DISTINCT CustomerID) AS NumberOfCustomers FROM Orders;
Example
SELECT TOP 1 CustomerName FROM Customers
ORDER BY CustomerID ASC;
MySQL Syntax
SELECT column_name FROM table_name
ORDER BY column_name ASC
LIMIT 1;
Example
SELECT CustomerName FROM Customers
ORDER BY CustomerID ASC
LIMIT 1;
Oracle Syntax
SELECT column_name FROM table_name
ORDER BY column_name ASC
WHERE ROWNUM <=1;
Example
SELECT CustomerName FROM Customers
ORDER BY CustomerID ASC
WHERE ROWNUM <=1;
Example
SELECT TOP 1 CustomerName FROM Customers
ORDER BY CustomerID DESC;
MySQL Syntax
SELECT column_name FROM table_name
ORDER BY column_name DESC
LIMIT 1;
Example
SELECT CustomerName FROM Customers
ORDER BY CustomerID DESC
LIMIT 1;
Oracle Syntax
SELECT column_name FROM table_name
ORDER BY column_name DESC
WHERE ROWNUM <=1;
Example
SELECT CustomerName FROM Customers
ORDER BY CustomerID DESC
WHERE ROWNUM <=1;
Example
SELECT MAX(Price) AS HighestPrice FROM Products;
Example
SELECT MIN(Price) AS SmallestOrderPrice FROM Products;
Example
SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails;
SQL Views
A view is a virtual table.
The view "Current Product List" lists all active products (products that are not
discontinued) from the "Products" table. The view is created with the following SQL:
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No
We can query the view above as follows:
SELECT * FROM [Current Product List]
Another view in the Northwind sample database selects every product in the "Products"
table with a unit price higher than the average unit price:
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName,UnitPrice
FROM Products
WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products)
We can query the view above as follows:
SELECT * FROM [Products Above Average Price]
Another view in the Northwind database calculates the total sale for each category in
1997. Note that this view selects its data from another view called "Product Sales for
1997":
CREATE VIEW [Category Sales For 1997] AS
SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales
FROM [Product Sales for 1997]
GROUP BY CategoryName
We can query the view above as follows:
SELECT * FROM [Category Sales For 1997]
We can also add a condition to the query. Now we want to see the total sale only for
the category "Beverages":
SELECT * FROM [Category Sales For 1997]
WHERE CategoryName='Beverages'