How do you find results that occurred in the past week?
To fetch entries from the last 7 days, substitute your_table
and created_at
with your table and date fields:
Quick and simple, each snippet accrues records per your SQL flavor.
Checking on time zones
Altering the time zone will change our definition of "current" day. Here's a tasty snippet that handles this:
Excluding today from the past week
Maybe you want to exclude today from your weekend planning. Here's how you'd do it:
Sunday to Saturday: Specific week boundaries
Perhaps you require records from an entire calendar week instead:
This gives you the previous Sunday to Saturday records, the regular work week.
Mitigating performance & leveraging indexes
For huge datasets, indexes are like Google Maps for your database. Here's how you would create an index on PostgreSQL for better performance:
Adapt your query to lean on the computed column for filtering.
Translating to different SQL dialects
SQL Server and SQLite handle dates slightly differently than PostgreSQL and MySQL. Here's the translation:
Improving readability: CTEs
Common Table Expressions (CTEs) are like a temporary post-it note. They help to enhance the readability of your SQL queries:
Was this article helpful?