SQL

SQL Exists

SQL Exists

This tutorial covers SQL Exists operator.

The “exists” operator is part of the logical operators.

This operator tests for the existence of row records, by specifying subqueries.

The concept of “exists” can work similarly to a statement of subqueries with the “in” operator.

For more information on operators here.

Here we use two tables. First is the table “student_info” from the previous tutorials, and the second is a table named “grade“, linked to the first table with a foreign key.

idfirstNamelastNameage
1JohnSmith21
2PatrickCasey26
3SamAdams19
4MikeGarciaNULL
5PatrickDumont21
idsubjectNamegradepassedstudentID
1HistoryC11
2PhysicsA12
3HistoryF03
4BiologyA1NULL
5BiologyE15

Exists

The “exists” logical operator tests for existence of rows.

Let’s see how it operates with two conditions. For instance, we want to check and list all student first names that have connections to the “grade” table (through the id/studentID and passed columns).

In other words, we check and list all student first names that have passed the subject.

SELECT firstName FROM student_info
WHERE EXISTS (SELECT passed FROM grade WHERE student_info.id = grade.studentID AND passed=1);
firstName
John
Patrick
Patrick

The query outputs 3 student records (one student has not passed and the other has a NULL value for studentID).

The “where” statement in the subquery checks whether students have passed the subject (passed=1). In addition, it tests if ids match in both tables.


Next: SQL Any

by AICorr Team

We are proud to offer our extensive knowledge to you, for free. The AICorr Team puts a lot of effort in researching, testing, and writing the content within the platform (aicorr.com). We hope that you learn and progress forward.