How to use dynamic column name in postgresql?

Member

by dana , in category: MySQL , a month ago

How to use dynamic column name in postgresql?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , a month ago

@dana 

In PostgreSQL, you can use dynamic column names by using the EXECUTE statement along with string interpolation. Here's an example of how you can use dynamic column names in a query:

1
2
3
4
5
6
7
8
DO $$
DECLARE
    column_name TEXT := 'email';
    query TEXT;
BEGIN
    query := 'SELECT ' || quote_ident(column_name) || ' FROM users;';
    EXECUTE query;
END $$;


In this example, we have a variable column_name that stores the name of the column we want to select from the table. We then interpolate that variable in the query string using quote_ident() function to properly quote the column name to prevent SQL injection attacks.


You can also use dynamic column names in other query statements like INSERT, UPDATE, and DELETE by following a similar approach using EXECUTE statement.