SQL Query Sample Library & Template Builder
Explore a curated repository of production SQL query samples. Select from Common Table Expressions (CTEs), Window Functions, Multi-Table Joins, and Upsert statements across PostgreSQL, MySQL, SQL Server, and SQLite.
Writing High-Performance SQL in Relational Databases
Writing optimal SQL queries requires structuring data access patterns to leverage indexes, minimizing table scans, and avoiding unnecessary nested subqueries in hot execution paths.
1. Window Functions vs Correlated Subqueries
When calculating aggregations across partitions (such as monthly department budgets or top-selling products per category), standard ANSI SQL Window Functions (like ROW_NUMBER() OVER (...) or SUM(amount) OVER (PARTITION BY ...)) outperform self-joins and subqueries by computing values in a single sequential scan.
2. Safe Upsert Patterns
Concurrent inserts can cause primary key collision exceptions. Using native dialect upsert semantics (such as PostgreSQL's ON CONFLICT (id) DO UPDATE or SQL Server's MERGE) guarantees atomicity inside a single ACID transaction.
Frequently Asked Questions
LIMIT 20 OFFSET 40. SQL Server (T-SQL) requires standard ANSI OFFSET 40 ROWS FETCH NEXT 20 ROWS ONLY, which must be preceded by an ORDER BY clause.
RANK() skips rank numbers after a tie (e.g. 1, 2, 2, 4), while DENSE_RANK() always produces contiguous sequence numbers without gaps (e.g. 1, 2, 2, 3).
INSERT INTO ... ON CONFLICT (col) DO UPDATE SET. MySQL uses INSERT INTO ... ON DUPLICATE KEY UPDATE. SQL Server and Oracle utilize the MERGE INTO statement.