Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do you query something like

if parent = 0 then alias is network_id else alias is group_id

Is this possible with only queries?

share|improve this question
Do you want to show a different column alias based on a condition? – siride Dec 27 '13 at 2:12
@siride yes, display different column aliases based on specified conditions. where the data remains the same. – madziikoy Dec 27 '13 at 2:18
up vote 3 down vote accepted

It's impossible to do what you want, and if not impossible, not a good idea. The columns in a resultset belong to every row in the resultset. You can't have a different alias for each row. That wouldn't make sense. Imagine a table in a spreadsheet that had a column header for each column and for each row. How would you even notate that?

It seems, though, that you want to be able to consider some upstream column to be a network_id in some cases and a group_id in others. I won't question your schema or query design, though it is suspect. If it's reasonable, then you can easily achieve this by simply having two columns: network_id and group_id. Only fill in network_id if parent = 0, and only fill in group_id if parent is not 0, like so (using standard SQL):

CASE WHEN parent = 0 THEN alias ELSE NULL END AS network_id,
CASE WHEN parent <> 0 THEN alias ELSE NULL END AS group_id,

Your application code can use whichever column needs to be used.

share|improve this answer
Exactly what I needed. Just added an unset function with php to get rid of the null columns. – madziikoy Dec 27 '13 at 2:46

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.