IN, NOT IN, and BETWEEN

Estimated reading: 2 minutes 16 views

1. Write a query to find rows where a column matches one of several values using IN.

The IN operator is used to specify multiple possible values for a column in a WHERE clause.

Example (Find employees in specific departments):

				
					SELECT name 
FROM employees 
WHERE department_id IN (1, 2, 3);

				
			

2. What is the difference between IN and NOT IN? Provide examples.

  • IN: Filters rows where a column matches any value in a specified list.
  • NOT IN: Filters rows where a column does not match any value in the list.

Examples:

  • IN (Find employees in specific departments):
				
					SELECT name 
FROM employees 
WHERE department_id IN (1, 2, 3);

				
			
  • NOT IN (Find employees not in specific departments):
				
					SELECT name 
FROM employees 
WHERE department_id NOT IN (1, 2, 3);

				
			

Note: If the NOT IN list contains NULL, the query may return unexpected results due to SQL’s handling of NULL.


3. Write a query to find rows where a value falls within a specific range using BETWEEN.

The BETWEEN operator is used to filter rows within an inclusive range of values.

Example (Find employees with salaries between 30,000 and 50,000):

				
					SELECT name, salary 
FROM employees 
WHERE salary BETWEEN 30000 AND 50000;

				
			

Key Notes:

  • BETWEEN includes both the lower and upper bounds.
  • Equivalent to salary >= 30000 AND salary <= 50000.

Leave a Comment

Share this Doc

IN, NOT IN, and BETWEEN

Or copy link

CONTENTS