DEV Community

Tim
Tim

Posted on

T-SQL: How To UNION ALL Tables and Why

In some cases, we need to combine the result of two tables where data types may be similar or identical. We could combine the data in one table using INSERT syntaxes, but with UNION ALL or UNION, we can achieve the same result instead of creating a new table. In the video, SQL Basics: How To Use UNION ALL and Why we see several examples of this in action. One example we union tables with the same data type and in another example, we union two columns that have different data types.

Some questions that are answered in the video:

  • Note the tables that we're using and what values are identical based on the column names and what values differ based on the column names. We'll be using these tables throughout these videos. What is a like data type? Why does it matter in a union? What's the outcome when we union two like data types that slightly differ?
  • Compare the results of the queries when we union identical data types versus when we combine two different data types.
  • If we have a type of varchar and a type of integer, what tool could we use to combine the columns in a union?
  • What should we know about union and security?
  • While there are object oriented tools that may automatically convert data types, if we have mismatches, we should be aware of the underlying data if we use a union.

One applied example of using unions is error logs. Often we have error logs for the database, application and other possible layers. It's useful to identify when an error happened and how that error translated across layers. Unioning tables with the errors by combining the error and date can be useful when we order by the time of the error. We can often find out where the error originated and how it impacted all the layers of our application or service.

Top comments (0)