How to Select Rows that Don't Exist in Other Table in PostgreSQL?
Last Updated :
27 Feb, 2024
In PostgreSQL, there are times when we need to find records in one table that do not exist in another table. This can be useful for various data manipulation tasks and ensuring data integrity.
In this article, we will explore different approaches along with examples to achieve this using PostgreSQL. By the end, you will have a clear understanding of how to efficiently select rows that don't exist in another table which help to improve your data management skills in PostgreSQL.
How to Select Rows That Don't Exist in Other Table?
When working with databases, it is common to encounter situations where we need to compare data across tables and find records that are missing in one table but present in another.
This can be challenging, especially when dealing with large datasets. However, PostgreSQL provides several methods to solve this problem efficiently. Below are the method that is used to select rows that don't exist in another table in PostgreSQL:
- Using NOT IN Clause
- Using NOT EXISTS Clause
- Using LEFT OUTER JOIN and IS NULL
- Using EXCEPT Operator
Let's set up an Environment
To understand How to select rows that don't exist in another table in PostgreSQL we need a 2 table on which we will perform various operations and queries. Here we will consider a table called professor and hod. Here the professor consists of id, consistsname, and dept. Also, the hod consists, of id, name and dept.
CREATE TABLE professor (
id INTEGER,
name VARCHAR(50),
dept VARCHAR(50)
);
INSERT INTO professor VALUES (1, 'Anil', 'Physics');
INSERT INTO professor VALUES (2, 'Rajesh', 'Chemistry');
INSERT INTO professor VALUES (3, 'Prakash', 'Physics');
INSERT INTO professor VALUES (4, 'Pawan', 'Chemistry');
INSERT INTO professor VALUES (5, 'Suraj', 'Maths');
INSERT INTO professor VALUES (6, 'Zenith', 'Maths');
CREATE TABLE hod (
id INTEGER,
name VARCHAR(50),
dept VARCHAR(50)
);
INSERT INTO hod VALUES (1, 'Anil', 'Physics');
INSERT INTO hod VALUES (2, 'Pawan', 'Chemistry');
INSERT INTO hod VALUES (3, 'Akash', 'Maths');
After Inserting some records Our professor table looks like:
Professor table dataAfter Inserting some records Our hod table looks like:
HOD table data1. Using NOT IN Clause
A subquery is a query that uses the result of another query to get the final result. There are multiple ways through which we can use subquery to get the our output. In the below query, we first select the name of professors that are present in the hod table and then use NOT IN clause to exclude them in the outer query.
SELECT * FROM professor
WHERE name NOT IN
(
SELECT name FROM hod
);
Output:
OutputExplanation: This above query selects all records from the "professor" table where the name does not exist in the "hod" table.
2. Using NOT EXISTS Clause
In the following query, we first select only those records in the inner query that are present in both the tables by comparing the name in the WHERE clause. Later we discard these records from the professor table by utilising the NOT EXISTS clause.
SELECT * FROM professor
WHERE NOT EXISTS
(
SELECT * FROM hod
WHERE professor.name=hod.name
);
Output:
OutputExplanation: This above query selects all records from the "professor" table where there is no corresponding record in the "hod" table with the same name.
3. Using LEFT OUTER JOIN and IS NULL
The left join returns all the records in the left table whether they are matched or not. Using this, we can filter out the records for which the fields from the right table are NULL.
The following query employs the same to filter out the records for which hod.name is NULL.
SELECT professor.* FROM professor
LEFT OUTER JOIN hod
ON professor.name=hod.name
WHERE hod.name IS NULL;
Output:
OutputExplanation: The output consists of employee records from the professor table where the name does not match any name in the hod table, using a LEFT OUTER JOIN and filtering for NULL values in the hod table.
4. Using EXCEPT Operator
The EXCEPT operator is used to retrieve distinct records from one table which are not present in the other table. We can make use of except operator to retrieve the rows which are not present in the other table. The following query does the same:
SELECT * FROM professor
WHERE name in (
SELECT name FROM professor
EXCEPT
SELECT name FROM hod
);
Output:
OutputExplanation: This above query selects all records from the "professor" table where the name exists in the "professor" table but does not exist in the "hod" table.
Conclusion
Overall, the PostgreSQL offers several efficient methods to select rows that don't exist in another table, which can be important for data management and ensuring data integrity. By using the NOT IN clause, NOT EXISTS clause, LEFT OUTER JOIN and IS NULL, and the EXCEPT operator, you can effectively compare data across tables and identify missing records. These methods provide valuable tools for database administrators and developers working with PostgreSQL, allowing them to manipulate data efficiently and maintain the integrity of their databases.
Similar Reads
How to Select the Nth Row in a PostgreSQL Database Table?
In PostgreSQL, selecting specific rows is a fundamental operation frequently required for tasks such as data analysis, pagination, and reporting. The "nth" row refers to the row in a table that holds a particular position or rank, where "n" represents that specific position or ranking number. This a
5 min read
How to Select All Records from One Table That Do Not Exist in Another Table in SQL?
When working with SQL databases, a common requirement is to find records from one table that do not exist in another table. This can be achieved using various SQL techniques like LEFT JOIN, NOT IN, or NOT EXISTS. In this detailed guide, we will explain how to accomplish this using SQL queries and La
4 min read
How to Select Rows from a Table that are Not in Another Table?
In MySQL, the ability to select rows from one table that do not exist in another is crucial for comparing and managing data across multiple tables. This article explores the methods to perform such a selection, providing insights into the main concepts, syntax, and practical examples. Understanding
3 min read
How to Select Rows with no Matching Entry in Another Table in SQLite?
In database management, selecting rows from one table that does not have matching entries in another table means returning the rows that are present in one table but do not have the same entry in any other table. This scenario often arises in various data validation and analysis processes. In this a
4 min read
How to Write a Normal Select Procedure in PostgreSQL?
PostgreSQL is an open-source relational database management system with a variety of features that allow users to operate database operations and improve the speed of queries. One of these options is the ability to write stored procedures, the SQL code that logically embeds logic for a more organize
4 min read
What is Nested Select Statement in PostgreSQL?
Nested select statements, also known as subqueries which is a fundamental concept in PostgreSQL and play an important role in data retrieval and manipulation. In PostgreSQL, a powerful relational database management system, the nested select statements allow for complex queries by nesting one query
5 min read
How to Update Table Rows in PostgreSQL Using Subquery?
PostgreSQL is a general-purpose object-relational database management system and is open-source. It ensures data integrity features like constraints, transactions and foreign key support. In this article, We will understand How to update table rows in PostgreSQL using subquery using various methods,
5 min read
How to Get Multiple Counts With Single Query in PostgreSQL?
Efficient data analysis often requires counting occurrences of different categories within a dataset. PostgreSQL, a powerful relational database management system offers a feature that allows us to achieve this efficiently. In this article, we'll explore how to Get Multiple Counts With a Single Quer
3 min read
How to Select Random Row in PostgreSQL?
Selecting random rows from a table in PostgreSQL can be a valuable feature for various applications, including data analysis, content generation, and gaming scenarios. PostgreSQL offers straightforward methods to achieve this, primarily through the RANDOM() function and the ORDER BY RANDOM() clause.
4 min read
How to Select Dates Between Two Dates in PostgreSQL?
When managing a PostgreSQL database, we may often encounter scenarios where we need to filter data based on date ranges. This task is crucial for generating reports, analyzing trends, or retrieving time-sensitive information. However, querying for data within a specific date range can be a challengi
4 min read