Tuesday, December 17, 2024

SQL AND Operator

 In SQL, the AND operator is used to combine multiple conditions in a WHERE clause. When you use AND, the query will return results only if all the conditions specified are true.

Syntax:

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

How it works:

  • The AND operator ensures that only rows that satisfy every condition are included in the result.
  • If any of the conditions evaluates to false, that row is excluded.

Example:

Suppose you have a table called employees with columns employee_id, name, age, and department.

Query:

SELECT name, age, department FROM employees WHERE age > 30 AND department = 'HR';

Explanation:

  • This query retrieves the names, ages, and departments of employees who are older than 30 and who belong to the HR department.
  • Both conditions must be true for a row to be returned.

Multiple Conditions:

You can use the AND operator to combine more than two conditions.

Example:

SELECT name, age, department FROM employees WHERE age > 25 AND department = 'Finance' AND employee_id < 1000;

This query returns the names, ages, and departments of employees who are:

  • Older than 25
  • In the Finance department
  • Have an employee_id less than 1000

Combining AND with OR:

You can also combine AND with the OR operator for more complex queries. When doing so, it’s important to use parentheses to control the logic of the conditions.

Example:

SELECT name, age, department FROM employees WHERE (age > 25 AND department = 'Finance') OR department = 'HR';

This query retrieves employees who either:

  • Are older than 25 and work in Finance, or
  • Work in the HR department (regardless of age).

Key Points:

  • AND conditions are evaluated from left to right, and all conditions must be true for the result to be included.
  • Using AND makes your queries more restrictive, narrowing down the results based on multiple conditions.

No comments:

Post a Comment