The Wayback Machine - https://web.archive.org/web/20240922025221/https://www.geeksforgeeks.org/difference-between-anti-join-and-semi-join/
Open In App

Difference Between Anti-Join and Semi-Join

Last Updated : 03 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In the context of SQL, Anti-join, and semi-join are two essential operations in relational databases used for querying and manipulating data. These operations focus on comparing data from two related tables, but they serve distinct purposes. In this article let us discuss these two operations in detail along with some examples.

What is SQL Join?

Join is an operation performed on the relations or tables that combine rows from two or more relations or tables based on the related columns between them.

Different kinds of joins can be applied to the relations which include:

Semi-join

Semi-join is a type of join that is applied to relations to join them based on the related columns. When semi-join is applied, it returns the rows from one table for which there are matching records in another related table.

Characteristics:

  • A Semi-join returns rows from the left table for which there are corresponding matching rows in the right table.
  • Unlike regular joins which include the matching rows from both tables, a semi-join only includes columns from the left table in the result.

Syntax:

using `EXISTS`:

SELECT column1, column2, …FROM table1

WHERE EXISTS (SELECT 1 FROM table2 WHERE table1.column = table2.column);

using `IN`:

SELECT column1, column2, …FROM table1WHERE column IN (SELECT column FROM table2);

Example:

Let us consider two relations namely “Customers” and “Orders“. The Customers table contains the list of customer’s details along with their ID and name. The Orders table contains the details of the orders placed by the customers along with the customer ID, Order Id, and the name of the order placed by the customer.

Creating Customers Table:

CREATE TABLE Customers (
Customer_ID VARCHAR(20) PRIMARY KEY,
Customer_Name VARCHAR(20)
);

Inserting into Customers Table:

INSERT INTO Customers (Customer_ID, Customer_Name) VALUES ('01', 'Alice');
INSERT INTO Customers (Customer_ID, Customer_Name) VALUES ('02', 'Bob');
INSERT INTO Customers (Customer_ID, Customer_Name) VALUES ('03', 'Charlie');
INSERT INTO Customers (Customer_ID, Customer_Name) VALUES ('04', 'David');

Customers table:

Customer_ID

Customer_Name

01

Alice

02

Bob

03

Charlie

04

David

Creating Orders Table:

CREATE TABLE Orders (
Customer_ID VARCHAR(20),
Order_ID VARCHAR(20) PRIMARY KEY,
Order_Name VARCHAR(20)
);

Inserting into Orders Table:

INSERT INTO Orders (Customer_ID, Order_ID, Order_Name) VALUES ('02', '101', 'Stationery');
INSERT INTO Orders (Customer_ID, Order_ID, Order_Name) VALUES ('01', '102', 'Pens');
INSERT INTO Orders (Customer_ID, Order_ID, Order_Name) VALUES ('04', '103', 'Books');

Orders Table

Customer_ID

Order_ID

Order_Name

02

101

Stationery

01

102

Books

04

103

Pens

Query for Semi-Join:

SELECT Customers.Customer_ID, Customers.Customer_Name
FROM Customers
WHERE EXISTS (
SELECT 1
FROM Orders
WHERE Customers.Customer_ID = Orders.Customer_ID
);

Output:

Customer_ID

Customer_Name

01

Alice

02

Bob

04

David

Anti-Join

Anti-join or Anti-semi-join is a type of join that is applied to relations to join them based on the related columns. When anti-join is applied, it returns the rows from one table for which there are no matching records in another related table.

Characteristics:

  • It is Exactly the opposite to semi-join.
  • An Anti-join returns rows from the left table for which there are no corresponding matching rows in the right table

Syntax:

SELECT column1, column2,…FROM table1

LEFT JOIN table2 ON table1.column_name = table2.column_name

WHERE table2.column_name IS NULL;

Example:

Let us consider the above example only which has Customers and Orders tables.

Query for Anti-Join

SELECT Customers.*
FROM Customers
LEFT JOIN Orders
ON Customers.Customer_ID = Orders.Customer_ID
WHERE Orders.Customer_ID IS NULL;

