in a MySQL query such as
SELECT *
FROM (
SELECT user_id
FROM favorites
WHERE user_id >1
UNION SELECT user_id
FROM favorites
WHERE user_id <9
) AS derived
is it OK not to alias the favorites tables (eg ‘friends AS f1’) I noticed that this query works as expected (ie, returns all user_ids), but I don’t know if it’s bad practice to do this. When I’ve got a few UNIONs it would make my queries less confusing if I didn’t have to keep all the aliases straight. Is there a good general rule for when to use aliases (maybe it’s ‘always use aliases when employing multiple instances of the same table’)?
You do not need to alias inside a union. Each part of the union is essentially its own query.
You only need to alias if you use the same table twice in a query or if you join to a subquery, otherwise there is no need for it (unless you want it).
You also don’t need the outer select wrapper it does nothing useful and may even slow things down.
(I’m assuming the union is just an example – your where clause could be done with just one query, and you probably want
union all.)