How to calculate percentage with a SQL statement
How can you calculate a percentage using a SQL statement?This question explores how to use SQL queries to compute percentages from your data by applying basic arithmetic within SELECT statements, often using COUNT, SUM, or subqueries.
Calculating a percentage in SQL might sound tricky at first, but it’s actually quite straightforward once you get the hang of it. You just need to understand how to work with basic arithmetic in your SQL queries. Typically, you'll divide part of a total by the whole, then multiply by 100.
Here’s how you can approach it:
Basic Percentage Formula
SELECT (part_column * 100.0) / total_column AS percentage
FROM your_table;
You multiply by 100.0 to make sure the result is a decimal and not rounded down to zero (which happens in integer division).
Example 1: Percentage of total sales
Let’s say you want to calculate the percentage each product contributes to total sales:
SELECT
product_name,
(sales_amount * 100.0) / (SELECT SUM(sales_amount) FROM sales) AS sales_percentage
FROM sales;
Example 2: Percentage of records
You can also calculate what percentage of rows meet a certain condition:
SELECT
(COUNT(*) * 100.0) / (SELECT COUNT(*) FROM employees) AS percent_full_time
FROM employees
WHERE employment_type = 'Full-Time';
A few things to keep in mind:
- Always use 100.0 (not 100) to avoid integer division.
- Use subqueries when you need totals or aggregates from the same table.
- You can round the result using ROUND() if needed.