Select info from table where row has max date
Retrieve rows from a table with the newest dates by combining an aggregated subquery with the main query:
This SQL statement gets you the latest records per id
by finding the maximum date_column
for each id
, and matching them back to your_table
.
Make it slick with window functions
SQL window functions are superb tools when working with large datasets:
This script employs ROW_NUMBER()
to assign unique identification to each row within a partition of rows with the same id
. The output is sorted by date_column
in descending order. We are after rows bearing 1
, pointing to the latest date.
Don't attract syntax errors
Do you want syntax errors? Because that's how you get syntax errors! Stay away from reserved keywords as column names (date
or check
).
Leave the extras on the shelf: Choose your columns wisely
Only pull the columns you need; including unnecessary ones will affect readability and performance:
Explicit column selection enhances maintainability and boosts query performance.
When too much is too much: Handle duplicates
Stroll in the DISTINCT
park when your table could have identical entries sharing the same date:
This lil' trick helps you wave goodbye to irksome duplicate group entries.
Performance traps are a no-no: Use JOIN
, not IN
and NOT IN
NOT IN
and IN
operations with subqueries can really drag on large tables. Maintain optimal query speed with JOIN
operations or window functions.
Unleash the power of derived tables
When you need to perform additional computations or filtering based on the subquery results, pull a rabbit out of the SQL hat and build a derived table from your main query:
Test before deploying in the wild
Use SQL Fiddle to experiment and benchmark your statements against different database systems for efficiency. No one deserves painfully slow SQL queries.
Was this article helpful?