25

say I have a table like this:

    table messages
id | show_message | message
 3 |   false      | "some message"
 4 |   true       |  "another message"

I want to only select the message column if show_message column is true, but I also want to select the show message column either way. Would a subquery be suitable in the scenario? I feel like I'm overthinking this. I'm using Postgres 9.5

1 Answer 1

35

How about a simple case?

select id, show_message, (case when show_message then message end) as message
from t;

This will put a NULL value in the message column in the result set for messages that are not shown.

SQL queries return a fixed set of columns. So, this is the best you can do with a single query. If you really want a result set that sometimes has two columns and sometimes has three, then some sort of conditional logic or dynamic SQL would be needed.

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

3 Comments

returning the column as null is totally fine because I can check the value of show_message before trying to do anything with it. Never used case but it looks like exactly what will work for me. I will try it out.
This is perfect. Thank you for your insights.
For anyone who wants to dig deeper - postgresql.org/docs/9.4/functions-conditional.html

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.