2

If I have a table with column names like that:

name,
name_raw,
item,
item_raw,
message,
message_raw
...
... etc.

How can I select every column that does not end with _raw dynamically?

Is something like this:

SELECT
   [SOME REGEX LOGIC HERE]
FROM
   mytable

or similar possible?

4
  • 1
    Why on earth would you want to do that dynamically? Commented Dec 9, 2017 at 2:16
  • There are a lot of columns. I thought it would be easier and leaner to just filter them via regex, but I'm kinda new to Postgres/sql, so please tell me if this doesn't make sense. Commented Dec 9, 2017 at 2:26
  • 1
    It does not make sense. SQL != OOP. Queries should be static if possible. Commented Dec 9, 2017 at 2:27
  • 1
    If there are so many columns that you are thinking of doing something like that, then your database schema is probably wrong. Commented Dec 9, 2017 at 2:33

2 Answers 2

2

If you have so many columns that you cannot write a (static) query, you probably have to change the schema of your db.

If you cannot change the schema, here's a quick and dirty solution that utilizes postgresql's JSON capabilities. It does not return a traditional table with multiple columns, instead it returns a single column that contains json objects which contain all the columns from the original table whose name ends with _raw.

SELECT (
    SELECT json_object_agg(key,value)
    FROM json_each(to_json(t))
    WHERE key ~ 'raw$'
) FROM mytable;

The idea is convert every row from mytable to a JSON object and then use JSON functions to filter the members of the object.

Sign up to request clarification or add additional context in comments.

Comments

2

Use the information schema e.g.

SELECT column_name
FROM information_schema.columns
WHERE table_schema = 'my_schema'
AND table_name   = 'mytable'
AND NOT column_name LIKE '%\_raw'

note because the underscore itself is a query wildcard it needs to be "escaped"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.