Date/Time & String Functions in SQL
Parse dates, truncate periods, and clean strings with dialect-aware SQL functions.
In plain words
Date functions cut timestamps into days, weeks and months and move between time zones; string functions clean and slice text.
Think of it like…
A calendar and a label maker: date functions round timestamps to the page you want (this week, this month) and shift between cities' clocks; string functions tidy the labels so identical things look identical.
Where you’ve seen it
Daily sales for an Indian retailer must follow IST. Orders are stored as UTC timestamps, so DATE_TRUNC('day', created_at AT TIME ZONE 'Asia/Kolkata') groups by IST day, whereas grouping by the UTC date misplaces evening orders into the next IST day and changes daily totals by about 4 percent. In the same query, LOWER(TRIM(city)) and SPLIT_PART(email, '@', 2) clean the city and extract the email domain for a segmentation feature.
Words you’ll hear
- DATE_TRUNC
- Rounds a timestamp down to the start of a period (day, week, month).
- Interval arithmetic
- Adding or subtracting durations: ts - INTERVAL '30 days'.
- AT TIME ZONE
- Converts a timestamp between time zones.
- Half-open period
- [start, next_start): no overlap or gap between consecutive periods.
Visual diagram
Theory & deep dive
Date and time functions
PostgreSQL: DATE_TRUNC('month', ts), EXTRACT(month FROM ts), ts + INTERVAL '1 month', AGE(a, b), ts AT TIME ZONE 'Asia/Kolkata'. MySQL: DATE_FORMAT, DATE_ADD(ts, INTERVAL 7 DAY), DATEDIFF, CONVERT_TZ. BigQuery: DATE_TRUNC(date, MONTH), DATE_DIFF(a, b, DAY), TIMESTAMP_ADD. Snowflake: DATE_TRUNC('month', ts), DATEADD, DATEDIFF, CONVERT_TIMEZONE. SQL Server: DATETRUNC (2022+), DATEADD, DATEDIFF. Check how timestamp vs timestamptz (or TIMESTAMP_NTZ / LTZ) behave in your warehouse before converting zones.
Always convert to the business time zone before truncating or extracting the date, use half-open ranges (>= start AND < next_start) for filters, and be careful that weeks start on Monday in some functions (ISO) and Sunday in others. Month arithmetic is calendar-aware only with intervals: adding 30 days is not adding one month. For features, extract day of week, hour, month-end flags and days to events, and compute recency as snapshot_date - last_order_date.
SELECT DATE_TRUNC('month', created_at AT TIME ZONE 'Asia/Kolkata') AS month, SUM(amount) FROM orders WHERE created_at >= TIMESTAMPTZ '2026-01-01 00:00+05:30' AND created_at < TIMESTAMPTZ '2027-01-01 00:00+05:30' GROUP BY 1 ORDER BY 1; The filter and the grouping use the same IST boundaries.
String functions and cleaning patterns
Core tools: LOWER/UPPER, TRIM (and LTRIM/RTRIM), LENGTH, SUBSTRING(s FROM 1 FOR 3), REPLACE, SPLIT_PART(email, '@', 2) (PostgreSQL, Snowflake; SUBSTRING_INDEX in MySQL), CONCAT or ||, LIKE/ILIKE for patterns, and regex functions (REGEXP_REPLACE, REGEXP_SUBSTR/REGEXP_EXTRACT). Normalise join and group keys with LOWER(TRIM(col)), remove non-digits from phone numbers with REGEXP_REPLACE(phone, '[^0-9]', '', 'g'), and extract domain or code parts into separate columns instead of repeating the expression everywhere.
Pitfalls: LIKE '%term%' can't use a normal index and is slow on huge tables; collations decide case and accent sensitivity; concatenating with NULL gives NULL (||) unless you use COALESCE or CONCAT_WS; and SUBSTRING positions are 1-based. Compare cleaned columns with their raw versions on samples to ensure you haven't merged different values. In pandas the equivalents live under .str and .dt; keep the transformation in one place (SQL view or a function) so training and serving use identical logic.
LEFT JOIN cities c ON c.city_key = LOWER(TRIM(o.city)) aligns "Pune " and "PUNE" with the lookup key "pune". Check the match rate first: COUNT(c.city_key) / COUNT(*).
How it works, step by step
Step 1 of 41. Fix the time zone
Convert stored UTC timestamps to the business zone before extracting dates or truncating.
- Store
- UTC · report in local
When to use it & trade-offs
What it is
Dates and strings need transforming before they become analysis columns. Date/time functions: truncate to a period (DATE_TRUNC('month', ts)), extract parts (EXTRACT(dow FROM ts)), add and subtract intervals (ts + INTERVAL '7 days'), measure differences, and convert time zones. String functions: LOWER, TRIM, SUBSTRING, REPLACE, SPLIT_PART, LIKE, regular expressions and concatenation (||). The syntax differs by dialect (PostgreSQL, MySQL, BigQuery, Snowflake, SQL Server), so know the equivalents of the handful you use daily.
Why it matters: Most grouping in analytics is by time (daily, weekly, monthly) and most cleaning is on text (emails, cities, codes). Time zones and period boundaries cause off-by-one-day errors that quietly misreport sales, and untrimmed or differently cased strings break joins and group-bys. Pushing these transformations into SQL keeps pipelines consistent and fast.
When to reach for it
- Daily, weekly and monthly aggregation
- Recency and calendar features
- Standardising text keys for joins
When to avoid or be careful
- Truncating UTC dates for local-time reports
- Adding 30 days when you mean one month
- Using LIKE '%x%' on very large tables
Where to transform dates and text
Strengths: Consistent; scales; reusable.
Watch out: Dialect-specific syntax.
Strengths: Rich, flexible tooling.
Watch out: Needs data in memory; logic can diverge from SQL.
Strengths: Maintainable and auditable.
Watch out: Another table to maintain.
Interview signals & numbers to know
When this topic comes up
- “Daily totals don't match finance”
- “Group by month”
- “Clean these inconsistent labels”
- Dialect differences
- Time-zone bugs
Benchmarks & rules of thumb
- ≈ 4%
- daily-total shift from using UTC instead of IST in the example
- 1-based
- SQL string positions
- half-open
- [start, next_start) ranges
Common mistakes & follow-ups
Common interview mistakes
- Grouping by the UTC date for a report the business reads in IST.
- Assuming weeks start on the same day in every function and database.
- Joining on raw city strings with trailing spaces and silently losing matches.
Likely interviewer follow-ups
- How do you group sales by local day when timestamps are stored in UTC?
- How do you compute days since last purchase in SQL?
- How would you clean a messy email or city column?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Date/Time & String Functions in SQL with data science interview Q&A and hands-on practice.