bcmcfc
bcmcfc

Reputation: 26825

How to select the name of the table in an SQL query?

I'm using a UNION and a LIMIT to select the earliest occurence of a type of table row from multiple tables. I need a record of which table satisfied the query in the result set.

Is there a way of doing something like:

SELECT id, someField, tableName FROM someUnknownTable WHERE someConditions = true

Upvotes: 4

Views: 180

Answers (1)

Peter Lang
Peter Lang

Reputation: 55594

You can select your tableName as a constant value:

Select id, someField, 'Table1' As tableName
From table1
Union
Select id, someField, 'Table2' As tableName
From table2

The second alias (As tableName) can be omitted.

Upvotes: 2

Related Questions