SQL Exists

The EXISTS clause in SQL is used to check whether a subquery returns any rows. It’s often employed in situations where you want to verify the existence of data that meets certain conditions in related tables.

SQL Exists Syntax

SELECT column_name(s)
FROM table_name
WHERE EXISTS (subquery);



SQL Exists Check Patients with Medical Records Example

This query retrieves the first and last names of patients who have at least one record in the MedicalRecords table. The subquery checks if there are matching patient_id values in the MedicalRecords table.

SELECT p.first_name, p.last_name
FROM Patients p
WHERE EXISTS (
  SELECT 1
  FROM MedicalRecords mr
  WHERE p.patient_id = mr.patient_id
);




SQL Exists Check Doctors Appointments Example

This query returns the first and last names of doctors who have at least one appointment.

SELECT d.first_name, d.last_name
FROM Doctors d
WHERE EXISTS (
  SELECT 1
  FROM Appointments a
  WHERE d.doctor_id = a.doctor_id
);




SQL Exists Visual Diagram



SQL Exists Labs

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top