Introduction
These functions help you quickly find totals, averages, and extremes in your data. They make it easy to understand big groups of numbers.
These functions help you quickly find totals, averages, and extremes in your data. They make it easy to understand big groups of numbers.
SELECT AGGREGATE_FUNCTION(column_name) FROM table_name; -- AGGREGATE_FUNCTION can be COUNT, SUM, AVG, MIN, or MAX
SELECT COUNT(*) FROM orders;
SELECT SUM(price) FROM products;
SELECT AVG(score) FROM tests;
SELECT MIN(age), MAX(age) FROM users;
This example creates a sales table, adds some fruit sales, then uses all five functions to summarize the data.
CREATE TABLE sales ( id SERIAL PRIMARY KEY, product VARCHAR(50), quantity INT, price NUMERIC ); INSERT INTO sales (product, quantity, price) VALUES ('Apple', 10, 0.5), ('Banana', 5, 0.3), ('Orange', 8, 0.7); SELECT COUNT(*) AS total_sales, SUM(quantity) AS total_quantity, AVG(price) AS average_price, MIN(price) AS cheapest_price, MAX(price) AS most_expensive_price FROM sales;
COUNT(*) counts all rows, even if some columns are NULL.
SUM and AVG ignore NULL values in the column.
MIN and MAX work on numbers, dates, and text (alphabetical order).
COUNT, SUM, AVG, MIN, MAX are easy ways to get quick info from many rows.
They help you see totals, averages, and extremes in your data.
Use them in SELECT queries to summarize your tables.
COUNT(column_name) do in a PostgreSQL query?price column in a table named products?sales with column amount containing values (100, 200, NULL, 300), what is the result of this query?SELECT COUNT(amount), SUM(amount), AVG(amount), MIN(amount), MAX(amount) FROM sales;
SELECT COUNT(*), SUM(price), AVG(price) FROM products WHERE price > 'ten';
orders with columns customer_id and total_amount. How do you write a query to find the average order amount for each customer, but only include customers with at least 5 orders?Pass the test and this pattern moves unknown