Search code examples
sqlpostgresqlnested-select

Selecting subset of columns in table based on their names using SQL


I have a table in Postgres DB which has a lot of columns such as "id, name, a01, a02, a03, ..., a20, b, c, d, e, f". I want to check whether any of these 'aXX' columns has value 'Y'. I know the trivial way which is:

SELECT name FROM table T 
WHERE T.a01 = Y OR T.a02 = Y OR ... OR T.a20 = Y

I was wondering if there is any way to use a loop or nested select query based on these column names since they have a pattern, instead of hard-coding them individually in WHERE?

Thanks in advance.


Solution

  • Imposible in SQL but...

    You can do it in PostgreSQL

    If you only want the id, the field name (key) and the value you can write:

    select d.id, e.key, e.value
      from the_data d, jsonb_each_text(to_jsonb(d.*)) e
      where value::integer = -1;
    

    If you want the row you can:

    select * 
      from the_data
      where id in (
        select d.id
          from the_data d, jsonb_each_text(to_jsonb(d.*))
          where value::integer = -1
      );
    

    See the running example in: http://rextester.com/CRGXPS45970

    EDITED

    You can filter fields or what you want. For example:

    select d.id, e.key, e.value
      from the_data d, jsonb_each_text(to_jsonb(d.*)) e
      where value::integer = -1 and key like 'a%';
    
    select * 
      from the_data
      where id in (
        select d.id
          from the_data d, jsonb_each_text(to_jsonb(d.*))
          where value::integer = -1 and key like 'a%'
      );
    

    You can see it here: http://rextester.com/EESKX21438