MySql - BETWEEN, IN, LIKE, IS NULL

MySQL - BETWEEN, IN, LIKE, IS NULL

BETWEEN, IN, LIKE, IS NULL IN MySQL

MySQL provides several powerful conditional operators that are commonly used to filter and manipulate data during retrieval. Among these, BETWEEN, IN, LIKE, and IS NULL are frequently used in WHERE clauses to control query results. This document provides a detailed explanation of each, with syntax, examples, and best practices.

1. BETWEEN Operator

1.1 Overview

The BETWEEN operator is used to filter the result set within a certain range. It is inclusive, meaning it includes the boundary values specified in the query.

1.2 Syntax

SELECT column_name
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

1.3 Example with Numeric Values

SELECT * FROM employees
WHERE salary BETWEEN 30000 AND 50000;

1.4 Example with Dates

SELECT * FROM orders
WHERE order_date BETWEEN '2025-01-01' AND '2025-06-30';

1.5 Important Notes

  • BETWEEN includes both start and end values.
  • You can use it with numbers, dates, or even text.

1.6 Example with Strings

SELECT * FROM products
WHERE product_name BETWEEN 'Laptop' AND 'Smartphone';

2. IN Operator

2.1 Overview

The IN operator allows you to specify multiple values in a WHERE clause. It’s a concise alternative to using multiple OR conditions.

2.2 Syntax

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

2.3 Example

SELECT * FROM students
WHERE grade IN ('A', 'B', 'C');

2.4 Alternative Using OR

SELECT * FROM students
WHERE grade = 'A' OR grade = 'B' OR grade = 'C';

2.5 Subquery in IN Clause

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

2.6 NOT IN Clause

Use NOT IN to exclude values:

SELECT * FROM students
WHERE grade NOT IN ('F', 'D');

2.7 NULL Caution with IN

If any value in the list is NULL, the IN condition may return unexpected results if NULL comparisons are not handled.

3. LIKE Operator

3.1 Overview

The LIKE operator is used to search for a specified pattern in a column, particularly useful with text data. It supports wildcard characters:

  • %: Represents zero, one, or multiple characters.
  • _: Represents a single character.

3.2 Syntax

SELECT column_name
FROM table_name
WHERE column_name LIKE pattern;

3.3 Example - Starts With

SELECT * FROM customers
WHERE name LIKE 'A%';

This returns all customers whose names start with 'A'.

3.4 Example - Ends With

SELECT * FROM customers
WHERE name LIKE '%son';

3.5 Example - Contains

SELECT * FROM products
WHERE product_name LIKE '%phone%';

3.6 Example - Single Character Wildcard

SELECT * FROM users
WHERE username LIKE 'j_hn';

3.7 Case Sensitivity

LIKE is case-insensitive for non-binary strings unless configured otherwise.

3.8 NOT LIKE

SELECT * FROM products
WHERE product_name NOT LIKE '%laptop%';

4. IS NULL Operator

4.1 Overview

NULL represents missing or unknown values. To test for NULL values, use the IS NULL or IS NOT NULL operator.

4.2 Syntax

SELECT column_name
FROM table_name
WHERE column_name IS NULL;

4.3 Example - IS NULL

SELECT * FROM employees
WHERE manager_id IS NULL;

4.4 Example - IS NOT NULL

SELECT * FROM employees
WHERE manager_id IS NOT NULL;

4.5 Common Mistake

Never use = NULL or <> NULL; always use IS NULL or IS NOT NULL.

5. Combining Operators

5.1 BETWEEN with IN

SELECT * FROM orders
WHERE status IN ('shipped', 'delivered')
AND order_date BETWEEN '2025-01-01' AND '2025-03-31';

5.2 LIKE with IS NOT NULL

SELECT * FROM customers
WHERE email LIKE '%@gmail.com'
AND phone IS NOT NULL;

5.3 Complex Combination

SELECT * FROM employees
WHERE department_id IN (1, 2, 3)
AND hire_date BETWEEN '2020-01-01' AND '2025-01-01'
AND status IS NOT NULL
AND name LIKE 'A%';

6. Performance Tips

  • Use indexes on columns involved in BETWEEN and IN for faster lookups.
  • LIKE with wildcards at the beginning (e.g., '%term') cannot use indexes efficiently.
  • Consider using full-text search for complex LIKE patterns.
  • Use NOT IN cautiously with subqueries; if NULLs are involved, results can be misleading.

7. Real-World Use Cases

7.1 Retrieve Active Subscriptions Expiring Soon

SELECT * FROM subscriptions
WHERE status = 'active'
AND expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY);

7.2 Users With Gmail or Yahoo Addresses

