Wednesday, December 18, 2024

SQL IN Keyword

 The IN keyword in SQL is used to filter the results of a query based on whether a column's value matches any value within a specified list of values. It can be used with SELECT, UPDATE, DELETE, and other SQL statements.

Syntax:

SELECT column1, column2, ...
FROM table_name
WHERE column_name IN (value1, value2, value3, ...);

Example:

  1. Basic usage: To select rows where a column's value matches one of several options:

    SELECT * FROM employees
    WHERE department IN ('HR', 'IT', 'Sales');
    

    This will return all employees whose department is either 'HR', 'IT', or 'Sales'.

  2. Using NOT IN: To exclude certain values:

    SELECT * FROM employees
    WHERE department NOT IN ('HR', 'IT');
    

    This will return all employees whose department is not 'HR' or 'IT'.

  3. Using with subqueries: The IN keyword can also be used with a subquery to match values from the result of another query:

    SELECT * FROM employees
    WHERE department IN (SELECT department FROM departments WHERE location = 'New York');
    

    This will return all employees whose department is in New York.

Notes:

  • The IN operator is equivalent to multiple OR conditions.
    SELECT * FROM employees
    WHERE department = 'HR' OR department = 'IT' OR department = 'Sales';
    
  • It can work with numeric, string, and date types.

No comments:

Post a Comment