Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally select a column in postgres SQL

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

like image 493
DigitalDisaster Avatar asked Dec 28 '16 16:12

DigitalDisaster


People also ask

How do I SELECT a specific column in PostgreSQL?

PostgreSQL SELECT statement syntax If you specify a list of columns, you need to place a comma ( , ) between two columns to separate them. If you want to select data from all the columns of the table, you can use an asterisk ( * ) shorthand instead of specifying all the column names.

How do I use coalesce in PostgreSQL?

In PostgreSQL, the COALESCE function returns the first non-null argument. It is generally used with the SELECT statement to handle null values effectively. Syntax: COALESCE (argument_1, argument_2, …); The COALESCE function accepts an unlimited number of arguments.

What is Nullif in PostgreSQL?

NULLIF in postgreSQL is an in-built conditional function that takes two arguments and returns null if two arguments are equal. Otherwise, it returns the first argument. The function returns NULL if either of the arguments is NULL .

Can you use if statements in PostgreSQL?

PostgreSQL has an IF statement executes `statements` if a condition is true. If the condition evaluates to false, the control is passed to the next statement after the END IF part.


1 Answers

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.

like image 129
Gordon Linoff Avatar answered Sep 19 '22 08:09

Gordon Linoff