When I write SQL queries, I often find that "there is no way to do this with a single query." When this happens, I often move on to stored procedures or multitasking table functions that use temporary tables (of one type or another) and eventually simply merge the results and return the result table.
I am wondering if anyone knows, simply as a matter of theory, whether it is possible to write ANY query that returns a single result set as a single query (rather than multiple statements). Obviously, I ignore relevant points such as code readability and maintainability, perhaps even query performance / efficiency. This is more about theory - it can be done ... and don’t worry, I certainly don’t plan to start pushing myself to write a query with one expression when multitasking is better for my purpose in all cases, but it can make me think twice or a little longer about whether there is a viable way to get the result from a single query.
I think a few parameters are fine - I am thinking of a relational database (e.g. MS SQL) with tables that follow common best practices (e.g. all tables have a primary key, etc.).
Note. To win the “Accepted Answer” on this, you need to provide the final proof (link to web material or something similar.)
sql theory relational-algebra
Michael bray
source share