SQL
Advanced SQL patterns for PostgreSQL including CTEs, window functions, and performance optimizations.
20 snippets
Showing 20 of 20 snippets
Keyset Pagination vs Offset
Efficient keyset (cursor) pagination pattern compared to traditional OFFSET for large datasets in PostgreSQL.
UPSERT with ON CONFLICT
Insert or update rows atomically using PostgreSQL ON CONFLICT clause with partial indexes and conditions.
Recursive CTE for Tree Queries
Traverse hierarchical data like org charts and nested categories using PostgreSQL recursive common table expressions.
Full-Text Search with Ranking
PostgreSQL full-text search using tsvector, tsquery, and ts_rank with trigram similarity for fuzzy matching.
Window Functions with RANK and LAG
Use window functions to rank rows, calculate running totals, and compare with previous rows without self-joins.
JSON Aggregation and Querying
Aggregate related rows into JSON arrays and query JSONB columns with PostgreSQL native JSON operators.
Soft Delete with Filtered Indexes
Implement soft deletes using a deleted_at column with partial indexes and views for transparent querying.
Audit Log Trigger Function
Automatically record all INSERT, UPDATE, and DELETE operations into an audit log table via PostgreSQL triggers.
Materialized View with Auto-Refresh
Create and maintain materialized views for expensive aggregate queries with concurrent refresh support.
LATERAL Join for Top-N Per Group
Use LATERAL joins to efficiently fetch the top N related rows per group without window function subqueries.
Optimistic Locking with Version Column
Prevent lost updates in concurrent environments using a version column for optimistic concurrency control.
Row-Level Security Policies
Enforce data access rules at the database level with PostgreSQL Row-Level Security policies.
Table Partitioning by Range
Partition large tables by date range for faster queries and easier data lifecycle management.
Deferred Foreign Key Constraints
Defer constraint checking to transaction commit for circular references and batch operations.
SQL MERGE (Standard Upsert)
Use the SQL MERGE statement for atomic insert-or-update operations with matched/not-matched clauses.
String Aggregation with GROUP BY
Concatenate grouped values into comma-separated strings using STRING_AGG with ordering and filtering.
Generate Series Calendar Table
Create a date calendar using generate_series for gap-free time series reporting and joins.
EXISTS vs IN Subquery Patterns
Choose between EXISTS and IN subqueries for optimal performance based on data distribution.
Covering Index (INCLUDE Columns)
Create covering indexes with INCLUDE columns to satisfy queries entirely from the index.
JSONB Query and Indexing Patterns
Query, filter, and index JSONB columns in PostgreSQL for flexible document-style data storage.