I have 3 different SQL queries from 3 different unrelated tables (all using LIMIT and ORDER BY).
I would like to merge and sort the results according to the "date" field (which appears in all of them)
What is the SQL to do this?
Conclusion. Combining several tables to one large table is possible in all 3 ways. As we have seen, the behavior of UNION in SQL Server and UNION in DAX within Power BI is very similar.
It is used to combine result sets of two or more SELECT statements into a single result set. Syntax: SELECT column_1, column_2 FROM table_name_1 UNION SELECT column_1, column_2 FROM table_name_2; The below rules need to be followed while using a UNION operator: Both queries must return the same number of columns.
SELECT.....
UNION ALL
SELECT....
UNION ALL
SELECT ...
ORDER BY date_field;
For the best performance, apply ORDER BY / LIMIT as late as possible, and avoid it in subqueries.
The best way is to create a new table containing the common fields from the three other tables and add an index on the common date field. The original three tables should contain a foreign key linking to the common table. With this design the query becomes simple:
SELECT *
FROM common_table
ORDER BY "date" DESC
LIMIT 100
If you also need data from the more specific tables you can use LEFT JOINs to also select that data in the same query.
If you can't change your design and performance is not an issue then you can use UNION ALL to combine the results from all three tables before sorting:
SELECT * FROM table1
UNION ALL
SELECT * FROM table2
UNION ALL
SELECT * FROM table3
ORDER BY "date" DESC
LIMIT 100
Note that the above will only work if all tables have the same structure. If you have fields that occur in one table but not in others then you should omit them from the SELECT or else return NULL for that column in the other tables. For example if:
table1
has columns a
, b
, c
and date
.table2
has columns b
, c
and date
.table3
has columns a
, c
and date
.Then use this:
SELECT a, b, c, "date"
FROM table1
UNION ALL
SELECT NULL AS a, b, c, "date"
FROM table2
UNION ALL
SELECT a, NULL as b, c, "date"
FROM table3
ORDER BY "date" DESC
LIMIT 100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With