Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic column in SELECT statement postgres

Tags:

People also ask

How to write dynamic query in PostgreSQL?

EXECUTE ... USING only works in PL/PgSQL - ie within functions or DO blocks written in the PL/PgSQL language. It does not work in plain SQL; the EXECUTE in plain SQL is completely different, for executing prepared statements. You cannot use dynamic SQL directly in PostgreSQL's SQL dialect.

How to use EXECUTE IMMEDIATE in PostgreSQL?

PostgreSQL UsageExecute a SQL SELECT query with the table name as a dynamic variable using bind variables. This query returns the number of employees under a manager with a specific ID. Run a DML command with no variables and then with variables. %s formats the argument value as a simple string.


I am quite new to the postgresql.

what is the best way to achieve this?

SELECT get_columns() 
  FROM table_name;

get_columns() will provide the column names for the query. I saw people advising to use EXECUTE statement but I couldn't got that working.

Lets say there is table Test with columns a,b,c and I want to run

SELECT a,b FROM Test;
SELECT a,c FROM Test;

with column names generated dynamically.