How to use dynamic column name in postgresql?

Member

by dana , in category: MySQL , a year ago

How to use dynamic column name in postgresql?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , a year 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.

Related Threads:

How to split name data in the same column in postgresql?
How to filter table with timestamp column in postgresql?
How to generate dynamic import chunk name in webpack?
How to avoid column name conflicts in cassandra?
How to get "not null column name" in mysql database?
How to add a column in PostgreSQL?