SQL
Date Functions
Database Queries
SQL Tips
Data Retrieval

Select records from NOW -1 Day

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Selecting rows from the last day is a frequent reporting and monitoring query. The core requirement is to define the time window clearly and ensure the query can use indexes instead of scanning the full table.

Most SQL engines support interval arithmetic against the current timestamp, but syntax varies slightly by dialect. The query should compare a timestamp column directly against a computed boundary value.

When time zones and daylight transitions are considered explicitly, last-day reports remain correct across regions and deployment environments.

Core Sections

Define the exact behavior contract

Most errors in these topics come from implicit assumptions about lifecycle or data shape. A strong implementation starts by writing down what must happen in success and failure paths. For UI flows, that includes which action closes a dialog and which action only shows validation feedback. For data queries and NLP pipelines, it includes window definitions, metadata retention, and deterministic preprocessing outputs.

Create one representative input and one expected output before changing the implementation. This turns debugging from guesswork into repeatable verification and helps reviewers reason about correctness quickly.

Implement a minimal, testable baseline

The best first version is small and deterministic. Keep environment-specific values explicit, isolate side effects, and avoid mixing validation, persistence, and presentation logic in one handler.

sql
1-- PostgreSQL: last 24 hours
2SELECT id, created_at, status
3FROM orders
4WHERE created_at >= NOW() - INTERVAL '1 day'
5ORDER BY created_at DESC;
6
7-- MySQL equivalent
8SELECT id, created_at, status
9FROM orders
10WHERE created_at >= NOW() - INTERVAL 1 DAY
11ORDER BY created_at DESC;

This baseline pattern is intentionally compact. If production requirements are larger, keep the same separation of concerns and move configuration to one predictable location.

Validate the full path with a smoke check

After baseline behavior works, run a short end-to-end check that covers the critical path. This catches integration mistakes quickly and shortens iteration cycles.

sql
1-- Day-boundary query in UTC for daily reporting windows
2SELECT id, created_at
3FROM events
4WHERE created_at >= DATE_TRUNC('day', NOW() AT TIME ZONE 'UTC') - INTERVAL '1 day'
5  AND created_at <  DATE_TRUNC('day', NOW() AT TIME ZONE 'UTC');
6
7-- Helpful index
8CREATE INDEX IF NOT EXISTS idx_events_created_at ON events(created_at);

Add one targeted negative-path check for the most likely production failure. Common examples include invalid input ranges, missing metadata, timezone mismatch, and unexpected callback ordering.

Make the fix robust in production

Stability comes from clear observability and explicit assumptions. Add concise logging around decision points and include identifiers needed to trace failures. Keep messages actionable so operators can diagnose issues without reading source code.

Document assumptions next to code, such as time boundary semantics, localization behavior, thread affinity, or expected callback count. Explicit assumptions reduce maintenance risk and improve onboarding speed for new contributors.

Regression and maintenance workflow

Every time you fix a user-visible bug, add a focused regression test that would fail before the fix and pass after it. This practice turns one-off debugging effort into durable reliability.

Keep helper functions reusable and small. Over time, consistent helper boundaries reduce duplicated logic and prevent divergence across multiple call sites.

Common Pitfalls

  • Wrapping the timestamp column in functions can prevent index usage.
  • Mixing local time and UTC in the same query logic causes off-by-hours errors.
  • Using inclusive upper and lower bounds carelessly can double-count boundary rows.
  • Assuming NOW means the same timezone across environments can break reports.
  • Running heavy last-day scans without an index leads to slow dashboards.

Summary

  • Compare timestamp columns directly to NOW minus one-day interval.
  • Prefer indexed range predicates for performance.
  • Decide whether window means rolling 24 hours or previous calendar day.
  • Use consistent timezone handling across query and storage.
  • Define boundary inclusivity explicitly to avoid duplicate counts.

Course illustration
Course illustration

All Rights Reserved.