Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9013667
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T03:19:33+00:00 2026-06-16T03:19:33+00:00

I am using array_to_json in combination with array_agg to format certain results in PostgreSQL

  • 0

I am using array_to_json in combination with array_agg to format certain results in PostgreSQL as JSON. This works fine for queries when I want to return the default value of a query (all columns, unmodified). But I’m stumped how I could use array_agg to create a JSON object for a query where I want to modify some of the output.

Here’s an example:

CREATE TABLE temp_user ( 
   user_id  serial PRIMARY KEY,
   real_name text
);
CREATE TABLE temp_user_ip (
   user_id  integer,
   ip_address text
);
INSERT INTO temp_user (user_id, real_name) VALUES (1, 'Elise'),  (2, 'John'), (3, NULL);
INSERT INTO temp_user_ip (user_id, ip_address) VALUES (1, '10.0.0.4'),  (2, '10.0.0.7'), (3, '10.0.0.9');

The following query works fine:

# SELECT array_to_json(array_agg(temp_user)) as users from temp_user;
                                            users                                                
-----------------------------------------------------------------------------------------------------
 [{"user_id":1,"real_name":"Elise"},{"user_id":2,"real_name":"John"},{"user_id":3,"real_name":null}]

But let’s say that I don’t like the null value appearing for user 3. I’d rather see the string “User logged in from $ip” instead.

I can do this:

# SELECT user_id, (CASE WHEN real_name IS NULL THEN (select 'User logged in from ' || ip_address FROM temp_user_ip WHERE user_id = temp_user.user_id) ELSE real_name END) as name from temp_user;

And I get the following results:

 user_id |             name             
---------+------------------------------
       1 | Elise
       2 | John
       3 | User logged in from 10.0.0.9

Which is great. But I can’t figure out how to manipulate this data into JSON format like the first example.

The desired output is:

[{"user_id":1,"name":"Elise"},{"user_id":2,"name":"John"},{"user_id":3,"name":"User logged in from 10.0.0.9"}]

This doesn’t work:

# select array_to_json(array_agg ( (SELECT user_id, (CASE WHEN real_name IS NULL THEN (select 'User logged in from ' || ip_address FROM temp_user_ip WHERE user_id = temp_user.user_id) ELSE real_name END) as name from temp_user)));
ERROR:  subquery must return only one column

I can’t figure out any way to get the data into a format that array_agg accepts. I even tried creating a custom type which matched the format of temp_user and trying to array_agg calls to the type constructor, which returned the same error. The error doesn’t make sense to me – if the subquery is aggregated, then it shouldn’t matter if it returns more than one column. Any advice?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T03:19:34+00:00Added an answer on June 16, 2026 at 3:19 am

    You can separate the aggregate call from the subquery and use the row constructor for generating the compound data:

    SELECT 
        array_to_json(array_agg(row(t.*))) AS users 
    FROM 
        (
            SELECT user_id, 
                CASE 
                    WHEN real_name IS NULL 
                    THEN (
                        SELECT 'User logged in from ' || ip_address 
                        FROM temp_user_ip 
                        WHERE user_id = temp_user.user_id
                    ) ELSE real_name 
                END AS name 
            FROM temp_user
        ) t
    ;
    

    You can also check this on SQLFiddle.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Hi I want to create a JSON array. I have tried using: JSONArray jArray
I'm using Array.sample to return a random element from an array. I want to
I convert my php array to json using json_encode, Than I record this json
I have a multidimensional array converted to JSON data in this format. [[null,null,null,null,null,null],[null,null,null,1,1,null],[null,null,null,null,1,1],[null,null,null,null,null,null],[null,null,null,null,null,null]] I
I am using AJAX/JSON combination in Zend Framework. Whenever I click any link in
I want to deserialize a JSON strin like this { status:1, since:1245626956', list:{ 1:{
Hi I'm trying to access a WCF service which returns a JSON Array using
I want to sort array using Bubble Sort. I an missing a small point
I'm using PHP to json encode a massive multi-dimensional array of events, so i
I'm using a jQuery ajax json call to retrieve a 3 dimensional PHP array

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.