WHERE
In this section, you will learn how to use the WHERE clauses to filter rows returned by a SELECT query with a specified condition.
Overview
The WHERE clause returns a specific value from a table or multiple tables based on specified conditions. It will filter out records you do not want to be included and only returns the exact result when the condition is fulfilled.
Syntax
The basic syntax of the WHERE clause is as follows −
Let’s explore the above syntax:
- SELECT column1, column2, ... defines the columns where the records will be displayed.
- FROM table_name sets the table name where the records will be taken from.
- WHERE [condition]specifies the search condition using comparison or logical operators (e.g., >, =, LIKE)
💡 It starts with the FROM clause -> then it executes the WHERE condition -> after that, it will SELECT the specified columns.
Examples
Let’s assume that we have a table salary with records as follows:
It will create a table as shown below:
#Case 1: WHERE clause with = Operator
Here we will be using the “equal” operator to look up the employee who works in the Marketing department:
The above command will create the following result:
⚠️ Oops, watch out! The value defined in the WHERE clause’s condition is case-sensitive, so ensure that you specify the correct and precise value.
#Case 2: WHERE clause with != Operator
Here we will be using the “not equal” operator to look up the employee who doesn’t live in Texas:
ℹ️ We can use the <> operator for another “not equal” operator.
The above query will give the following result:
⚠️ The value defined in the WHERE clause’s condition is case-sensitive. If you set ‘texas,’ it will return all records from the salary table.
#Case 3: WHERE clause with > Operator
Here we will be using the “greater than” operator to figure out who has a salary above 20000:
ℹ️ We can use the < operator for a “less than” condition.
The output will let us know that Parker has a salary greater than 20000:
#Case 4: WHERE clause with <= Operator
Here we will be using the “less than or equal to” operator to see who has a salary less than or equal to 15000:
ℹ️ We can use the >= operator for a “greater than or equal to” condition.
The output will let us know that Brandon has a salary equal to 15000 and Lisa has a salary of less than 15000:
#Case 5: WHERE clause with LIKE Operator
Here we will use the “like” operator to retrieve the employee whose first name starts with Br.
ℹ️ Do the reverse to get the result based on the last string, %string.
We will get an output where the above query fetches Brandon & Bradley.
#Case 6: WHERE clause with IS NULL Operator
Here we will use the “is null” operator to search for the employee who doesn’t have a salary value. It will return true and display the result set if a value is NULL; otherwise, it will return false with no result set.
The above command will create the following result:
