CodeGym /Courses /SQL SELF /Common Mistakes When Working with Dates and Time

Common Mistakes When Working with Dates and Time

SQL SELF
Level 32 , Lesson 4
Available

Today, we’re talking about mistakes again. Because working with dates and time is like walking through a minefield: everything’s chill until you take that one wrong step.

Mistakes When Choosing Data Types

This is where all the trouble usually starts. Picking the wrong data type can totally ruin your efforts with dates and time.

Situation 1: Using DATE Instead of TIMESTAMP

When you’re logging an event that has not just a date but also a time, using only DATE can make you lose important info.

CREATE TABLE orders (
    order_id SERIAL PRIMARY KEY,
    order_date DATE -- just the date
);

With this design, you can’t tell if two orders were made in the morning or at night. Why lose the chance to sip coffee and look at those beautiful timestamps?

Situation 2: Forgot About Time Zones

If your app works with international users but you’re saving date and time using just TIMESTAMP without time zones, your data can become “homeless.” TIMESTAMPTZ fixes this for you.

CREATE TABLE events (
    event_time TIMESTAMP -- no time zone
);

No one wants to mix up an evening event in New York with a morning one in Tokyo. Use TIMESTAMPTZ!

Mistakes When Using Functions

Situation 1: Wrong Format in TO_CHAR()

Problems start if you mess up the format. For example:

SELECT TO_CHAR(NOW(), 'YYYY-DD-MM'); -- Oops, mixed up month and day

Here, instead of the usual year-month-day, you got year-day-month. This can lead to some funny (but not always pleasant) situations for your users. Always double-check your format.

Situation 2: Mistakes Using TO_DATE()

On the flip side, if you try to convert a string to a date but the format doesn’t match, PostgreSQL will throw an error.

SELECT TO_DATE('10/31/2023', 'YYYY-MM-DD'); -- Error! Format doesn’t match.

The string format has to match exactly what you specified. For example:

SELECT TO_DATE('2023-10-31', 'YYYY-MM-DD'); -- All good.

Mistakes with Time Intervals

Situation 1: Implicit Type Casting

Sometimes you might forget about type casting quirks. For example:

SELECT NOW() + '1'; -- ERROR! Not clear what '1' means.

PostgreSQL doesn’t know you want to add one day. The right way:

SELECT NOW() + INTERVAL '1 day';

Situation 2: Confusion with Subtracting Intervals

Be careful when adding or subtracting intervals:

SELECT NOW() - INTERVAL '-1 day'; -- This adds a day instead of subtracting!

Here, the double minus does the opposite of what you want. Better avoid stuff like this.

Mistakes with Rounding and Truncating Data

Situation 1: Wrong Truncation with DATE_TRUNC()

When you use DATE_TRUNC() to group data, always check if you picked the right level. For example:

SELECT DATE_TRUNC('hour', NOW()); -- Truncates to the start of the hour
SELECT DATE_TRUNC('minute', NOW()); -- Truncates to the start of the minute

If you expected one result but got another, maybe you picked the wrong level.

Situation 2: Forgetting About Time Zones with DATE_TRUNC()

If you’re working with time in different time zones, the result can be unexpected:

SELECT DATE_TRUNC('day', NOW() AT TIME ZONE 'UTC');

Make sure the time zone is set right, or you might literally get lost in time.

Unix Time: Lost Seconds

Unix time (EPOCH) is handy but tricky. The most common mistake is mixing up seconds and milliseconds.

SELECT TO_TIMESTAMP(1680000000); -- This is right (seconds).
SELECT TO_TIMESTAMP(1680000000000); -- This is wrong! Too many zeros.

Check what your timestamp is measured in so you don’t end up saving a million extra seconds.

Mistakes with Time Zones

Situation 1: Mixed Up Time Zones

When you’re working with users from different time zones, data can get mixed up. For example:

SELECT TIMESTAMP '2023-10-01 10:00:00' AT TIME ZONE 'UTC';

Make sure you know exactly what time zone your data is in.

Situation 2: Duplicating Time Zones

Saving date and time and then trying to apply time zones again is a bad idea:

SELECT TIMESTAMP '2023-10-01 10:00:00 UTC' AT TIME ZONE 'UTC'; -- Don’t do this!

This can lead to wrong calculations.

Tips to Prevent Mistakes

Pick the right data type. If you’re working with international time data, use TIMESTAMPTZ. If just the date is enough, stick with DATE.

Test your queries. Make sure the results match what you expect, especially if you’re working with time intervals, formats, or rounding.

Store time data in UTC. This is the best way to avoid time zone confusion.

Check your formats. Make sure the format in TO_CHAR() and TO_DATE() matches your data.

Use functions carefully. Read the PostgreSQL docs on date/time functions carefully to avoid nasty surprises.

Working with time data can be tricky, but with the right approach and attention to detail, you’ll keep things running smooth. Dates and time are a big deal in your apps, and forgetting about them is as risky as forgetting to set your Monday morning alarm!

2
Task
SQL SELF, level 32, lesson 4
Locked
Working with Time Intervals
Working with Time Intervals
1
Survey/quiz
Working with Time Zones, level 32, lesson 4
Unavailable
Working with Time Zones
Working with Time Zones
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION