PostgreSQL WHERE EXISTS Query

28/12/2020

PostgreSQL: Using where EXISTS clause

When any SQL query is used inside another SQL query then it is called a subquery. The complicated query can be written easily by dividing a large query into multiple subqueries. EXISTS clause is used with a subquery in a SQL statement. The output of EXISTS depends on the numbers of records returned by the subquery but does not depends on the values of the records. The result of EXISTS will be true if the associated subquery returns at least one row. How you can use EXISTS and NOT EXISTS clause in select, insert, update and delete statements are shown in this tutorial using different examples.

EXISTS Clause Syntax:

SELECT  col1, col2, col3…..
FROM  table_name1
WHERE EXISTS( SELECT 1
     FROM
     table_name2
     WHERE col1 = table_name1.col1);

Create three tables named company, items and customers and insert some data. Run the following select query to show the contents of these tables.

SELECT * from company;
SELECT * from items;
SELECT * from customers;

Example-1: Using EXISTS clause in SELECT query

(a) EXISTS

The following query will retrieve records from items table based on company table. The subquery searches all records from company table where company_id of company table is equal to company_id of items table and the value of phone field is not empty. There is one record in company table that does not have phone number and this record will be omitted from the output.

SELECT item_id, name, quantity
FROM items
WHERE EXISTS (SELECT 1
  FROM company
  WHERE items.company_id = company.company_id and company.phone<>);

Output:

The record of LG has no phone entry in company table. So it is not appeared in the output.

(b)NOT EXISTS

NOT EXISTS clause is opposite of EXISTS clause.  The following query will retrieve those records from items table when the subquery returns false.

SELECT item_id, name, quantity
FROM items
WHERE NOT EXISTS (SELECT 1
   FROM company
   WHERE items.company_id = company.company_id and company.website_url is NULL);

Output:

There is no record in company table where website_url is NULL. So the output of subquery is false for all records and all records of the items table are retrieved.

Example-2: Using EXISTS clause in INSERT query

According to the following insert query, the data will be inserted in items table when company_id of both company and customers tables are equal.

INSERT INTO items
(company_id)
SELECT company_id
FROM customers
WHERE EXISTS (sELECT 1
FROM company,customers
WHERE customers.company_id = company.company_id);

Output:

There are three entries for company_id in customers table with values are 1 and 2. So the subquery will return true for three times and three records will be inserted.

Run the select query to check the content of items table.

Example-3: Using EXISTS clause in UPDATE query

The following query will update the records of items table where company_id is 1 and the subquery returns true.

UPDATE items
SET name=‘Nokia’
WHERE company_id=1 and EXISTS (SELECT 1
FROM items
WHERE name=‘Not Assign’);

Output:

Here, the subquery will return true for three times and company_id is 1 for three records. Three records will be updated after executing the update query.

Run the select query to check the content of items table.

Example-4: Using EXISTS clause in DELETE query

The following query will delete those records of items table where company_id is 1 and the subquery returns true.

DELETE FROM items
WHERE company_id=1 and EXISTS (SELECT 1
FROM items
WHERE name=‘Not Assign’);

Output:

There are three records with value 1 of company_id and one record has name value ‘Not Assign’. So, the condition will true for three times and delete three records from items table.

Run the select query to check the content of items table.

Hope, you have get a clear idea of using EXISTS clause in SQL query after reading this tutorial.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

Setting up PostgreSQL with PostGIS on Debian GNU/Linux 10

As symbolized by the blue elephant with its disctinctive project symbol, PostgreSQL  belongs to the most stable Open Source...
29/12/2020

How to Install PostgreSQL on Debian

Debian is one of the most successful and independent linux operation system distributions and PostgreSQL is the same for...
29/12/2020

PostgreSQL to Manage JSON

One of the many data types that PostgreSQL support is JSON. Since most of the web APIs communication uses JSON payload...
29/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

SỰ KHÁC BIỆT GIỮA RESIDENTIAL PROXY VÀ PROXY DATACENTER
17/02/2024

Mua Proxy v6 US Private chạy PRE, Face, Insta, Gmail
07/01/2024

Mua shadowsocks và hướng dẫn sữ dụng trên window
05/01/2024

Tại sao Proxy Socks lại được ưa chuộng hơn Proxy HTTP?
04/01/2024

Mua thuê proxy v4 nuôi zalo chất lượng cao, kinh nghiệm tránh quét tài khoản zalo
02/01/2024