February 25th, 2009

INTERSECT

Posted by admin in M. UNIONs

An INTERSECT operator combines the results of two or more selects, giving all the rows that match between the selects.
While UNION acts like a logical OR between selects, an INTERSECT acts like a logical AND between selects.

                                                       INTERSECT syntax:

                                                      SELECT statement_1
                                                 INTERSECT [ALL | DISTINCT]
                                                      SELECT statement_2
                                                 INTERSECT [ALL | DISTINCT]
                                                      SELECT statement_3 …

INTERSECT … sets which sets will be combined into one result set.
                      Duplicate rows and nulls are excluded by default.

ALL ……………. means that duplicate rows are not to be excluded.

DISTINCT …… means duplicate rows and nulls are to be excluded.
                       If neither ALL or DISTINCT are specified, then DISTINCT is the default.

> The multiple selects must have the same number of columns (column names, functions, or arithmetic expressions).

> The order of columns must match in data type or be convertible to the same data type.

> If the name in a column is the same in all selects, then this name is used in the result. If this is not true, then most RDBMS systems take the name from the first select. If you want to create a different column name, use an AS clause in the first select for a column alias.

> ORDER BY can only be used in the last select, but it is applied to the entire result table.

> GROUP BY and HAVING can be used in each select statement, but do not apply to the final result table.

> DB2, Oracle, PostgreSQL, and SQL Server 2005 support INTERSECT and INTERSECT ALL.

> Access, and MySQL do not support INTERSECT and INTERSECT ALL.

Leave a reply

:mrgreen: :neutral: :twisted: :shock: :smile: :???: :cool: :evil: :grin: :oops: :razz: :roll: :wink: :cry: :eek: :lol: :mad: :sad: