How is the SQL WHERE statement used?

The WHERE clause is a keyword in SQL used to filter data. It allows certain conditions to be applied to SELECT, UPDATE, or DELETE statements in order to restrict the scope of the results.

The general syntax of a WHERE statement is as follows:

Retrieve columns column1, column2, etc. from the table named table_name based on a specified condition.

In the above syntax, the SELECT statement is used to specify the columns to retrieve, the FROM clause specifies the table to retrieve data from, and the WHERE clause is used to specify filtering conditions.

The WHERE clause can utilize comparison operators (such as =, <>, >, <, >=, <=) to compare the values of columns, and use logical operators (such as AND, OR, NOT) to combine multiple conditions.

Here are some examples using the WHERE clause:

  1. Retrieve data with specific conditions.

Retrieve all employees from the database who have a salary higher than $50,000.

  1. Filter using multiple conditions.

Select all customers who are located in New York, USA.

  1. Performing a fuzzy match using wildcards.

Retrieve all records from the products table where the product name starts with ‘Apple’.

  1. Match multiple values using the IN operator.

Retrieve all orders where the customer ID is either 1, 2, or 3.

  1. Check for empty values using NULL.

Retrieve all employees whose department is not specified.

In conclusion, the WHERE clause is a crucial component in SQL, as it allows for filtering, sorting, and retrieving specific data from a database.

bannerAds