2

I have this MySQL query that makes use of MONTH() and YEAR():

SELECT 
  MONTH(created_at) AS month, 
  YEAR(created_at) AS year 
FROM users 
GROUP BY MONTH(created_at), YEAR(created_at) 
ORDER BY YEAR(created_at), MONTH(created_at)

How would I modify that query to work with PostgreSQL?

2 Answers 2

4
SELECT 
  extract(MONTH from created_at) AS month, 
  extract(YEAR from created_at) AS year 
FROM users 
GROUP BY extract(MONTH from created_at), extract(YEAR from created_at) 
ORDER BY extract(MONTH from created_at), extract(YEAR from created_at) 

Here is the up-to-date manual
http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT

Btw: This is standard (ANSI) SQL that works on MySQL as well.

2

http://www.postgresql.org/docs/9.0/static/functions-datetime.html

SELECT 
  EXTRACT(MONTH FROM created_at) AS month, 
  EXTRACT(YEAR FROM created_at) AS year 
FROM users 
GROUP BY EXTRACT(MONTH FROM created_at), EXTRACT(YEAR FROM created_at)
ORDER BY EXTRACT(YEAR FROM created_at), EXTRACT(MONTH FROM created_at)

This syntax should work on PostgreSQL, Oracle and Teradata

0

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.