MySQL WEEKOFYEAR in Postgres - How Do You Do It?


Share this post:

Every wonder how to group by the week of the year in Postgres?  MySQL comes with the handy WEEKOFYEAR() Function.  How do you solve for the same thing in Postgres?

Let's take an example, let's say we're measuring how many hearing tests get taken per week.  Using MySQL, you'd do something like this:

SELECT
	YEAR(CONVERT_TZ(taken_at,'+00:00','-06:00')) as year,
	WEEKOFYEAR(CONVERT_TZ(taken_at,'+00:00','-06:00')) as week,
	COUNT(DISTINCT id)
FROM tests
GROUP BY 
	YEAR(CONVERT_TZ(taken_at,'+00:00','-06:00')),
	WEEKOFYEAR(CONVERT_TZ(taken_at,'+00:00','-06:00'))
ORDER BY 
	YEAR(CONVERT_TZ(taken_at,'+00:00','-06:00')) DESC,
	WEEKOFYEAR(CONVERT_TZ(taken_at,'+00:00','-06:00')) DESC

Now, let's do the same thing in Postgres, with the time zone conversion done for extra credit.

SELECT 
	DATE_PART('year',(t.created_at at time zone 'utc' at time zone 'cst')::Date) as year,
	DATE_PART('week',(t.created_at at time zone 'utc' at time zone 'cst')::Date) as week,
	COUNT(DISTINCT t.id) as tests
FROM tests t
GROUP BY 
	DATE_PART('year',(t.created_at at time zone 'utc' at time zone 'cst')::Date),
	DATE_PART('week',(t.created_at at time zone 'utc' at time zone 'cst')::Date)
ORDER BY 
	DATE_PART('year',(t.created_at at time zone 'utc' at time zone 'cst')::Date) DESC,
	DATE_PART('week',(t.created_at at time zone 'utc' at time zone 'cst')::Date)
LIMIT 100
;
	

And there you have it!  Time zone conversion and results grouped by week for both MySQL and Postgres.  Enjoy!