3

One of my columns is a date type in the following format: YYYY-MM-DD. I want to extract YYYY-MM. So far, the resources I've come across show me that I can extract either year using SELECT extract(year from order_date)... but I can't figure out how to extract both the year and the month. I tried the following but it didn't work: https://www.w3schools.com/sql/func_mysql_extract.asp

2 Answers 2

6

I just want to point out that it is often convenient to leave the value as a date. If so, use date_trunc():

select date_trunc('month', order_date) as yyyymm

If you really want a string, you should accept Nick's answer.

Sign up to request clarification or add additional context in comments.

1 Comment

@Gordon Linoff would you upvote my question? Apparently, I am not allowed to ask any for questions for the time being. The hep section says that it may be due to previously asking unhelpful questions. Can you give me an upvote so I can keep participating here?
4

In PostgreSQL you can use TO_CHAR():

SELECT TO_CHAR(order_date, 'YYYY-MM')

Output (if order_date = '2020-04-06'):

2020-04

Note if your column is not already a date or timestamp you will need to cast it to a date or timestamp (e.g. order_date::date).

Demo on dbfiddle

1 Comment

That is so much better than my solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.