Monday, October 12, 2015

SQL Server Brain Basher of the Week #033 - Cartesian Product

SQL statements produce various types of results and forming the result is based on the way the query has been written. This week brain basher is based on types of results that SQL statement produces;

What is a Cartesian Product and how it can be produced?

There are different types of JOINs that can be used for combining tables such as INNER JOIN, LEFT OUTER JOIN, FULL OUTER JOIN. In addition to these well known JOINs, SQL Server facilitates CROSS JOIN that has only one logical query processing phase. This requires two tables as inputs for the JOIN and produces a Cartesian Product of the two tables.

Cartesian Product (referred as Cross Product and Cross Join as well) is an operator that works on two sets. This combines two records (tuples); records (tuples) from one table (relation) will all the records (tuples) from other table (relation).

There are two ways of writing CROSS JOIN with SQL Server; ANSI SQL-92 and ANSI SQL-89. There are no performance differences between these two, both works fine but ANSI SQL-92 is the most common one.

  1. USE AdventureWorks2014;  
  2. GO  
  3.   
  4. /* Producing a resultset for  
  5. product catgories for each year  
  6. */  
  7.   
  8. -- ANSI SQL-92  
  9. SELECT   
  10.  DISTINCT YEAR(OrderDate) Year  
  11.  , Name Category  
  12. FROM Sales.SalesOrderHeader  
  13. CROSS JOIN Production.ProductCategory  
  14. ORDER BY 1, 2;  
  15.   
  16. -- ANSI SQL-89  
  17. SELECT   
  18.  DISTINCT YEAR(OrderDate) Year  
  19.  , Name Category  
  20. FROM Sales.SalesOrderHeader, Production.ProductCategory  
  21. ORDER BY 1, 2;  


No comments: