DBMS Menu


INTERSECT in DBMS




The INTERSECT operator in a DBMS is used to combine two SELECT statements and return only the records that are common to both.

The basic syntax of the INTERSECT clause in SQL is:

Syntax
SELECT column_name(s) FROM table1
INTERSECT
SELECT column_name(s) FROM table2;

For example, if you have two tables, Orders and Deliveries, and you want to find all orders that have been delivered (assuming order_id is a common column), you could write:

Example:
SELECT order_id FROM Orders
INTERSECT
SELECT order_id FROM Deliveries;

This would return a list of order_ids that appear in both the Orders and Deliveries tables.

Here are some key points about the INTERSECT operator:

  • The number and order of columns, and the data types in both the SELECT statements should be the same.
  • It removes duplicate rows from the result set.
  • It returns records that are common to both the SELECT statement queries.

However, not all DBMSs support the INTERSECT operator. For example, MySQL does not have a built-in INTERSECT operator, you can achieve the same result using a combination of INNER JOIN, UNION, or EXISTS.

Here is an example of how to emulate INTERSECT using INNER JOIN:

Syntax
SELECT table1.id FROM table1
INNER JOIN table2 ON table1.id = table2.id;

This would also return ids that exist in both table1 and table2.


For example, if you have two tables, Orders and Deliveries, and you want to find all orders that have been delivered (assuming order_id is a common column), you could write:

Example:
SELECT o.order_id FROM Orders o
INNER JOIN 
Deliveries d ON o.order_id = d.order_id

This would return a list of order_ids that appear in both the Orders and Deliveries tables.


Next Topic :EXCEPT in DBMS