Premium
SQL Snippets.

Curated list of production-ready SQL scripts and coding solutions.

SQL

Perform Upsert (Insert or Update) in PostgreSQL

Master the upsert operation in PostgreSQL using `INSERT ... ON CONFLICT DO UPDATE` to atomically insert a new record or update an existing one if a unique conflict occurs.

View Snippet →
SQL

Group and Filter Aggregated Data with HAVING Clause

Learn to group database records and apply filters on aggregated results using `GROUP BY` and `HAVING` for powerful reporting and analytical queries.

View Snippet →
SQL

Retrieve All Records with Optional Related Data using LEFT JOIN

Use `LEFT JOIN` to retrieve all records from a primary table and their matching records from a secondary table, including primary records that have no matches.

View Snippet →
SQL

Implement Full-Text Search with Ranking in PostgreSQL

Harness PostgreSQL's powerful full-text search capabilities using `tsvector` and `tsquery` to perform efficient and ranked keyword searches on text fields.

View Snippet →
SQL

Finding Duplicate Rows Based on Specific Columns

Learn to identify and count duplicate records in your SQL database based on multiple column values, essential for data cleansing and ensuring data integrity.

View Snippet →
SQL

Generating a Series of Dates or Numbers

Learn how to programmatically generate a continuous sequence of dates or numbers in SQL, useful for time-series analysis, filling data gaps, or creating calendars.

View Snippet →
SQL

Finding Unmatched Records Using LEFT JOIN and IS NULL

Identify records in one table that do not have corresponding entries in another table, a critical technique for data integrity checks and precise reporting without `NOT EXISTS`.

View Snippet →
SQL

Upserting Records with PostgreSQL's ON CONFLICT

Efficiently insert new records or update existing ones in PostgreSQL. Utilize INSERT ... ON CONFLICT DO UPDATE to prevent duplicate key errors and maintain data integrity, a must for web apps.

View Snippet →
SQL

Retrieve the Nth Highest Value Using DENSE_RANK()

Discover how to find the Nth highest value within a dataset using SQL's DENSE_RANK() window function, providing an efficient way to rank and select specific records.

View Snippet →
SQL

Calculate Time Differences Between Consecutive Events

Learn to calculate the duration between successive events for each user or item in your SQL database using the LAG() window function, perfect for sequence analysis.

View Snippet →
SQL

Filter Parent Records Using EXISTS with a Subquery

Optimize SQL queries by filtering parent records based on the existence of related child records using the EXISTS clause. Often more efficient than IN for large datasets.

View Snippet →
SQL

Find Records Without Any Related Entries (Anti-Join with NOT EXISTS)

Identify parent records that do not have any corresponding child records in a related table using the efficient NOT EXISTS subquery pattern, useful for data cleanup.

View Snippet →