Search code examples
sqlpostgresqlcrosstab

How to convert Rows to Columns in postgresql query


I have a simple query output of two rows and single column

Virginia
Texas

I want the output as

Virginia   |  Texas

I just tried it as two subqueries in column list.

select 
(select state from table where code='VA') as state1
(select state from table where code='TX') as state2
from tablename

Is there better way to get the result


Solution

  • Are you looking for string aggregation?

    select string_agg(state, ' | ' order by code desc)
    from table
    where code in ('VA', 'TX')
    

    You can use conditional aggregation:

    select max(state) filter (where code = 'VA'),
           max(state) filter (where code = 'TX')       
    from t
    where code in ('VA', 'TX')