Output:

Customer_ID

Customer_Name

03

Charlie

Difference Between Anti-Join and Semi-Join

Semi-join

Anti-Join

The purpose is to retrieve the records from the left table for which there are corresponding matching records in the right table.

The purpose is to retrieve the records from the left table for which there are corresponding matching records in the right table.

The result includes the matching records from both tables.

The result excludes the matching records from both tables

It uses INNER JOIN, EXISTS subquery, or IN operator

It uses the LEFT JOIN or NOT EXISTS subquery.

It is used to find the common elements between two sets.

It is used to identify the elements that are unique to one set and not present in another.

Example: Selecting customers who placed orders.

Example: Selecting customers who haven’t placed any orders.

Conclusion

Anti-join filters out rows based on the absence of matches in another table, while semi-join filters rows based on the existence of related records but only returns columns from the first table. Understanding the differences between these two operations is crucial for effective data analysis and reporting in relational databases.

FAQs

1. What is the key difference between Anti-Join and Semi-Join ?

Semi-Joins returns rows from left table with a match on the right table whereas an Anti-join returns rows from left table with no match on right table.

2. When you should use an Anti-Join ?

Use an Anti-Join when you need to exclude rows from the left table that have a corresponding entry in the right table. For example, finding items in one table that do not exist in another table.

3. When you should use a Semi-Join ?

Use a Semi-Join when you need to filter rows in the left table by checking if they have corresponding matches in the right table, without retrieving data from the right table.

4. Which is more efficient Anit-Join or Semi-join ?

In general, both can be optimized for performence also efficiency depends on the specific database engine and query structure.

5. Do Anti-Join and Semi-Join returns data from right table ?

No, both the Joins only returns data from left table. They don’t include any data from right table.



Similar Reads

