TECHNOLOGIESTieInn Technologies

Aggregate functions

SQL · 15 questions

Short notes

Key idea

Aggregate functions squeeze many rows into one value: how many, how much, the average, the smallest, the largest.

Syntax

SELECT COUNT(*)            AS orders,
       COUNT(coupon_code)  AS with_coupon,
       COUNT(DISTINCT customer_id) AS customers,
       SUM(amount), AVG(amount), MIN(amount), MAX(amount)
FROM orders;

Example

Average order value in March:

SELECT ROUND(AVG(amount), 2) AS avg_order
FROM orders
WHERE order_date >= '2024-03-01' AND order_date < '2024-04-01';

WHERE filters first, then the average is taken over the rows left.

Traps

  • COUNT(*) counts rows; COUNT(col) skips NULLs in that column.
  • AVG ignores NULLs, so it's the average of the known values, not of all rows.
  • Integer division: PostgreSQL and SQL Server give 5 / 2 = 2; DuckDB and MySQL give 2.5. Write * 1.0 so a percentage is right everywhere.
  • Don't mix plain columns with aggregates without GROUP BY; SELECT city, COUNT(*) FROM t is an error.

Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    Aggregate functions

  1. Question 1easy

    What does COUNT(city) count?

  2. Aggregate functions

  3. Question 2medium

    The customers table has 40 rows, and 3 customers have no city. What does this return?

    SELECT COUNT(*) - COUNT(city) FROM customers;
  4. Aggregate functions

  5. Question 3hard

    order_items has 166 lines. 27 of them have no discount recorded. How many rows does COUNT see here?

    SELECT COUNT(quantity * unit_price - discount)
    FROM order_items;
  6. Aggregate functions

  7. Question 4medium

    A column has the values 10, 20, and NULL. What is AVG(column)?

  8. Aggregate functions

  9. Question 5medium

    No order has the status 'lost'. What does this query return?

    SELECT SUM(amount)
    FROM orders
    WHERE status = 'lost';

10 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.