The SQL WHERE clause is used to filter the results of a SELECT, UPDATE, or DELETE statement.
The WHERE clause specifies the conditions that must be met for the statement to execute.
If the conditions are not met, the statement will not be executed.
The basic syntax for the WHERE clause is as follows:
SELECT column1, column2, ... FROM table_name WHERE condition;
The WHERE clause can use various operators to compare values and filter the results. Some of the most commonly used operators include:
- = : Equal to
- <> or != : Not equal to
- > : Greater than
- < : Less than
- >= : Greater than or equal to
- <= : Less than or equal to
- BETWEEN : Between a certain range
- LIKE : Search for a pattern
- IN : To specify multiple possible values for a column
Here are some examples of how the WHERE clause can be used in different statements:
SELECT * FROM employees WHERE salary > 50000;
This statement will select all columns from the employees table where the salary is greater than 50000.
UPDATE customers SET address = 'New York' WHERE customer_id = 1;
This statement will update the address of the customer with ID = 1 to New York in the customers table.
DELETE FROM products WHERE quantity < 10;
This statement will delete all rows from the products table where the quantity is less than 10.
SELECT * FROM orders WHERE order_date BETWEEN '2022-01-01' AND '2022-12-31';
This statement will select all columns from the orders table where the order_date is between January 1st, 2022 and December 31st, 2022.
SELECT * FROM employees WHERE name LIKE '%son';
This statement will select all columns from the employees table where the name ends with son.
SELECT * FROM employees WHERE department IN ('sales', 'marketing');
This statement will select all columns from the employees table where the department is either sales or marketing.
The SQL WHERE clause is a powerful tool for filtering the results of a SQL statement. By using the various operators and conditions, you can easily retrieve the specific data you need from your database. Keep in mind that the SQL WHERE clause is optional and if you don't use it all the rows will be selected.