SELECT * FROM users
WHERE email LIKE '%@gmail.com'
OR email LIKE '%@yahoo.com';

7.3 Orders Without Delivery Date

SELECT * FROM orders
WHERE delivery_date IS NULL;

7.4 Employees in Specific Departments

SELECT * FROM employees
WHERE department_id IN (101, 102, 103);

The BETWEEN, IN, LIKE, and IS NULL operators are essential tools for querying data in MySQL effectively. Each operator serves a specific purpose:

  • BETWEEN: Filters values within a range.
  • IN: Filters values that match one or more options.
  • LIKE: Searches patterns in string fields using wildcards.
  • IS NULL: Tests whether a column value is NULL.

Using these operators wisely can lead to concise, efficient, and expressive SQL queries. Whether you're filtering records by date ranges, pattern-matching text, checking for missing data, or working with a list of values, these operators are foundational to writing effective SQL in MySQL.

logo

MySQL

Beginner 5 Hours
MySQL - BETWEEN, IN, LIKE, IS NULL

BETWEEN, IN, LIKE, IS NULL IN MySQL

MySQL provides several powerful conditional operators that are commonly used to filter and manipulate data during retrieval. Among these, BETWEEN, IN, LIKE, and IS NULL are frequently used in WHERE clauses to control query results. This document provides a detailed explanation of each, with syntax, examples, and best practices.

1. BETWEEN Operator

1.1 Overview

The BETWEEN operator is used to filter the result set within a certain range. It is inclusive, meaning it includes the boundary values specified in the query.

1.2 Syntax

SELECT column_name FROM table_name WHERE column_name BETWEEN value1 AND value2;

1.3 Example with Numeric Values

SELECT * FROM employees WHERE salary BETWEEN 30000 AND 50000;

1.4 Example with Dates

SELECT * FROM orders WHERE order_date BETWEEN '2025-01-01' AND '2025-06-30';

1.5 Important Notes

  • BETWEEN includes both start and end values.
  • You can use it with numbers, dates, or even text.

1.6 Example with Strings

SELECT * FROM products WHERE product_name BETWEEN 'Laptop' AND 'Smartphone';

2. IN Operator

2.1 Overview

The IN operator allows you to specify multiple values in a WHERE clause. It’s a concise alternative to using multiple OR conditions.

2.2 Syntax

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

2.3 Example

SELECT * FROM students WHERE grade IN ('A', 'B', 'C');

2.4 Alternative Using OR

SELECT * FROM students WHERE grade = 'A' OR grade = 'B' OR grade = 'C';

2.5 Subquery in IN Clause

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

2.6 NOT IN Clause

Use NOT IN to exclude values:

SELECT * FROM students WHERE grade NOT IN ('F', 'D');

2.7 NULL Caution with IN

If any value in the list is NULL, the IN condition may return unexpected results if NULL comparisons are not handled.

3. LIKE Operator

3.1 Overview

The LIKE operator is used to search for a specified pattern in a column, particularly useful with text data. It supports wildcard characters:

  • %: Represents zero, one, or multiple characters.
  • _: Represents a single character.

3.2 Syntax

SELECT column_name FROM table_name WHERE column_name LIKE pattern;

3.3 Example - Starts With

SELECT * FROM customers WHERE name LIKE 'A%';

This returns all customers whose names start with 'A'.

3.4 Example - Ends With

SELECT * FROM customers WHERE name LIKE '%son';

3.5 Example - Contains

SELECT * FROM products WHERE product_name LIKE '%phone%';

3.6 Example - Single Character Wildcard

SELECT * FROM users WHERE username LIKE 'j_hn';

3.7 Case Sensitivity

LIKE is case-insensitive for non-binary strings unless configured otherwise.

3.8 NOT LIKE

SELECT * FROM products WHERE product_name NOT LIKE '%laptop%';

4. IS NULL Operator

4.1 Overview

NULL represents missing or unknown values. To test for NULL values, use the IS NULL or IS NOT NULL operator.

4.2 Syntax

SELECT column_name FROM table_name WHERE column_name IS NULL;

4.3 Example - IS NULL

SELECT * FROM employees WHERE manager_id IS NULL;

4.4 Example - IS NOT NULL

SELECT * FROM employees WHERE manager_id IS NOT NULL;

4.5 Common Mistake

Never use = NULL or <> NULL; always use IS NULL or IS NOT NULL.

5. Combining Operators

5.1 BETWEEN with IN

SELECT * FROM orders WHERE status IN ('shipped', 'delivered') AND order_date BETWEEN '2025-01-01' AND '2025-03-31';

5.2 LIKE with IS NOT NULL

SELECT * FROM customers WHERE email LIKE '%@gmail.com' AND phone IS NOT NULL;

