Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

84
Views
PostgreSQL return result set of select as json

I would like to have psql return result as json with the following format example:

{
   "2021-10-27" : 324,
   "2021-10-26" : 14,
   "2021-10-28" : 24,
   "2021-10-30" : 4,
}

My SQL is :

SELECT DATE(user.updated_at), COUNT(*) 
  FROM users AS user
 GROUP BY DATE(user.updated_at)

How can I return the above SQL as json. I use psql version 13.

Thanks.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can use JSON_OBJECT_AGG() function after nesting your current SELECT statement such as

SELECT JSON_OBJECT_AGG( updated_at, cnt )
  FROM (
        SELECT DATE(updated_at) AS updated_at, COUNT(*) AS cnt 
          FROM users
         GROUP BY DATE(updated_at)
       ) AS u

Demo

over 4 years ago · Santiago Trujillo Report

0

SELECT
json_build_object(
    'current_date', json_agg(users.current_date),
    'current_date', json_agg(users.current_date)
) FROM users

Note: "current_date is date values into users table"

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!