WHERE clause - SQL

In SQL, the WHERE clause is used to filter rows based on specified conditions when retrieving data from a table. It allows you to specify criteria that must be met for rows to be included in the result set.

Here's the basic syntax of the SELECT statement with a WHERE clause:

Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
  • SELECT: This keyword is used to indicate that data is being retrieved from the database.
  • column1, column2, ...: These are the names of the columns that you want to retrieve data from. If you want to retrieve data from all columns, you can use the asterisk (*) wildcard.
  • FROM: This keyword specifies the table or tables from which you want to retrieve the data.
  • table_name: The name of the table from which you want to retrieve data.
  • WHERE: This keyword is used to specify conditions that must be met for the rows to be included in the result set.
  • condition: The condition that must be met for a row to be included in the result set. It can consist of comparisons, logical operators, and functions.

Example

Let's say you have a table named employees with columns employee_id, first_name, and department_id, and you want to retrieve the names of employees who belong to department 10:

Example
SELECT first_name
FROM employees
WHERE department_id = 10;

This SQL statement retrieves the first_name of employees from the employees table where the department_id is equal to 10.

You can also combine multiple conditions using logical operators such as AND, OR, and NOT within the WHERE clause to create more complex conditions.

Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2;

This statement retrieves rows where both condition1 and condition2 are true. Similarly, you can use OR to retrieve rows where either condition1 or condition2 is true, and you can use NOT to negate a condition.

Always ensure that your conditions are logically correct and accurately represent the data you want to retrieve.