Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialwafic fahme
3,309 PointsHow to alias a subquery of 4 tables
Hi, what if I have 4 tables that I union that are a subqeury and I want to alias them to refer to the 4 tables as one single table in the select and where clause, is it possible?
3 Answers
Steven Parker
231,248 PointsSure, you can do this.
As long as your subquery is being used instead of a table in a FROM or JOIN, you can apply a table alias to it.
If the multiple tables are contained in a subquery it will still be treated as one table to the main query. You probably don't need an alias at all, since there will be just one source and no ambiguities:
SELECT *
FROM (SELECT * FROM table1
UNION
SELECT * FROM table2
UNION
SELECT * FROM table3
UNION
SELECT * FROM table4)
WHERE somecolumn = "somevalue"
Of course, depending on the table structures and purpose of the main query you may need to make the SELECT
statements more specific.
wafic fahme
3,309 PointsThank you Steven for your help. Can you please share how the query structure might look like because I am always getting issues with sub-queries when there are more than 2 tables to join. Thank you,
wafic fahme
3,309 PointsYes I meant Union, thank you very much