How can I select only those columns whose name matches a regular expression in PostgreSQL?
For example, how do I select only the columns whose name begins with 'A' in the following table, without explicitly enumerating them in the select list?
id A1 A2 A3 A4 A5 B
1 a b c d e f
2 g h i j k l
To list down all tables columns on a specific table in the a PostgreSQL database using psql command-line, you can use \dS your_table_name.
The % operator lets you compare against elements of an array, so you can match against any part of the name.
The Regular Expressions in PostgreSQL are implemented using the TILDE (~) operator and uses '. *” as a wildcard operator. As you can see in the figure above, we have used Regular Expression in PostgreSQL using the TILDE (~) operator and the wildcard '.
There are three separate approaches to pattern matching provided by PostgreSQL: the traditional SQL LIKE operator, the more recent SIMILAR TO operator (added in SQL:1999), and POSIX -style regular expressions.
You will need to write a dynamic sql('select '||colname||' from (yourtable)') to accomplish this and dynamic sql should have supplied column names from the following sql:
select column_name from information_schema.columns where table_name=(your table) and column_name like 'a%';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With