Suppose that two tables exist: users and groups.
How does one provide ‘simple search’ in which a user enters text and results contain both users and groups whose names contain the text?
The result of the search must distinguish between the two types.
The trick is to combine a
UNIONwith a literal string to determine the type of ‘object’ returned. In most (?) cases, UNION ALL will be more efficient, and should be used unless duplicates are required in the sub-queries. The following pattern should suffice:NOTE: I’ve added the answer myself, because I came across this problem yesterday, couldn’t find a good solution, and used this method. If someone has a better approach, please feel free to add it.