
Blog
SQL for Business: 10 queries every analyst needs
🌐 Machine-translated from Russian. Show original
You don't need to know all SQL analytics — you need to confidently solve typical business tasks. Below are 10 queries that cover most daily questions. Examples for PostgreSQL on tables orders(id, customer_id, amount, status, created_at) and customers(id, city, created_at).
In this part:
1. Revenue by month#
SELECT date_trunc('month', created_at) AS month,
sum(amount) AS revenue, count(*) AS orders
FROM orders WHERE status = 'paid'
GROUP BY 1 ORDER BY 1;
2. Average check and median#
SELECT avg(amount) AS avg_check,
percentile_cont(0.5) WITHIN GROUP (ORDER BY amount) AS median_check
FROM orders WHERE status = 'paid';
The median is fairer than average when there are rare large orders.
3. Top 10 Clients#
SELECT customer_id, sum(amount) AS total, count(*) AS orders
FROM orders WHERE status = 'paid'
GROUP BY customer_id ORDER BY total DESC LIMIT 10;
4. Growth compared to last month#
WITH m AS (
SELECT date_trunc('month', created_at) AS month, sum(amount) AS revenue
FROM orders WHERE status = 'paid' GROUP BY 1
)
SELECT month, revenue,
round(100.0 * (revenue / lag(revenue) OVER (ORDER BY month) - 1), 1) AS growth_pct
FROM m ORDER BY month;
5. Cumulative Outcome#
SELECT created_at::date AS day, sum(amount) AS revenue,
sum(sum(amount)) OVER (ORDER BY created_at::date) AS running_total
FROM orders WHERE status = 'paid'
GROUP BY 1 ORDER BY 1;
6. First customer order#
SELECT DISTINCT ON (customer_id) customer_id, id AS first_order, created_at
FROM orders ORDER BY customer_id, created_at;
7. Repeat purchases#
SELECT count(*) FILTER (WHERE n > 1) * 100.0 / count(*) AS repeat_rate_pct
FROM (SELECT customer_id, count(*) AS n FROM orders WHERE status = 'paid' GROUP BY 1) t;
8. Cohorts by month of first order#
WITH first AS (
SELECT customer_id, date_trunc('month', min(created_at)) AS cohort
FROM orders WHERE status = 'paid' GROUP BY 1
)
SELECT f.cohort,
date_trunc('month', o.created_at) AS month,
count(DISTINCT o.customer_id) AS active
FROM orders o JOIN first f USING (customer_id)
WHERE o.status = 'paid'
GROUP BY 1, 2 ORDER BY 1, 2;
9. Status funnel#
SELECT status, count(*) AS orders,
round(100.0 * count(*) / sum(count(*)) OVER (), 1) AS share_pct
FROM orders GROUP BY status ORDER BY orders DESC;
10. Duplicate search#
SELECT customer_id, amount, created_at::date, count(*)
FROM orders
GROUP BY 1, 2, 3 HAVING count(*) > 1;
Tips#
- First, check the data: duplicates, empty values, test orders. Incorrect data gives confident incorrect conclusions.
- Clearly filter statuses: "revenue" from canceled orders is a common mistake.
- Run analytics queries on replicas or copies, not on the workbase in the middle of the day.
💬 Which queries do you use most often? Add them in the comments — let's gather the second part.
Comments · 0
No comments yet.Sign in to comment, rate and see all comments.