Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do text calculations using columns in SQL

I’d like to conditionally include the values from particular columns in a SQL query. To illustrate the question let me use the fictional example of returning selective data about users.

If we were to return all data we’d use a query of the form:

SELECT 
  name, email, gender 
FROM 
  users

Assume all users have entered their gender. However some have set the value of gender_public to be false and I would like to reflect this in the data the query returns.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The type of thing I’d like to do is:

SELECT 
  name, email, if(gender_public, gender, 'N/A')
FROM 
  users

Is this possible? I’m working with Postgres

>Solution :

Using CASE

This is the obvious way to go, as suggested by @a_horse_with_no_name.

Assuming gender_public is of type BOOLEAN.

SELECT name, email, CASE WHEN gender_public THEN gender ELSE 'N/A' END AS gender
FROM users;

Using lateral join

This way of doing is especially useful if you need to use the value in more than one place and want to remain consistent.

SELECT name, email, T.gender
FROM users
CROSS JOIN LATERAL (
  SELECT gender WHERE show_gender
  UNION
  SELECT 'N/A' WHERE NOT(show_gender)
) T(gender)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading