Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get month name from number in PostgreSQL

Tags:

I have a table with a column month(integer). In this column I store values like 1, 2, .. 12.
But I have to show the month name.

Ex: If the value is 1 I need to display jan.

like image 633
user007 Avatar asked Feb 01 '12 10:02

user007


People also ask

How to get month number from month name in PostgreSQL?

In PostgreSQL, if you already have a month name, but you want to convert that name to the month number, you can do this with the EXTRACT() function.

How do I sort by month name in PostgreSQL?

How do I sort by month name in PostgreSQL? The TO_DATE(birthday_month, 'Month') function converts a full month name to a date in the ' 0001-MM-01 ' format. For example, you get ' 0001-12-01 ' for December. You can now use the EXTRACT(MONTH FROM date) function to extract the month from this date value.

How do I cast an expression in PostgreSQL?

CAST ( expression AS target_type ); where: The expression can be a constant or a table column or any expression that finally resolves to a value, The target_type is the final datatype to which you want to convert the above expression to.

What is To_date in PostgreSQL?

The TO_DATE function in PostgreSQL is used to converting strings into dates. Its syntax is TO_DATE(text, text) and the return type is date. The TO_TIMESTAMP function converts string data into timestamps with timezone. Its syntax is to_timestamp(text, text) .


1 Answers

Basically what @small_duck already posted, but a couple of improvements:

SELECT to_char(to_timestamp (4::text, 'MM'), 'TMmon') 
  • A plain cast to text 4::text is enough, no need for to_char(..).

  • Question asks for lower case "jan", there is a template pattern for that: mon.

  • If you want to localize the output, prefix the template with the modifier TM.

like image 190
Erwin Brandstetter Avatar answered Sep 28 '22 01:09

Erwin Brandstetter