SQL | Join (Cartesian Join & Self Join)
SQL| JOIN(Inner, Left, Right and Full Joins) In this article, we will discuss about the remaining two JOINS: CARTESIAN JOIN SELF JOIN Consider the two tables below: StudentCourse CARTESIAN JOIN: The CARTESIAN JOIN is also known as CROSS JOIN. In a CARTESIAN JOIN there is a join for each row of one table to every row of another table. This usually h
2 min read
Difference between Structured, Semi-structured and Unstructured data
Big Data includes huge volume, high velocity, and extensible variety of data. There are 3 types: Structured data, Semi-structured data, and Unstructured data. Structured data - Structured data is data whose elements are addressable for effective analysis. It has been organized into a formatted repository that is typically a database. It concerns al
2 min read
Difference between Natural join and Inner Join in SQL
The join operation merges the two tables based on the same attribute name and their datatypes are known as Natural join Unlike INNER JOIN, which requires you to specify the columns and conditions for the join explicitly. In this article, we will also see the differences between them. Let's start with Natural Join. Example: If you have two tables "S
3 min read
Difference between Natural join and Cross join in SQL
1. Natural Join : Natural Join joins two tables based on same attribute name and datatypes. The resulting table will contain all the attributes of both the tables but only one copy of each common column. Example: Consider the two tables given below: Student Table Marks Table Consider the given query SELECT * FROM Student S NATURAL JOIN Marks M; Out
2 min read
Difference between Nested Loop join and Sort Merge Join
1. Nested Loop Join : Nested Loop Join is the simplest join algorithm which usually has better performance than all other types of joins due to a lesser number of comparisons involved in it. Each row in the outer table is compared to each row in the inner table. The Nested Loop Join algorithm for 2 relations R and S : For each record x of R read in
3 min read
Difference between Hash Join and Sort Merge Join
1. Hash Join : It is also known as "go-to-guy" in case of join operators. This means that in case no other join is preferred (maybe due to no sorting or indexing etc), then, Hash join is used. Hash join is best algorithm when large, unsorted, and non-indexed data (residing in tables) is to be joined. Hash join algorithm consists of probe phase and
3 min read
Difference Between Left Join and Right Join
Database management system or DBMS is the application software that allows us with its feature to store and manage the data which is collected from different types of sources. Now these sources can be from social media, user feedback, real-time generated data, etc. Database Management System follows the standardized model, which is a relational mod
5 min read
Difference Between Right Join and Right Outer Join
Joins in a Database (SQL) are mostly used for combining data or the rows of two or more table records that are based on the same or common attribute. There are various types of Joins like Right Join, Left Join, Full Join, etc. Each join has its own syntax and data-returning capability. In this article, we will see the information about Right Join a
4 min read
Difference between Inner Join and Outer Join in SQL
JOINS in SQL are fundamental operations used to combine data from multiple tables based on related columns. They are essential for querying data that is distributed across different tables, allowing you to retrieve and present it as a single or similar result set. In this article, We will learn about Inner Join vs Outer Join in SQL in detail. What
5 min read
Difference Between “INNER JOIN” and “OUTER JOIN”
Joins in SQL are essential tools that allow us to combine rows from multiple tables based on specific conditions, often involving a relation between columns in those tables. These joins help in pulling related data together in a meaningful way. Among the most commonly used joins are INNER JOIN and OUTER JOIN. In this article, We will learn about th
5 min read
Difference Between Nested Loop Join and Hash Join
These join operations are very important in the optimization of SQL operations particularly in relation to database management systems. Mostly where clause conditions can be transformed to Nested Loop Join and Hash Join, the two main methods of joining two or more data tables based on the same attribute. Nested Loop Join is actually a simple approa
7 min read
Difference Between Left Join and Left Outer Join
In SQL language, different joins are used to assemble rows from two or more tables from the related column. The terms "Left Join" and "Left Outer Join" are used interchangeably in SQL but they refer to the same concept. A Left Join retrieves all records from the left table (the first table in the query) and matches them with records from the right
5 min read
Large objects(LOBs) for Semi Structured and Unstructured Data
Large objects (LOBs) are a type of data type used to store semi-structured and unstructured data in a database. LOBs are typically used for storing data that is too large to fit into a traditional data type, such as text documents, images, videos, and audio files. LOBs are particularly useful for storing semi-structured and unstructured data, as th
5 min read
What is Semi-structured data?
Semi-structured data is a type of data that is not purely structured, but also not completely unstructured. It contains some level of organization or structure, but does not conform to a rigid schema or data model, and may contain elements that are not easily categorized or classified. Semi-structured data is typically characterized by the use of m
7 min read
Left join and Right join in MS SQL Server
Prerequisite – Introduction of MS SQL Server 1. Left Join : A join combines the set of two tables only. A left join is used when a user wants to extract the left table's data only. Left join not only combines the left table's rows but also the rows that match alongside the right table. Syntax - select select_list from table1 left join table2 on joi
2 min read
Self Join and Cross Join in MS SQL Server
Prerequisite - Introduction of MS SQL Server 1. Self Join : Self-join allows us to join a table itself. It is useful when a user wants to compare the data (rows) within the same table. Syntax - select select_list from T t1 [Inner|Left] Join on T t2 on join_predicate. Here T refers to the table we use for comparison and it is referred twice. To avoi
2 min read
Full join and Inner join in MS SQL Server
Full Join Full join selects all the rows from the left and right tables along with the matching rows as well. If there are no matching rows, it will be displayed as NULL. Syntax: select select_list from table1 full join table2 on join _predicate (OR) select table1.*, table2.* from table1 full join table2 on join _predicate (OR) select * from table1
2 min read
Inner Join vs Outer Join
Inner Join and Outer Join are the types of join. The inner join has the work to return the common rows between the two tables, whereas the Outer Join has the work of returning the work of the inner join in addition to the rows that are not matched.  Let's discuss both of them in detail in this article. Before moving ahead, let's discuss what is Joi
9 min read
Difference between JOIN and UNION in SQL
Pre-requisites: JOIN, UNION JOIN in SQL is used to combine data from many tables based on a matched condition between them. The data combined using the JOIN statement results in new columns. Consider the two tables: Boys Girls Example: sql> SELECT Boys.Name, Boys.Age, Girls.Address, FROM Boys INNER JOIN Girls ON Boys.Rollno = Girls.Rollno; The r
2 min read
Difference between Lossless and Lossy Join Decomposition
The process of breaking up a relation into smaller sub-relations is called Decomposition. Decomposition is required in DBMS to convert a relation into a specific normal form which further reduces redundancy, anomalies, and inconsistency in the relation. There are mainly two types of decompositions in DBMS Lossless join DecompositionLossy join Decom
5 min read
Difference Between Nested Subquery, Correlated Subquery and Join Operation
Nested subqueries, correlated subqueries, and join operations are common methods for querying data, but they all have different behaviors and serve various purposes. Joins are used to combine two or more different tables based on a common field between them. We can easily retrieve data from multiple tables using joins. Similarly, Nested and correla
8 min read
Difference between Left, Right and Full Outer Join
When working with SQL and relational databases, joins are essential tools that allow you to combine data from multiple tables based on related columns. Among the various types of joins, Left Join, Right Join, and Full Outer Join are commonly used for different scenarios. Understanding the differences between these joins is crucial for efficient dat
6 min read
Lossless Join and Dependency Preserving Decomposition
Decomposition of a relation is done when a relation in a relational model is not in appropriate normal form. Relation R is decomposed into two or more relations if decomposition is lossless join as well as dependency preserving. Lossless Join DecompositionIf we decompose a relation R into relations R1 and R2, Decomposition is lossy if R1 ⋈ R2 ⊃ RDe
4 min read
SQL Joins (Inner, Left, Right and Full Join)
SQL Join operation combines data or rows from two or more tables based on a common field between them. In this article, we will learn about Joins in SQL, covering JOIN types, syntax, and examples. SQL JOINSQL JOIN clause is used to query and access data from multiple tables by establishing logical relationships between them. It can access data from
5 min read
Join algorithms in Database
There are two algorithms to compute natural join and conditional join of two relations in database: Nested loop join, and Block nested loop join. To understand these algorithms we will assume there are two relations, relation R and relation S. Relation R has TR tuples and occupies BR blocks. Relation S has TS tuples and occupies BS blocks. We will
4 min read
What is PJNF(Project-Join Normal Form)?
Fifth normal form (5NF), is also known as project-join normal form (PJNF). It is a level of database normalization designed to reduce redundancy in relational databases. A relation is said to be in 5NF if and only if it satisfies 4NF and no join dependency exists. A relation is said to have join dependency if it can be recreated by joining multiple
2 min read
Join statement in JCL
Prerequisite - Job Control Language (JCL) In RDBMS, SQL JOIN clause is used to join tables and perform multiple operations on it. To perform operations on records in different flat files, JOINKEYS are used. With the help of JOINKEYS in SORT JCL, various join operation on matched and non-matched records can be executed based on matching fields or Ke
3 min read
SQL | UPDATE with JOIN
SQL UPDATE JOIN could be used to update one table using another table and join condition. Syntax - UPDATE tablename INNER JOIN tablename ON tablename.columnname = tablename.columnname SET tablenmae.columnnmae = tablenmae.columnname; Use multiple tables in SQL UPDATE with JOIN statement. Let us assume we have two tables - Geeks1 and Geeks2. To check
2 min read
Double-Pipelined Join
Double-pipelined join is a type of distributed query processing technique used to join two large datasets stored in a distributed environment. The two datasets are joined using a two-phase pipelined approach, which allows for faster query processing than traditional join algorithms. In this approach, each dataset is split into two separate streams,
4 min read
SQL Server FULL OUTER JOIN
Joins in SQL are used to retrieve data from multiple tables based on a related column (or common column) between them. In this article, we will learn how to use FULL OUTER JOIN, which returns all rows from both tables being joined. It combines the results of both LEFT OUTER JOIN and RIGHT OUTER JOIN. Instead of discarding a row with no match, it fi
6 min read