WMA Hub

SQL snippet library

Copy-ready SQL queries, each with an explanation, the tables it assumes and the mistakes to avoid.

  • Share of total

    Aggregation & grouping · Intermediate · generic

    Show each group as a percentage of the grand total using a window function.

  • Total and average per group

    Aggregation & grouping · Beginner · generic

    Add up and average a number for every value of a column, with GROUP BY.

  • Find duplicate rows

    Data quality & cleaning · Beginner · generic

    List the values that appear more than once, with HAVING COUNT(*) > 1.

  • Orders per month (SQLite)

    Dates & time · Beginner · sqlite

    Count and add up orders by month with strftime.

  • Customers with no orders (LEFT JOIN)

    Joins · Beginner · generic

    Find the rows of one table that have no match in another table.

  • Top 2 orders for each customer

    Ranking & Top N · Intermediate · generic

    Rank rows inside each group with ROW_NUMBER and keep the first few.

  • Running total by month

    Running totals & trends · Intermediate · sqlite

    A cumulative total that grows month by month, with a window SUM.

  • Latest order for each customer

    Subqueries & CTEs · Intermediate · generic

    Keep only the most recent row per customer using a CTE and ROW_NUMBER.

  • Month-over-month change with LAG

    Window functions · Intermediate · sqlite

    Compare each month with the month before it using LAG.