0

I am trying to have a query that will be something like this:

SELECT * 
FROM some_table 
WHERE $1 = $2

I am using sqlc to generate everything needed to execute the query so I don't have the option the use a formatted string.

I was also trying to do it this way

SELECT * 
FROM some_table
WHERE 
    CASE 
        WHEN $1 = "name"
            THEN name
            ELSE id
    END = $2;

But could not find a way to make it work right

Is there any way to do something like this?

Thanks you!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • *"Is there any way to do something like this?"* -- No. You cannot use parameter placeholders for identifiers like column names etc. You can use parameter placeholders ONLY for values. A column name is NOT a value. Re-think. Re-design. – mkopriva Sep 01 '22 at 07:55
  • 1
    There is a way you can accomplish this, but it's not something I'd recommend if there is an alternative. You can move the query into a postgres function that uses [dynamic SQL](https://stackoverflow.com/a/11751557/11810946) (see the PostgreSQL 9.1 example) and then call that from your application (the table name can be passed in as a string or determined using logic within the function). – Brits Sep 01 '22 at 09:19
  • Thanks for the comments - I will try to think of a different approach! – Maya Saias Sep 01 '22 at 11:12

0 Answers0