SQL for Data Analysis: Data query and analysis

1. The Core Structure of Data Analysis with SQL

Suppose there are three business tables:

users (
    user_id,
    signup_at,
    country
)

orders (
    order_id,
    user_id,
    order_at,
    amount,
    status
)

order_items (
    order_id,
    product_id,
    quantity,
    unit_price
)

The following examples primarily use these tables.

Typical analysis SQL:

SELECT
    u.country,
    COUNT(DISTINCT o.user_id) AS paying_users,
    SUM(o.amount) AS revenue
FROM orders o
JOIN users u ON o.user_id = u.user_id
WHERE o.status = 'paid'
GROUP BY u.country
HAVING SUM(o.amount) > 10000
ORDER BY revenue DESC
LIMIT 10;

SQL logical execution sequence

It is important to understand the logical execution sequence:

FROM / JOIN
    ↓
WHERE
    ↓
GROUP BY
    ↓
HAVING
    ↓
SELECT
    ↓
DISTINCT
    ↓
ORDER BY
    ↓
LIMIT

This is a simplified sequence for understanding the semantics of SQL and does not represent the actual physical execution plan of the database.

Window functions are usually calculated after grouping and aggregation.

Therefore, the window function results of the same layer query cannot be used directly in WHERE and need to be processed through subqueries or CTE.

2. SELECT, WHERE and CASE

Basic screening

SELECT
    user_id,
    amount,
    order_at
FROM orders
WHERE status = 'paid'
  AND amount >= 100
ORDER BY order_at DESC
LIMIT 100;

Common conditions:

amount BETWEEN 100 AND 500
status IN ('paid', 'completed')
country IS NOT NULL
name ILIKE '%apple%'

PostgreSQL in:

  • LIKE: Pattern matching.
  • ILIKE: Case-insensitive pattern matching.
  • IN: Match the specified set.
  • BETWEEN: Contains two endpoints.

CASE WHEN

Used to construct analytical categories.

SELECT
    order_id,
    amount,
    CASE
        WHEN amount >= 1000 THEN 'high'
        WHEN amount >= 100 THEN 'medium'
        ELSE 'low'
    END AS amount_level
FROM orders;

Can also be used for conditional calculations:

SELECT
    order_id,
    amount,
    CASE
        WHEN status = 'paid' THEN amount
        ELSE 0
    END AS valid_revenue
FROM orders;

NULL and COALESCE

NULL in SQL means unknown or missing, not equal to 0.

SELECT
    COALESCE(amount, 0) AS amount
FROM orders;

COALESCE() returns the first non-NULL value.

Note:

WHERE amount = NULL

It is wrong to judge NULL, you should use:

WHERE amount IS NULL

3. GROUP BY: Group aggregation

One of the most frequently used SQL functions in data analysis.

SELECT
    user_id,
    COUNT(*) AS order_count,
    SUM(amount) AS total_spending,
    AVG(amount) AS avg_order_amount,
    MIN(amount) AS min_amount,
    MAX(amount) AS max_amount
FROM orders
WHERE status = 'paid'
GROUP BY user_id;

Common aggregate functions:

functionPurpose
COUNT(*)Count rows
COUNT(column)Count the number of non-NULL values
COUNT(DISTINCT column)Count the number of different non-NULL values
SUM()Sum
AVG()average
MIN() / MAX()minimum value, maximum value
STDDEV_SAMP()sample standard deviation
VAR_SAMP()sample variance

WHERE and HAVING

  • WHERE: Filter rows before aggregation.
  • HAVING: Filter group after aggregation.

For example, find users whose cumulative consumption exceeds 1,000:

SELECT
    user_id,
    SUM(amount) AS total_spending
FROM orders
WHERE status = 'paid'
GROUP BY user_id
HAVING SUM(amount) > 1000;

Conditional aggregation: FILTER

PostgreSQL You can use FILTER to specify conditions on aggregate functions.

SELECT
    user_id,
    COUNT(*) AS total_orders,
    COUNT(*) FILTER (
        WHERE status = 'paid'
    ) AS paid_orders,
    SUM(amount) FILTER (
        WHERE status = 'paid'
    ) AS paid_revenue
FROM orders
GROUP BY user_id;

FILTER is usually clearer than writing multiple CASE WHEN repeatedly.

Other databases can also be used:

SUM(
    CASE WHEN status = 'paid'
         THEN amount
         ELSE 0
    END
)

Conditional proportion

Calculate payment order ratio:

SELECT
    COUNT(*) FILTER (
        WHERE status = 'paid'
    )::numeric / NULLIF(COUNT(*), 0) AS paid_rate
FROM orders;

Here:

  • ::numeric: Avoid precision loss caused by integer division.
  • NULLIF(x, 0): Returns NULL when the denominator is 0 to avoid division by zero errors.

4. JOIN: Joining Data

Analysis tasks often require correlating multiple data sources.

SELECT
    o.order_id,
    u.country,
    o.amount
FROM orders o
JOIN users u
    ON o.user_id = u.user_id;

Common JOIN

Typemeaning
INNER JOINKeep only matching records
LEFT JOINKeep all records in the left table
RIGHT JOINKeep all records in the right table
FULL OUTER JOINKeep all records in both tables
CROSS JOINCartesian product

Repeat counting problem after JOIN

This is one of the most common mistakes in data analysis SQL.

Assumptions:

orders:
order_id = 1, amount = 100

order_items:
order_id = 1, product A
order_id = 1, product B

Directly JOIN:

SELECT SUM(o.amount)
FROM orders o
JOIN order_items i
    ON o.order_id = i.order_id;

Two lines will appear for this order, causing SUM(o.amount) to be calculated as 200.

The core problem of is that the data granularity (Grain) has changed.

The right approach depends on the analysis needs. For example, when calculating revenue by order, you can aggregate it directly in the orders table, or aggregate the detailed table to the order level before JOIN.

EXISTS

If you only need to determine whether the user has an order, there is no need to generate duplicate rows with JOIN:

SELECT
    u.user_id
FROM users u
WHERE EXISTS (
    SELECT 1
    FROM orders o
    WHERE o.user_id = u.user_id
      AND o.status = 'paid'
);

EXISTS is an existence filter and will not return user rows repeatedly because it matches multiple orders.

5. CTE and subquery

CTE: Common Table Expression, common table expression.

Define temporary named query results via WITH.

WITH user_revenue AS (
    SELECT
        user_id,
        SUM(amount) AS revenue
    FROM orders
    WHERE status = 'paid'
    GROUP BY user_id
)
SELECT
    u.country,
    AVG(r.revenue) AS avg_user_revenue
FROM user_revenue r
JOIN users u ON r.user_id = u.user_id
GROUP BY u.country;

The main advantage of CTE is that it makes complex analytical queries easier to read and maintain.

Raw Data
    ↓
CTE 1: Filter
    ↓
CTE 2: Aggregate
    ↓
CTE 3: Calculate
    ↓
Final SELECT

Need to pay attention to:

  • CTE does not mean actually creating a persistent table.
  • PostgreSQL The optimizer may inline CTE, or it may materialize it.
  • CTE is not necessarily faster than a subquery and should be judged based on the execution plan.

6. Window Functions: Window function

The window function is the most important function of the analytical SQL to master.

Ordinary GROUP BY will summarize multiple rows into one row or one row per group.

The window function can calculate rankings, cumulative values, moving averages and other indicators based on associated rows while retaining the original rows.

Basic syntax:

FUNCTION(...) OVER (
    PARTITION BY ...
    ORDER BY ...
    ROWS BETWEEN ...
)

Among them:

  • PARTITION BY: Window grouping.
  • ORDER BY: Sorting within the window.
  • ROWS BETWEEN: Define the window frames participating in the calculation.

ROW_NUMBER、RANK、DENSE_RANK

For example, ranking according to user consumption amount:

SELECT
    user_id,
    amount,
    ROW_NUMBER() OVER (
        ORDER BY amount DESC, order_id
    ) AS row_num,
    RANK() OVER (
        ORDER BY amount DESC
    ) AS rank_num,
    DENSE_RANK() OVER (
        ORDER BY amount DESC
    ) AS dense_rank_num
FROM orders
WHERE status = 'paid';

The difference between the three:

Assume the amounts are in order:

100, 90, 90, 80
AmountROW_NUMBERRANKDENSE_RANK
100111
902/322
903/222
80443

ROW_NUMBER() requires additional unique sorting columns to obtain a definite row numbering sequence when the sorting values are the same.

