Reading history

SQL Percent of Total and Ratios

4 min read 0 views

Learn to calculate percent of total and percent within groups with window functions, avoid integer division, and prevent divide-by-zero errors with NULLIF.

“Karim brought in 47% of our sales.” “Our cancellation rate is 12.5%.” Percentages and ratios turn raw totals into numbers people can compare. In SQL they are easy to get slightly wrong: integer division quietly gives 0, and a zero count can crash a report. This lesson shows the safe patterns, using window functions for shares of a total and of a group.

In this lesson you will learn

  • How to compute each row’s percent of the grand total
  • How to compute percent within a group
  • Why 2 / 3 gives 0, and how to fix it
  • How to avoid dividing by zero with NULLIF
  • How to count a condition with SUM(condition)

You should know GROUP BY and window functions.

Percent of the Grand Total

-- Each customer's share of delivered sales
SELECT customer,
       SUM(amount) AS sales,
       ROUND(100.0 * SUM(amount) / SUM(SUM(amount)) OVER (), 1) AS pct_of_total
FROM orders
WHERE status = 'delivered'
GROUP BY customer
ORDER BY sales DESC;

Output

+----------+-------+--------------+
| customer | sales | pct_of_total |
+----------+-------+--------------+
| Karim    | 2700  | 47.0         |
| Joya     | 2600  | 45.2         |
| Rina     | 450   | 7.8          |
+----------+-------+--------------+
(3 rows)
  • SUM(amount) is each customer’s total after grouping.
  • SUM(SUM(amount)) OVER () adds up those group totals across the whole result. The empty OVER () means “all rows”. Here the grand total is 5,750.
  • Multiplying by 100.0 first makes the division use decimals, and ROUND(…, 1) keeps one decimal place.

The three shares add up to 100.0. After rounding, shares sometimes add to 99.9 or 100.1; that is normal and worth a note under a report.

Percent Within a Group, and Two Traps

-- Share of each employee's salary within their manager's team
SELECT m.name AS manager,
       e.name AS employee,
       e.salary,
       ROUND(100.0 * e.salary / SUM(e.salary) OVER (PARTITION BY e.manager_id), 1) AS pct_of_team
FROM employees AS e
JOIN employees AS m ON m.id = e.manager_id
ORDER BY m.name, e.salary DESC;

-- Integer division trap
SELECT 2 / 3        AS int_division,
       2 * 1.0 / 3  AS real_division,
       100 * 2 / 3  AS whole_percent;

-- Ratio of cancelled to all orders, safe against dividing by zero
SELECT COUNT(*) AS all_orders,
       SUM(status = 'cancelled') AS cancelled,
       ROUND(100.0 * SUM(status = 'cancelled') / NULLIF(COUNT(*), 0), 1) AS cancel_rate_pct
FROM orders;

Output

+---------+----------+--------+-------------+
| manager | employee | salary | pct_of_team |
+---------+----------+--------+-------------+
| Faisal  | Mou      | 95000  | 51.4        |
| Faisal  | Rubel    | 90000  | 48.6        |
| Lipi    | Anik     | 70000  | 100.0       |
| Rubel   | Sumi     | 25000  | 100.0       |
| Shahana | Faisal   | 180000 | 51.4        |
| Shahana | Lipi     | 170000 | 48.6        |
+---------+----------+--------+-------------+
(6 rows)

+--------------+--------------------+---------------+
| int_division | real_division      | whole_percent |
+--------------+--------------------+---------------+
| 0            | 0.6666666666666666 | 66            |
+--------------+--------------------+---------------+
(1 row)

+------------+-----------+-----------------+
| all_orders | cancelled | cancel_rate_pct |
+------------+-----------+-----------------+
| 8          | 1         | 12.5            |
+------------+-----------+-----------------+
(1 row)
  • OVER (PARTITION BY e.manager_id) totals salaries within each manager’s team, so every team adds up to 100%.
  • Integer division: 2 / 3 is 0 in SQLite, PostgreSQL and SQL Server, because both numbers are integers. Write 100.0 * or * 1.0 before dividing. (MySQL’s / already returns a decimal.)
  • SUM(status = 'cancelled') counts matching rows, because a true comparison is 1 and false is 0 in SQLite and MySQL. In other databases write SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) or COUNT(*) FILTER (WHERE …) in PostgreSQL.
  • NULLIF(COUNT(*), 0) turns a zero count into NULL. Dividing by NULL gives NULL instead of an error, so an empty month shows a blank rate rather than breaking the report.

Choosing the Right Denominator

The hardest part of a ratio is usually deciding what to divide by. “Cancellation rate” could mean cancelled ÷ all orders, or cancelled ÷ orders that were not pending. Both are valid; they answer different questions. Write the definition next to the number in any report, for example “12.5% of all 8 orders”.

Common Mistakes

  1. Integer division. COUNT(x) / COUNT(*) is 0 for most rates. Multiply by 100.0 first.
  2. Rounding too early. Round only the final percentage, not the parts you divide.
  3. Forgetting NULLs. SUM(amount) skips NULL amounts, while COUNT(*) counts those rows. Make sure the top and bottom of the fraction cover the same rows.
  4. Dividing by zero. Wrap the denominator in NULLIF(…, 0).

Practice Exercises

Exercise 1. Show each department’s share of all students, as a percentage.

Show answer
SELECT dept, COUNT(*) AS students,
       ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS pct
FROM students
GROUP BY dept;

CSE has 4 of 8 students (50.0%), EEE and BBA have 2 each (25.0%).

Exercise 2. What does SELECT 7 / 2; return in SQLite, and how do you get 3.5?

Show answer

It returns 3, because both numbers are integers. Write 7 / 2.0 or 7 * 1.0 / 2 to get 3.5.

Frequently Asked Questions

How do I calculate percentage of total in SQL?

Divide each row’s value by the total over all rows using a window function, for example 100.0 times SUM(amount) divided by SUM(SUM(amount)) OVER (). Multiplying by 100.0 first avoids integer division.

Why does my SQL percentage show 0?

Both numbers in the division are integers, so the result is rounded down to a whole number. Multiply by 100.0 or 1.0 before dividing so the database uses decimal division.

Summary

  • Percent of total: value ÷ SUM(…) OVER ().
  • Percent within a group: add PARTITION BY.
  • Multiply by 100.0 before dividing to avoid integer division.
  • Use NULLIF(denominator, 0) to avoid division-by-zero errors.

Next: SQL Date Range Overlaps.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *