How to return source table name when using a UNION?

sql

Solution

Supply table names in a column along other columns you are pulling:

SELECT
  'table1' AS tablename,
  other columns
FROM table1

UNION ALL

SELECT
  'table2' AS tablename,
  other columns
FROM table2

UNION ALL

…

Problem

If I use a UNION to select columns from 5 tables, then select a particular value from the results, how can I determine which table that value came from?

Original source