Can I add logic to SQL UNION?

Viewed 24

I'm not an expert at SQL at all, so I want to know is there a way to execute SQL queries with some logic without any additional functions or stored procedures. I have two tables: governor and figure. I need to union them by the column full_name and add additional column where it will say is a person a governor or no. But I have no clue how to do it. This is my initial query:

SELECT full_name FROM governor
UNION
SELECT full_name FROM figure 

Is there a way to do this only within the query?

1 Answers

Yes, people do this with unions all the time. Just select a constant and give it an appropriate alias (in the first select; aliases/column names in later selects are ignored):

SELECT full_name, 'governor' AS governor_or_figure FROM governor
UNION ALL
SELECT full_name, 'figure' FROM figure 

Just "UNION" defaults to UNION DISTINCT, which is only what is actually intended a minority of the time. Specifying "UNION ALL" usually what you want.

Related