There are many things you can do to define a query in SQL. One thing you can do to a WHERE clause is check to see if a row exists with the matching parameters in the database. We do this with the EXISTS operator.
The syntax is as follows:
SELECT <Column>)FromTable1> FROM <Table 1 Name> WHERE EXISTS (SELECT <Column> FROM <Table 2 Name> WHERE <Table 2 Primary Key> = <Table 1 Primary Key> AND <Another Column From Table 2> = <someConstraint>);
SQL’s EXISTS condition returns the column names originally selected on the rows where the EXISTS subquery in parentheses is true. In this example from W3Schools, we select a supplier name from an outer query that returns true when the subquery passes the EXISTS clause.
SELECT SupplierName FROM Suppliers WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price < 20);
SQL EXISTS essentially acts as a type of filter where the only data returned are the columns we select from the first table. Try this and other SQL operators and query statements in the sandbox environment on W3Schools. It’ll definitely help you to level up your query writing skills!
- Career Karma matches you with top tech bootcamps
- Get exclusive scholarships and prep courses
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.