Each group Top-N

For example, each user’s 3 most recent orders:

WITH ranked_orders AS (
    SELECT
        order_id,
        user_id,
        amount,
        ROW_NUMBER() OVER (
            PARTITION BY user_id
            ORDER BY order_at DESC, order_id DESC
        ) AS rn
    FROM orders
)
SELECT *
FROM ranked_orders
WHERE rn <= 3;

This is a very common analysis pattern.

LAG / LEAD

Get the previous or next record in the same group.

SELECT
    user_id,
    order_at,
    amount,
    LAG(amount) OVER (
        PARTITION BY user_id
        ORDER BY order_at, order_id
    ) AS previous_amount
FROM orders;

LEAD() gets the following value.

Available for:

  • month-on-month growth.
  • Comparison of user behavior before and after.
  • Order interval.
  • Status change detection.

Cumulative sum

SELECT
    user_id,
    order_at,
    amount,
    SUM(amount) OVER (
        PARTITION BY user_id
        ORDER BY order_at, order_id
        ROWS BETWEEN UNBOUNDED PRECEDING
                 AND CURRENT ROW
    ) AS cumulative_amount
FROM orders
WHERE status = 'paid';

moving average

Calculate the average of the last 7 rows of data:

SELECT
    day,
    revenue,
    AVG(revenue) OVER (
        ORDER BY day
        ROWS BETWEEN 6 PRECEDING
                 AND CURRENT ROW
    ) AS moving_avg_7
FROM daily_revenue;

ROWS here means the first 6 lines plus the current line.

It corresponds to the strictly last 7 calendar days only if daily_revenue has exactly one row per date and the dates are consecutive.

The window functions ROWS and RANGE have different meanings; the default window frame may also be affected by rows with the same sort value. Therefore, it is easier to avoid unexpected results by explicitly writing ROWS BETWEEN when performing cumulative calculations.

7. Date and time series analysis

PostgreSQL provides a large number of date and time functions.

DATE_TRUNC

Aggregation by day, month, quarter, etc. time granularity:

SELECT
    DATE_TRUNC('month', order_at) AS month,
    SUM(amount) AS revenue
FROM orders
WHERE status = 'paid'
GROUP BY 1
ORDER BY 1;

Commonly used granularity:

day
week
month
quarter
year

EXTRACT

Extract specific parts of time:

SELECT
    EXTRACT(YEAR FROM order_at) AS year,
    EXTRACT(MONTH FROM order_at) AS month
FROM orders;

Time range filter

It is recommended to use left-closed and right-open intervals:

WHERE order_at >= TIMESTAMP '2026-01-01'
  AND order_at < TIMESTAMP '2026-02-01'

More reliable than using BETWEEN to specify the last second of the day.

Generate consecutive dates

Some days there are no orders, but the report still needs to show 0.

PostgreSQL can use generate_series():

WITH dates AS (
    SELECT generate_series(
        DATE '2026-01-01',
        DATE '2026-01-07',
        INTERVAL '1 day'
    )::date AS day
),
daily AS (
    SELECT
        order_at::date AS day,
        SUM(amount) AS revenue
    FROM orders
    WHERE status = 'paid'
      AND order_at >= TIMESTAMP '2026-01-01'
      AND order_at < TIMESTAMP '2026-01-08'
    GROUP BY 1
)
SELECT
    d.day,
    COALESCE(s.revenue, 0) AS revenue
FROM dates d
LEFT JOIN daily s ON d.day = s.day
ORDER BY d.day;

For timestamptz, the business time zone also needs to be clarified to prevent the date attribution from changing with the database session time zone.

8. Analysis of common business indicators

DAU:Daily Active Users

Assume there is an event table:

events (
    user_id,
    event_at,
    event_name
)

Daily active users:

SELECT
    event_at::date AS day,
    COUNT(DISTINCT user_id) AS dau
FROM events
GROUP BY 1
ORDER BY 1;

In actual business, it is necessary to clarify which events represent active events and which time zone is used to divide natural days.

ARPU

ARPU:Average Revenue Per User。

For example, calculate the average income of registered users in each country:

WITH revenue AS (
    SELECT
        user_id,
        SUM(amount) AS total_revenue
    FROM orders
    WHERE status = 'paid'
    GROUP BY user_id
)
SELECT
    u.country,
    COALESCE(SUM(r.total_revenue), 0)
        / NULLIF(COUNT(DISTINCT u.user_id), 0) AS arpu
FROM users u
LEFT JOIN revenue r ON u.user_id = r.user_id
GROUP BY u.country;

Note: The denominator of ARPU should be defined by the business, usually the target user group within a specified period, rather than simply using all historical registered users.

conversion rate

Suppose there are two events:

view_product
purchase

Calculate the proportion of users who viewed at least once and purchased at least once:

WITH user_actions AS (
    SELECT
        user_id,
        BOOL_OR(event_name = 'view_product') AS viewed,
        BOOL_OR(event_name = 'purchase') AS purchased
    FROM events
    GROUP BY user_id
)
SELECT
    COUNT(*) FILTER (
        WHERE viewed AND purchased
    )::numeric
    / NULLIF(
        COUNT(*) FILTER (WHERE viewed),
        0
    ) AS conversion_rate
FROM user_actions;

This example only counts whether the user has taken two types of actions, and does not guarantee that the purchase occurred after browsing.

True funnel analysis also typically requires consideration of sequence of events, observation windows, and conversion attribution rules.

9. Cohort Analysis and Retention

Cohort Analysis Group users based on their common starting time and observe subsequent behavior.

For example, divide Cohort according to the registration month, and then observe the activity in each month.

Signup Month
     ↓
Cohort
     ↓
Month 0 / Month 1 / Month 2 ...
     ↓
Retention Rate

Example:

WITH cohorts AS (
    SELECT
        user_id,
        DATE_TRUNC('month', signup_at)::date
            AS cohort_month
    FROM users
),
monthly_active AS (
    SELECT DISTINCT
        user_id,
        DATE_TRUNC('month', event_at)::date
            AS active_month
    FROM events
),
cohort_size AS (
    SELECT
        cohort_month,
        COUNT(*) AS users
    FROM cohorts
    GROUP BY 1
),
retention AS (
    SELECT
        c.cohort_month,
        (
            EXTRACT(YEAR FROM a.active_month)::int
            - EXTRACT(YEAR FROM c.cohort_month)::int
        ) * 12
        + (
            EXTRACT(MONTH FROM a.active_month)::int
            - EXTRACT(MONTH FROM c.cohort_month)::int
        ) AS month_number,
        COUNT(DISTINCT c.user_id) AS active_users
    FROM cohorts c
    JOIN monthly_active a
      ON c.user_id = a.user_id
     AND a.active_month >= c.cohort_month
    GROUP BY 1, 2
)
SELECT
    r.cohort_month,
    r.month_number,
    r.active_users,
    r.active_users::numeric
        / NULLIF(s.users, 0) AS retention_rate
FROM retention r
JOIN cohort_size s USING (cohort_month)
ORDER BY r.cohort_month, r.month_number;

Need to pay attention to:

  • The denominator is the original number of Cohort users.
  • The numerator is the number of Cohort users active that month.
  • Months with no active users require additional zeros.
  • Cohort months that have not yet been fully observed should not be directly compared to full months.
  • The definitions of monthly retention, next-day retention, and 7-day retention are different.

10. Quantiles and advanced aggregation

Percentile

For example, the median of the statistical order amount and P90:

SELECT
    PERCENTILE_CONT(0.5)
        WITHIN GROUP (ORDER BY amount) AS p50,
    PERCENTILE_CONT(0.9)
        WITHIN GROUP (ORDER BY amount) AS p90
FROM orders
WHERE status = 'paid';

PERCENTILE_CONT is defined using continuous quantiles, possibly interpolated.

PERCENTILE_DISC selects discrete quantiles from existing data values.

GROUPING SETS

Compute multiple aggregation dimensions at once:

SELECT
    country,
    status,
    COUNT(*) AS order_count
FROM order_summary
GROUP BY GROUPING SETS (
    (country, status),
    (country),
    (status),
    ()
);

order_summary is assumed to be a prepared order analysis table.

ROLLUP is also commonly used to generate hierarchical subtotals and totals.

These functions are more useful in multidimensional statistical reports, but mastering GROUP BY, FILTER, and window functions is usually sufficient for general data analysis.

11. EXPLAIN and query performance

Data analysis queries may scan large amounts of data, so it is important to understand the execution plan.

EXPLAIN
SELECT *
FROM orders
WHERE user_id = 123;

View real execution information:

EXPLAIN (ANALYZE, BUFFERS)
SELECT
    user_id,
    SUM(amount)
FROM orders
WHERE status = 'paid'
GROUP BY user_id;

ANALYZE actually executes the query and should be used with caution on statements that have data-modifying side effects.

Common execution nodes:

nodemeaning
Seq Scansequential scan
Index Scanindex scan
Hash Joinhash join
Nested LoopNested loop join
Merge Joinsort merge join
HashAggregateHash aggregation
Sortsort

Common optimization principles

1. Try to screen unnecessary data in advance

WHERE order_at >= ...

2. Query only the required column

Avoid unnecessary SELECT *.

3. Properly build index

For example:

CREATE INDEX idx_orders_user_time
ON orders (user_id, order_at);

Indexes help with partial filtering, correlation, and sorting, but they increase storage and write maintenance costs and do not necessarily improve large-scale aggregation scans.

4. Avoid unnecessary function calculations on filter columns

For example:

WHERE order_at::date = DATE '2026-01-01'

This can usually be changed to:

WHERE order_at >= TIMESTAMP '2026-01-01'
  AND order_at < TIMESTAMP '2026-01-02'

This makes it easier to take advantage of ordinary time column indexes.

5. Check the change in the number of rows after JOIN

Many errors in analyzing SQL are not errors in the calculation formula, but that JOIN enlarges the data granularity.

6. Consider pre-aggregation for large-scale repeat analyses.

If you need to frequently count large amounts of detailed data, you may consider:

  • Summary Table。
  • Materialized View。
  • Partition table.
  • Column analysis database, such as DuckDB, ClickHouse.

Note: DuckDB and ClickHouse cannot simply be regarded as complete replacements for PostgreSQL. They have different positioning in terms of storage and execution architecture.

12. Common mistakes in data analysis SQL

ErrorConsequences
JOIN directly followed by SUM main table amountRepeat count
Ignore the difference between COUNT(*) and COUNT(column)The quantity is inaccurate
Use integer divisionRatio is truncated
No clear time zoneDay/month attribution error
ORDER BY is not uniqueRanking, LAG result uncertain
Treat ROWS 6 PRECEDING as the last 7 daysTime window error
NULL directly participate in the comparisonThe condition result is not as expected
Do not define indicator denominator and observation windowConversion rate and retention rate distortion
A large number of queries only look at the averageIgnore data distribution and long tail

In particular, you need to understand Grain (data granularity).

For example:

Users table → One row per user
Orders table → One line per order
Order Items table → One line per order item
Events table → One line per event

Data granularity determines which fields can be directly summed, counted, and whether re-aggregation is required after JOIN.


Summary

Knowledge pointsimportance
SELECT / WHERE / CASEcore
GROUP BY / HAVINGcore
COUNT DISTINCT / FILTERcore
JOIN / EXISTScore
CTE / Subquerycore
Window Functionscore
ROW_NUMBER / RANK / DENSE_RANKhigh frequency
LAG / LEADhigh frequency
Rolling / Cumulative Aggregationhigh frequency
DATE_TRUNC / EXTRACThigh frequency
generate_seriesTime series commonly used
PercentileCommonly used in statistical analysis
Cohort / RetentionProduct analysis is important
EXPLAIN / IndexPerformance optimization is important
GROUPING SETS / ROLLUPon demand

SQL The five most important abilities in data analysis:

  1. Aggregation: Calculate the indicator using GROUP BY, aggregate functions and conditional aggregation.
  2. Data Joining: Understand the relationships between tables and changes in data granularity.
  3. Window Functions: Calculate ranking, cumulative value, lag value and moving window.
  4. Time Series Analysis: Calculate the trend, growth rate and retention rate according to the time dimension.
  5. Query Optimization: Control query costs through execution plans, filtering and reasonable indexing.

Common analysis workflows:

Database
    ↓
Filter / Join
    ↓
Aggregate / Window Functions
    ↓
CTE / Derived Metrics
    ↓
Analysis Results
    ↓
Pandas / Visualization / Dashboard

Reference documentation

Back to top