5.3 Complex Combination

SELECT * FROM employees WHERE department_id IN (1, 2, 3) AND hire_date BETWEEN '2020-01-01' AND '2025-01-01' AND status IS NOT NULL AND name LIKE 'A%';

6. Performance Tips

  • Use indexes on columns involved in BETWEEN and IN for faster lookups.
  • LIKE with wildcards at the beginning (e.g., '%term') cannot use indexes efficiently.
  • Consider using full-text search for complex LIKE patterns.
  • Use NOT IN cautiously with subqueries; if NULLs are involved, results can be misleading.

7. Real-World Use Cases

7.1 Retrieve Active Subscriptions Expiring Soon

SELECT * FROM subscriptions WHERE status = 'active' AND expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY);

7.2 Users With Gmail or Yahoo Addresses

SELECT * FROM users WHERE email LIKE '%@gmail.com' OR email LIKE '%@yahoo.com';

7.3 Orders Without Delivery Date

SELECT * FROM orders WHERE delivery_date IS NULL;

7.4 Employees in Specific Departments

SELECT * FROM employees WHERE department_id IN (101, 102, 103);

The BETWEEN, IN, LIKE, and IS NULL operators are essential tools for querying data in MySQL effectively. Each operator serves a specific purpose:

  • BETWEEN: Filters values within a range.
  • IN: Filters values that match one or more options.
  • LIKE: Searches patterns in string fields using wildcards.
  • IS NULL: Tests whether a column value is NULL.

Using these operators wisely can lead to concise, efficient, and expressive SQL queries. Whether you're filtering records by date ranges, pattern-matching text, checking for missing data, or working with a list of values, these operators are foundational to writing effective SQL in MySQL.

Related Tutorials

Frequently Asked Questions for MySQL

Use the command: CREATE INDEX index_name ON table_name (column_name); to create an index on a MySQL table.

To install MySQL on Windows, download the installer from the official MySQL website, run the setup, and follow the installation wizard to configure the server and set up user accounts.

MySQL is an open-source relational database management system (RDBMS) that uses SQL (Structured Query Language) for managing and manipulating databases. It is widely used in web applications for its speed and reliability.

Use the command: INSERT INTO table_name (column1, column2) VALUES (value1, value2); to add records to a MySQL table.

Use the command: mysql -u username -p database_name < data.sql; to import data from a SQL file into a MySQL database.

DELETE removes records based on a condition and can be rolled back, while TRUNCATE removes all records from a table and cannot be rolled back.

A trigger is a set of SQL statements that automatically execute in response to certain events on a MySQL table, such as INSERT, UPDATE, or DELETE.

The default MySQL port is 3306, and the root password is set during installation. If not set, you may need to configure it manually.

Replication in MySQL allows data from one MySQL server (master) to be copied to one or more servers (slaves), providing data redundancy and load balancing.

 A primary key is a unique identifier for a record in a MySQL table, ensuring that no two records have the same key value.

 Use the command: SELECT column1, column2 FROM table_name; to fetch data from a MySQL table.

 Use the command: CREATE DATABASE database_name; to create a new MySQL database.

Use the command: CREATE PROCEDURE procedure_name() BEGIN SQL_statements; END; to define a stored procedure in MySQL.

Indexing in MySQL improves query performance by allowing the database to find rows more quickly. Common index types include PRIMARY KEY, UNIQUE, and FULLTEXT.

Use the command: UPDATE table_name SET column1 = value1 WHERE condition; to modify existing records in a MySQL table.

CHAR is a fixed-length string data type, while VARCHAR is variable-length. CHAR is faster for fixed-size data, whereas VARCHAR saves space for variable-length data.

MyISAM is a storage engine that offers fast read operations but lacks support for transactions, while InnoDB supports transactions and foreign keys, providing better data integrity.

A stored procedure is a set of SQL statements that can be stored and executed on the MySQL server, allowing for modular programming and code reuse.

Use the command: mysqldump -u username -p database_name > backup.sql; to create a backup of a MySQL database.

Use the command: DELETE FROM table_name WHERE condition; to remove records from a MySQL table.

A foreign key is a column or set of columns in one MySQL table that references the primary key in another, establishing a relationship between the two tables.

Use the command: CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW BEGIN SQL_statements; END; to create a trigger in MySQL.

Normalization in MySQL is the process of organizing data to reduce redundancy and improve data integrity by dividing large tables into smaller ones.

JOIN is used to combine rows from two or more MySQL tables based on a related column, allowing for complex queries and data retrieval.

Use the command: mysqldump -u username -p database_name > backup.sql; to export a MySQL database to a SQL file.

line

Copyrights © 2024 letsupdateskills All rights reserved