Explain Codes LogoExplain Codes Logo

Date in mmm yyyy format in PostgreSQL

sql
date-formatting
postgresql
to_char
Nikita BarsukovbyNikita Barsukov·Dec 3, 2024
TLDR

For 'mmm yyyy' format in PostgreSQL, employ the to_char function with the 'Mon YYYY' format string:

SELECT to_char(your_date_column, 'Mon YYYY') AS formatted_date FROM your_table;

Insert your actual column and table names in places of your_date_column and your_table.

Diving into to_char

The to_char treasure trove

Beyond 'Mon YYYY', to_char opens the door to a multitude of formatting scenarios:

  • Day abbreviation: 'Dy' emits 'Sun', 'Mon', etc.
  • Full month name: 'Month' outputs 'January', 'February', etc.
  • Locale-oriented formatting: 'TMMonth' employs the translation from your locale setting.

Cautionary tales with to_char

When calling to_char, pay heed to:

  • Locale settings: They mold the output. Default settings may not render as expected in English.
  • Performance Hits: Prolific usage on large datasets could dampen query performance. Optimize with caution!

Alternatives and sidekicks

Other armors in your PostgreSQL arsenal involve:

  • date_trunc: Handy for herding dates to designated precision.
  • extract or date_part: Draw specific segments (like the year or month) from a date.
  • set DateStyle: To preset the default date representation should you frequent specific date formats.

Hands-on examples

Today's date in 'mmm yyyy' format

Need the current date and time in 'mmm yyyy'? Your magic spell is now() or its alias, CURRENT_TIMESTAMP:

-- Psst, it's also a time traveler! SELECT to_char(now(), 'Mon YYYY');

Expect a whisper in your logs like 'Apr 2023'.

A trip down memory lane

Suppose you curate a historical events database and yearn for 'mmm yyyy' event dates:

-- Hum along to the rhythm of time! SELECT event_name, to_char(event_date, 'Mon YYYY') AS formatted_event_date FROM history_archive;

Customization galore

Where dates must be formatted conditionally, draft the CASE muscle:

-- Date fashion tailored to the era! SELECT event_name, CASE WHEN era = 'medieval' THEN to_char(event_date, 'DD Mon YYYY') ELSE to_char(event_date, 'Mon YYYY') END AS formatted_event_date FROM history_archive;

Medieval dates sport the day, while others keep it low-key with the month and year.

Manipulating varied date types

Wrangling null values

When faced with'NULL dates, use COALESCE to lay down fallback values:

-- You can't hide, but you can run to a fallback! SELECT COALESCE(to_char(birth_date, 'Mon YYYY'), 'Date of birth unknown') FROM person_records;

Parsing user-supplied dates

Got user-supplied dates? Confirm they align with your target format:

-- Even your pet can interpret this date correctly! SELECT to_char(to_date('02-2023', 'MM-YYYY'), 'Mon YYYY');

Type casting and custom formats

You might be tempted to attempt a direct type cast using ::date, but remember, you cannot customize a date using direct cast, always stick with to_char for the perfect fit.