In SQL, the WHERE clause is used to filter records from a database table that satisfy a specific condition. It is used in SELECT, UPDATE, DELETE, and other SQL statements to define the criteria that must be met for rows to be included in the result set or operation.
Basic Syntax
Components:
column1, column2, ...: The columns you want to retrieve.table_name: The name of the table you're querying.condition: The condition that must be met to filter the records.
Example 1: Basic WHERE Clause
This query retrieves all records from the Employees table where the Age is greater than 30.
Example 2: Using AND and OR Operators
You can combine multiple conditions using the AND and OR operators.
This query will retrieve records where the employee is older than 30 and works in the 'HR' department.
This query will retrieve records where either the employee is older than 30 or works in the 'HR' department.
Example 3: Using IN Operator
The IN operator allows you to specify multiple values in the WHERE clause.
This query will retrieve employees who work in either the HR, Finance, or IT department.
Example 4: Using BETWEEN Operator
The BETWEEN operator is used to filter records within a range.
This query will return employees whose age is between 25 and 35 (inclusive).
Example 5: Using LIKE for Pattern Matching
The LIKE operator is used for pattern matching with wildcards.
This will return employees whose names start with the letter 'A'. The % symbol is a wildcard that matches zero or more characters.
This will return employees whose names end with 'son'.
Example 6: Using IS NULL and IS NOT NULL
To check if a column has NULL values, you can use IS NULL or IS NOT NULL.
This query retrieves employees who do not have a manager (i.e., ManagerID is NULL).
This query retrieves employees who have a manager (ManagerID is not NULL).
Example 7: Using Comparison Operators
You can use comparison operators like =, >, <, >=, <=, !=, or <> to define conditions.
This query retrieves employees who have a salary greater than 50,000.
Example 8: Using Subqueries in the WHERE Clause
A subquery can be used in the WHERE clause to filter results based on the result of another query.
This query retrieves employees who work in the 'HR' department, where the department ID is determined by a subquery.
Conclusion
The WHERE clause is a powerful tool in SQL for filtering records based on specific conditions. It can be used with various operators like =, >, LIKE, IN, BETWEEN, and more, to refine your query results.
No comments:
Post a Comment