Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting columns whose name matches a regular expression in PostgreSQL

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
like image 364
DKS Avatar asked Feb 20 '15 22:02

DKS


People also ask

How do I get column names in PostgreSQL?

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.

How can you compare a part of name rather than entire name in PostgreSQL?

The % operator lets you compare against elements of an array, so you can match against any part of the name.

Can we use regular expression in PostgreSQL?

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 '.

What are the pattern matching operators that can be used in PostgreSQL?

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.


1 Answers

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%';

like image 160
Somnath Bandopadhyay Avatar answered Nov 15 '22 06:11

Somnath Bandopadhyay