SQL Tutorial
|
|
|
|
| Articles Reviews Structured Query Language | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Written by Bogdan V | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Thursday, 14 September 2006 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Page 10 of 17 {mos_sb_discuss:29} It is possible to embed a SQL statement within another. When this is done on the WHERE or the HAVING statements, we have a subquery construct. The syntax is as follows:
SELECT "column_name1" [Comparison Operator] could be equality operators such as =, >, <, >=, <=. It can also be a text operator such as "LIKE." Let's use the same example as we did to illustrate SQL joins: Table Store_Information
Table Geography
and we want to use a subquery to find the sales of all stores in the West region. To do so, we use the following SQL statement:
SELECT SUM(Sales) FROM Store_Information Result:
In this example, instead of joining the two tables directly and then adding up only the sales amount for stores in the West region, we first use the subquery to find out which stores are in the West region, and then we sum up the sales amount for these stores. SQL UNION The purpose of the SQL UNION command is to combine the results of two queries together. In this respect, UNION is somewhat similar to JOIN in that they are both used to related information from multiple tables. One restriction of UNION is that all corresponding columns need to be of the same data type. Also, when using UNION, only distinct values are selected (similar to SELECT DISTINCT).
The syntax is as follows:
Say we have the following two tables, Table Store_Information
Table Internet_Sales
and we want to find out all the dates where there is a sales transaction. To do so, we use the following SQL statement:
SELECT Date FROM Store_Information Result:
Please note that if we type "SELECT DISTINCT Date" for either or both of the SQL statement, we will get the same result set. The syntax for UNION ALL is as follows:
[SQL Statement 1]
Let's use the same example as the previous section to illustrate the difference. Assume that we have the following two tables, Table Store_Information
Table Internet_Sales
and we want to find out all the dates where there is a sales transaction at a store as well as all the dates where there is a sale over the internet. To do so, we use the following SQL statement:
SELECT Date FROM Store_Information Result:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Last Updated ( Saturday, 30 June 2007 ) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| < Prev |
|---|







