How to calculate Gross Profit Margin
Gross profit margin is the percentage of revenue left after paying the direct costs of producing what you sold.
Formula
Gross margin % = (revenue − cost of goods sold) ÷ revenue × 100SQL query
This example assumes: sales(product, sold_at, revenue, cogs). It is written in PostgreSQL syntax; date functions differ slightly in MySQL, BigQuery and SQLite, and your column names will differ from these.
SELECT product,
SUM(revenue) AS revenue,
SUM(revenue - cogs) AS gross_profit,
SUM(revenue - cogs) * 100.0 / NULLIF(SUM(revenue), 0) AS gross_margin_pct
FROM sales
WHERE sold_at >= DATE '2026-01-01'
GROUP BY product
ORDER BY gross_margin_pct;Common mistakes that make Gross Profit Margin wrong
- Missing cost on some products makes their margin look 100%; count rows with no cost.
- Average of per-product margins is not the overall margin; sum first, then divide.
- Costs booked in a later period than the sale shift margin between months.
Ask for Gross Profit Margin in plain English
Instead of writing the query yourself, you can type the question. SchemaChat turns it into SQL against your connected database or uploaded file, runs it, and shows the SQL and the figures it used so you can check the answer before you share it. It does not replace your judgement about the definition: check that the query matches the formula your business uses.
- What is gross margin by product for this year?
- Which products have the lowest gross margin?