Uncategorized

Practical SQL Query Patterns: A Hands-On Collection

Practical SQL Query Patterns: A Hands-On Collection

sql query examples

Practical SQL Query Patterns: A Hands-On Collection is a field guide for developers who want reliable answers without reinventing joins, filters, and aggregations every time. The goal is not to memorize every command but to recognize recurring shapes that make sql query examples easier to adapt, test, and explain. Each pattern below solves a common task, from finding duplicates to ranking rows within groups, and each one rewards careful attention to edge cases, indexes, and readability.

Start with Filtering and Sorting

A simple WHERE clause is the backbone of most reporting queries. When you filter on multiple columns, put the most selective predicate first and use parentheses when mixing AND and OR; otherwise the database may apply logic you did not intend. For example, a query that looks for active customers in one region should group those conditions explicitly. Sorting is equally practical: order by the columns users actually scan, and add a deterministic tie-breaker such as an ID so pagination does not shuffle rows between pages.

Pattern: Count Rows Without Loading Them

sql query examples

Use COUNT(*) in a dedicated query instead of fetching every row and counting in application code. If you need totals for several categories, conditional aggregation with CASE lets one scan produce multiple counts, which is often faster than several separate queries. This is one of the most reusable sql query examples because it scales from dashboards to ad hoc checks without changing the table structure.

Join Patterns That Stay Readable

Inner joins answer “which rows match,” while left joins preserve the first table and expose missing related records. A practical habit is to qualify every column with its table alias, especially when joins grow beyond two tables. For anti-joins—finding parent rows with no children—use NOT EXISTS or a left join with a null check; both are clearer than a subquery that returns a list. Keep join conditions in the ON clause and filtering conditions in WHERE so the query’s intent remains obvious.

Pattern: Find Duplicates Before They Become Incidents

sql query examples

Duplicate detection usually follows GROUP BY plus HAVING. Group on the natural key, count rows, and filter groups with a count greater than one. Add MIN(id) and MAX(id) to see the spread, then join those IDs back to the table for details. This pattern is safer than scanning manually because it produces reproducible evidence. Pair it with a unique index on the natural key to prevent future duplicates instead of only reporting them.

Aggregations and Window Functions

Window functions handle ranking, running totals, and comparisons across rows without collapsing detail. A common pattern is ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) to pick the latest order per customer. Another is SUM(amount) OVER (PARTITION BY account_id ORDER BY posted_at) for a running balance. These queries are easier to audit than correlated subqueries because the partitioning and ordering are visible in one place.

Pattern: Pivot with Conditional Aggregation

When you need columns like pending_count, shipped_count, and cancelled_count, use SUM(CASE WHEN status = ‘pending’ THEN 1 ELSE 0 END) and repeat for each status. This keeps one row per entity and avoids multiple self-joins. It is also easy to extend when a new status appears. For teams learning to read execution plans, this pattern is a good exercise because it often benefits from a covering index on the grouping columns.

sql query examples

Pagination Without Surprises

Offset pagination is easy to write but slows down on large tables and can skip or repeat rows when data changes. Keyset pagination avoids both problems: filter on the last seen sort key, order by that key plus a unique tie-breaker, and fetch the next page with a limit. For example, WHERE (created_at, id) < (:last_created_at, :last_id) ORDER BY created_at DESC, id DESC LIMIT 50. This approach uses an index on the sort columns and stays stable under concurrent inserts. Document the ordering contract so client code does not invent its own.

Date Ranges and Time Zones

Date filters deserve explicit boundaries. Prefer half-open ranges such as created_at >= :start AND created_at < :end instead of BETWEEN when timestamps include a time component. Store timestamps in UTC and convert for display, not for comparison. If users report missing records near midnight, check whether the application applied local time to a UTC column. An index-friendly predicate keeps the column bare on the left side; wrapping it in a function can prevent index use. Add test cases for the first millisecond of a month and the day after a range ends.

Finally, run EXPLAIN on the slowest query, add only the indexes the plan justifies, and recheck after data grows.

Make Queries Testable and Portable

Write queries with CTEs when logic has distinct stages; they name intermediate results and make review easier than deeply nested subqueries. Use parameters instead of concatenating values, and test with boundary data such as nulls, zero, and maximum dates. A small library of saved sql query examples can become a team asset. For broader references and more patterns, see codecodex.com, which collects practical programming resources and examples.