We’re improving Formula Genius. We’re redesigning the app and fixing issues along the way. Sorry for any disruption, and thank you for your patience.
SQL intermediate

How to Calculate Each Row's Percentage of Total in SQL?

Understanding how to express each row's value as a percentage of the total can simplify data analysis. This guide shows you how to achieve this using window functions.

Formula Genius can generate a draft from a plain-English prompt. Supported formulas can be checked with sample cases; review the coverage on the result.

The formula

Prompt

"Calculate each row's value as a percentage of the total using a window function instead of a subquery"

SQL
SELECT value, (value * 100.0 / SUM(value) OVER ()) AS percentage FROM your_table;

This SQL query calculates each row's value as a percentage of the total sum of the values in the specified column.

Step-by-step breakdown

  1. SELECT value: Selects the column containing the values you want to analyze.
  2. SUM(value) OVER (): Computes the total sum of the values across all rows without grouping.
  3. value * 100.0: Multiplies the individual row value by 100 to convert it into a percentage.
  4. AS percentage: Renames the resulting column to 'percentage' for clarity.

Edge cases & warnings

  • If the total sum is zero, the percentage calculation will result in NULL or an error.
  • Rows with NULL values in the 'value' column will not contribute to the total sum.
  • If all values are negative, the percentages will also be negative, which may be unexpected.

Examples

Prompt

"Table with values: (100, 200, 300)"

SQL
Percentage results: (16.67%, 33.33%, 50.00%)
Prompt

"Table with values: (50, 50, 100)"

SQL
Percentage results: (25.00%, 25.00%, 50.00%)

Frequently asked questions

What happens if there are NULL values?

NULL values will be ignored in the total sum calculation.

Can I use this with GROUP BY?

Yes, but you need to adjust the window function accordingly.

Is the percentage calculated for each row or overall?

The percentage is calculated for each individual row based on the total sum.

Can't find what you need?

Describe a formula in plain English. Formula Genius drafts and explains it, and can check supported formulas on sample cases.