Home Blog Page 21

INNER JOIN in SQL Explained with Examples

0
sql course

Table of Contents

  1. Introduction
  2. What is an INNER JOIN?
  3. Syntax of INNER JOIN
  4. How INNER JOIN Works
  5. INNER JOIN with Real Tables
  6. INNER JOIN with Aliases
  7. Filtering with INNER JOIN
  8. INNER JOIN on Multiple Conditions
  9. INNER JOIN with Aggregate Functions
  10. INNER JOIN with GROUP BY
  11. INNER JOIN Between Three or More Tables
  12. INNER JOIN vs LEFT JOIN
  13. Common Mistakes with INNER JOIN
  14. Performance Tips
  15. Best Practices
  16. Real-World Examples
  17. Sample Data Setup
  18. Nested INNER JOINs
  19. Using INNER JOIN in Subqueries
  20. Summary and Whatโ€™s Next

1. Introduction

The INNER JOIN is the most commonly used JOIN in SQL. It returns rows when there is a match in both joined tables. If you’re working with normalized databases, INNER JOIN is your best friend.


2. What is an INNER JOIN?

An INNER JOIN returns only the rows where matching values exist in both tables based on a specified condition.


3. Syntax of INNER JOIN

sqlCopyEditSELECT table1.column, table2.column
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;

4. How INNER JOIN Works

It performs a row-by-row comparison, returning only those pairs where the condition matches.

Think of it as the intersection of two datasets.


5. INNER JOIN with Real Tables

Suppose we have two tables:

customers

idname
1Ravi
2Sneha
3Aditya

orders

idcustomer_idtotal
11500
221000
34300
sqlCopyEditSELECT c.name, o.total
FROM customers c
INNER JOIN orders o
ON c.id = o.customer_id;

Result:

nametotal
Ravi500
Sneha1000

Notice: Aditya and customer_id 4 (nonexistent in customers) are excluded.


6. INNER JOIN with Aliases

Aliases help shorten queries:

sqlCopyEditSELECT c.name, o.total
FROM customers AS c
INNER JOIN orders AS o
ON c.id = o.customer_id;

This is functionally the same and widely used in production SQL.


7. Filtering with INNER JOIN

Add WHERE for more specific results:

sqlCopyEditSELECT c.name, o.total
FROM customers c
INNER JOIN orders o ON c.id = o.customer_id
WHERE o.total > 500;

Returns customers with orders above 500.


8. INNER JOIN on Multiple Conditions

sqlCopyEditSELECT *
FROM a
INNER JOIN b
ON a.id = b.a_id AND a.status = b.status;

Used when join requires more than one field to match.


9. INNER JOIN with Aggregate Functions

sqlCopyEditSELECT c.name, COUNT(o.id) AS order_count
FROM customers c
INNER JOIN orders o ON c.id = o.customer_id
GROUP BY c.name;

Returns total number of orders per customer.


10. INNER JOIN with GROUP BY

You can combine JOINs with GROUP BY to get grouped metrics:

sqlCopyEditSELECT d.name AS department, AVG(e.salary) AS avg_salary
FROM employees e
INNER JOIN departments d ON e.dept_id = d.id
GROUP BY d.name;

11. INNER JOIN Between Three or More Tables

sqlCopyEditSELECT e.name, d.name AS dept, l.city
FROM employees e
INNER JOIN departments d ON e.dept_id = d.id
INNER JOIN locations l ON d.location_id = l.id;

This joins 3 tables: employees โ†’ departments โ†’ locations.


12. INNER JOIN vs LEFT JOIN

FeatureINNER JOINLEFT JOIN
Match onlyReturns only matchesReturns all from left table
NULL valuesSkipped if no matchShown as NULL if no match
PerformanceSlightly fasterSlightly heavier

13. Common Mistakes with INNER JOIN

  • Missing ON clause โ€” leads to cross join
  • Forgetting to qualify column names โ€” ambiguity
  • Expecting unmatched rows to appear โ€” use LEFT JOIN instead
  • Matching on incorrect columns โ€” wrong results

14. Performance Tips

  • Always index columns used in ON clause
  • Avoid joining unnecessary columns
  • Filter early using WHERE
  • Use proper data types to avoid implicit type casting

15. Best Practices

  • Use meaningful aliases
  • Qualify columns: table.column
  • Use INNER JOIN over WHERE-based joins (modern syntax)
  • Avoid SELECT * in joins
  • Comment complex logic if needed

16. Real-World Examples

Example 1: Customers and Orders

sqlCopyEditSELECT c.name, o.order_date
FROM customers c
INNER JOIN orders o ON c.id = o.customer_id;

Example 2: Students and Courses

sqlCopyEditSELECT s.name, c.title
FROM students s
INNER JOIN enrollments e ON s.id = e.student_id
INNER JOIN courses c ON e.course_id = c.id;

17. Sample Data Setup

sqlCopyEditCREATE TABLE customers (
  id INT PRIMARY KEY,
  name VARCHAR(100)
);

CREATE TABLE orders (
  id INT PRIMARY KEY,
  customer_id INT,
  total DECIMAL(10, 2)
);

18. Nested INNER JOINs

sqlCopyEditSELECT name, total
FROM (
  SELECT c.name, o.total
  FROM customers c
  INNER JOIN orders o ON c.id = o.customer_id
) AS summary
WHERE total > 500;

Useful for isolating complex subqueries.


19. Using INNER JOIN in Subqueries

sqlCopyEditSELECT *
FROM orders
WHERE customer_id IN (
  SELECT id FROM customers WHERE city = 'Delhi'
);

Can be rewritten as a more efficient INNER JOIN.


20. Summary and Whatโ€™s Next

INNER JOIN is the backbone of combining tables in SQL. It ensures that only related records are retrieved โ€” clean, fast, and accurate. When working with normalized databases, this is the most frequently used join.

Understanding Joins in SQL

0
sql course

Table of Contents

  1. Introduction
  2. What is a Join in SQL?
  3. Why Do We Use Joins?
  4. Types of Joins in SQL
  5. INNER JOIN Explained
  6. LEFT JOIN Explained
  7. RIGHT JOIN Explained
  8. FULL OUTER JOIN Explained
  9. CROSS JOIN Explained
  10. SELF JOIN Explained
  11. Syntax for JOINs
  12. Aliasing Tables in Joins
  13. Filtering Data in Joins
  14. Joining More Than Two Tables
  15. Real-World Example: Employee and Department
  16. Real-World Example: Orders and Customers
  17. Common Errors with Joins
  18. Performance Tips for Joins
  19. Best Practices for Writing JOINs
  20. Summary and Whatโ€™s Next

1. Introduction

In real-world databases, information is often spread across multiple tables. The power of SQL comes from its ability to combine this data using JOINs โ€” a way to retrieve related data in a single query.


2. What is a Join in SQL?

A JOIN is used to combine rows from two or more tables based on a related column between them โ€” typically a foreign key and a primary key.


3. Why Do We Use Joins?

  • Retrieve data from related tables
  • Reduce data duplication
  • Normalize tables for better database design
  • Answer complex queries with multiple dimensions

4. Types of Joins in SQL

Join TypeDescription
INNER JOINOnly matching records in both tables
LEFT JOINAll records from the left + matches from right
RIGHT JOINAll records from the right + matches from left
FULL OUTER JOINAll records from both tables
CROSS JOINCartesian product of both tables
SELF JOINA table joined to itself

5. INNER JOIN Explained

Returns rows when there is a match in both tables.

sqlCopyEditSELECT employees.name, departments.name AS dept
FROM employees
INNER JOIN departments ON employees.dept_id = departments.id;

If an employee doesnโ€™t have a department, they will not appear in the result.


6. LEFT JOIN Explained

Returns all rows from the left table and matched rows from the right. Fills in NULL if thereโ€™s no match.

sqlCopyEditSELECT customers.name, orders.total
FROM customers
LEFT JOIN orders ON customers.id = orders.customer_id;

Customers with no orders will still appear with NULL in the total.


7. RIGHT JOIN Explained

Opposite of LEFT JOIN: returns all rows from the right table and matched rows from the left.

sqlCopyEditSELECT orders.total, customers.name
FROM orders
RIGHT JOIN customers ON orders.customer_id = customers.id;

Not all SQL databases (e.g., SQLite) support RIGHT JOIN.


8. FULL OUTER JOIN Explained

Returns all rows from both tables, with NULLs where thereโ€™s no match.

sqlCopyEditSELECT a.name, b.name
FROM tableA a
FULL OUTER JOIN tableB b ON a.id = b.a_id;

Useful to detect unmatched records from either side.


9. CROSS JOIN Explained

Creates a Cartesian product โ€” every row from table A is paired with every row from table B.

sqlCopyEditSELECT a.color, b.size
FROM colors a
CROSS JOIN sizes b;

If colors has 4 rows and sizes has 3, the result will have 12 rows (4ร—3).


10. SELF JOIN Explained

A table joined with itself. Useful for hierarchical or recursive relationships.

sqlCopyEditSELECT a.name AS employee, b.name AS manager
FROM employees a
JOIN employees b ON a.manager_id = b.id;

11. Syntax for JOINs

Basic syntax:

sqlCopyEditSELECT columns
FROM table1
JOIN table2 ON table1.column = table2.column;

Use INNER, LEFT, RIGHT, or FULL as needed.


12. Aliasing Tables in Joins

Use aliases for shorter, readable queries:

sqlCopyEditSELECT e.name, d.name
FROM employees AS e
JOIN departments AS d ON e.dept_id = d.id;

13. Filtering Data in Joins

You can add WHERE clauses to filter results:

sqlCopyEditSELECT o.id, c.name
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.total > 1000;

14. Joining More Than Two Tables

You can chain multiple joins:

sqlCopyEditSELECT e.name, d.name AS department, l.city
FROM employees e
JOIN departments d ON e.dept_id = d.id
JOIN locations l ON d.location_id = l.id;

15. Real-World Example: Employee and Department

sqlCopyEditSELECT e.name AS employee, d.name AS department
FROM employees e
JOIN departments d ON e.dept_id = d.id;

16. Real-World Example: Orders and Customers

sqlCopyEditSELECT c.name AS customer, o.total, o.order_date
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id
WHERE o.order_date >= '2024-01-01';

17. Common Errors with Joins

ErrorCause
Duplicate columnsSelecting columns with same names from both tables
Missing ON clauseResults in a cross join
Forgetting alias prefixesLeads to ambiguous column references
Incorrect join typeUnexpected NULL or missing records

18. Performance Tips for Joins

  • Use indexed columns for join conditions
  • Prefer INNER JOIN when possible (faster)
  • Limit result set with WHERE, LIMIT
  • Avoid joining on non-indexed or computed columns
  • Always analyze execution plan for large joins

19. Best Practices for Writing JOINs

  • Always use ON explicitly, not implicit joins with commas
  • Use table aliases to simplify queries
  • Qualify all column names in multi-table queries
  • Only SELECT needed columns โ€” avoid SELECT *
  • Add comments if joins are complex or involve business logic

20. Summary and Whatโ€™s Next

Joins are the cornerstone of relational databases. Whether youโ€™re linking users to orders, products to categories, or employees to managers โ€” joins help you query data across normalized tables. Mastering each join type gives you the power to extract precise and meaningful insights from complex datasets.

Basic Subqueries and Their Use Cases in SQL

0
sql course

Table of Contents

  1. Introduction
  2. What is a Subquery?
  3. Types of Subqueries
  4. Why Use Subqueries?
  5. Syntax of a Subquery
  6. Subqueries in SELECT Clause
  7. Subqueries in FROM Clause
  8. Subqueries in WHERE Clause
  9. Single-Row vs Multi-Row Subqueries
  10. Using Subqueries with IN
  11. Using Subqueries with =, >, <, !=
  12. Using Subqueries with EXISTS
  13. Correlated vs Non-Correlated Subqueries
  14. Real-World Example: Top-Selling Products
  15. Real-World Example: Customers Without Orders
  16. Subquery vs JOIN: When to Use What
  17. Performance Considerations
  18. Common Errors in Subqueries
  19. Best Practices for Subqueries
  20. Summary and Whatโ€™s Next

1. Introduction

SQL subqueries allow you to nest a query inside another query. This helps break complex logic into manageable pieces, supports modular querying, and powers dynamic filtering.


2. What is a Subquery?

A subquery is a query that is embedded inside another SQL statement. It is enclosed in parentheses and can return a single value or a set of values.


3. Types of Subqueries

TypeDescription
Scalar SubqueryReturns a single value
Row SubqueryReturns a single row
Table SubqueryReturns multiple rows and columns
Correlated SubqueryDepends on the outer query’s row

4. Why Use Subqueries?

  • To avoid temporary tables
  • To write readable nested logic
  • To dynamically filter based on other data
  • To create reusable logic inside complex queries

5. Syntax of a Subquery

sqlCopyEditSELECT column
FROM table
WHERE column IN (
    SELECT column FROM another_table WHERE condition
);

6. Subqueries in SELECT Clause

sqlCopyEditSELECT name,
       (SELECT AVG(salary) FROM employees) AS avg_salary
FROM employees;

Each row shows the employee’s name and the average salary across all employees.


7. Subqueries in FROM Clause

sqlCopyEditSELECT dept, avg_salary
FROM (
    SELECT department AS dept, AVG(salary) AS avg_salary
    FROM employees
    GROUP BY department
) AS dept_summary
WHERE avg_salary > 60000;

Used when you want to treat the result of one query as a virtual table.


8. Subqueries in WHERE Clause

sqlCopyEditSELECT * FROM products
WHERE price > (
    SELECT AVG(price) FROM products
);

This filters products that cost more than the average price.


9. Single-Row vs Multi-Row Subqueries

  • Single-row: use =, >, <, !=
  • Multi-row: use IN, ANY, ALL, EXISTS

Example:

sqlCopyEditSELECT name FROM customers
WHERE id IN (
    SELECT customer_id FROM orders WHERE total > 1000
);

10. Using Subqueries with IN

sqlCopyEditSELECT name FROM users
WHERE id IN (
    SELECT user_id FROM logins WHERE login_date >= '2024-01-01'
);

Returns users who logged in recently.


11. Using Subqueries with =, >, <, !=

sqlCopyEditSELECT name, salary FROM employees
WHERE salary > (
    SELECT AVG(salary) FROM employees
);

Useful for value comparisons against aggregates or single-row results.


12. Using Subqueries with EXISTS

sqlCopyEditSELECT * FROM customers c
WHERE EXISTS (
    SELECT 1 FROM orders o WHERE o.customer_id = c.id
);

Checks for the existence of related rows โ€” often more efficient than IN.


13. Correlated vs Non-Correlated Subqueries

  • Non-Correlated: Executed once
  • Correlated: Re-evaluated per row of the outer query

Correlated Example:

sqlCopyEditSELECT name FROM employees e
WHERE salary > (
    SELECT AVG(salary)
    FROM employees
    WHERE department = e.department
);

Each employee is compared to their departmentโ€™s average.


14. Real-World Example: Top-Selling Products

sqlCopyEditSELECT * FROM products
WHERE id IN (
    SELECT product_id
    FROM order_items
    GROUP BY product_id
    HAVING SUM(quantity) = (
        SELECT MAX(total_quantity)
        FROM (
            SELECT product_id, SUM(quantity) AS total_quantity
            FROM order_items
            GROUP BY product_id
        ) AS totals
    )
);

Finds products with the highest overall sales.


15. Real-World Example: Customers Without Orders

sqlCopyEditSELECT name FROM customers
WHERE id NOT IN (
    SELECT DISTINCT customer_id FROM orders
);

Identifies inactive customers.


16. Subquery vs JOIN: When to Use What

ScenarioUse
You need combined row dataJOIN
You need filters based on summarySubquery
Performance is criticalPrefer JOIN
Self-contained logicSubquery

17. Performance Considerations

  • Subqueries inside SELECT can be slow if not scalar or optimized
  • Correlated subqueries run once per row โ€” use with caution
  • Index columns used in subquery filters (IN, EXISTS)
  • Try converting correlated subqueries to joins for large datasets

18. Common Errors in Subqueries

MistakeFix
Returning multiple rows to =Use IN, or limit with TOP / LIMIT 1
Not aliasing derived tablesRequired in FROM clause
Ambiguous columns in correlationPrefix with table alias

19. Best Practices for Subqueries

  • Use aliases to make subqueries readable
  • Avoid deeply nested subqueries if possible
  • Cache subquery results (e.g., CTEs in PostgreSQL)
  • Always test subqueries independently before integrating

20. Summary and Whatโ€™s Next

Subqueries help you write modular, dynamic, and powerful SQL. From filtering with nested conditions to treating subquery results as tables, they unlock advanced capabilities without making your queries overly complex.

Using the IN, BETWEEN, and LIKE Operators in SQL

0
sql course

Table of Contents

  1. Introduction
  2. Why Use Conditional Operators?
  3. The Role of IN, BETWEEN, and LIKE
  4. Basic Syntax Recap
  5. The IN Operator
  6. IN with Numbers
  7. IN with Strings
  8. IN with Subqueries
  9. NOT IN Clause
  10. Performance Tips for IN
  11. The BETWEEN Operator
  12. BETWEEN with Numbers
  13. BETWEEN with Dates
  14. NOT BETWEEN Clause
  15. The LIKE Operator
  16. Using % and _ in LIKE
  17. Case Sensitivity in LIKE
  18. Real-World Examples
  19. Best Practices
  20. Summary and Whatโ€™s Next

1. Introduction

SQL offers several powerful comparison operators that go beyond =, >, or <. Among them, IN, BETWEEN, and LIKE are highly useful for writing more readable and flexible conditional logic.


2. Why Use Conditional Operators?

These operators allow you to:

  • Match multiple values with ease
  • Filter based on ranges
  • Perform pattern-based text searches

All three are especially useful in filtering rows with specific rules in the WHERE clause.


3. The Role of IN, BETWEEN, and LIKE

OperatorPurpose
INMatch one of several values
BETWEENMatch a value within a range
LIKEMatch a pattern in a string

4. Basic Syntax Recap

sqlCopyEditSELECT * FROM table_name
WHERE column IN (value1, value2, ...);

SELECT * FROM table_name
WHERE column BETWEEN value1 AND value2;

SELECT * FROM table_name
WHERE column LIKE 'pattern';

5. The IN Operator

The IN operator checks whether a value exists in a list or a subquery result.

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

6. IN with Numbers

sqlCopyEditSELECT * FROM orders
WHERE status_id IN (1, 2, 5);

7. IN with Strings

sqlCopyEditSELECT * FROM products
WHERE category IN ('Books', 'Electronics', 'Toys');

8. IN with Subqueries

sqlCopyEditSELECT * FROM users
WHERE id IN (
  SELECT user_id FROM orders
  WHERE total > 1000
);

This checks if a user has made high-value purchases.


9. NOT IN Clause

Negates the IN condition:

sqlCopyEditSELECT * FROM customers
WHERE country NOT IN ('India', 'Nepal');

โš ๏ธ Caution: If any value in the list is NULL, it may yield no results.


10. Performance Tips for IN

  • Avoid large IN lists (consider a join instead)
  • IN is faster and cleaner than multiple OR conditions
  • Use indexed columns in the IN list for better performance

11. The BETWEEN Operator

The BETWEEN operator matches values inclusively within a given range.

sqlCopyEditSELECT * FROM products
WHERE price BETWEEN 100 AND 500;

This returns products priced from 100 to 500 inclusive.


12. BETWEEN with Numbers

sqlCopyEditSELECT * FROM students
WHERE marks BETWEEN 40 AND 75;

13. BETWEEN with Dates

sqlCopyEditSELECT * FROM orders
WHERE order_date BETWEEN '2024-01-01' AND '2024-01-31';

Great for monthly reports or time-bound queries.


14. NOT BETWEEN Clause

sqlCopyEditSELECT * FROM inventory
WHERE quantity NOT BETWEEN 10 AND 50;

Excludes values within the specified range.


15. The LIKE Operator

LIKE is used for pattern matching in string fields. It uses:

  • %: matches any number of characters
  • _: matches a single character
sqlCopyEditSELECT * FROM customers
WHERE name LIKE 'A%';

Finds names starting with โ€œAโ€.


16. Using % and _ in LIKE

PatternDescription
'A%'Starts with A
'%India'Ends with “India”
'%Tech%'Contains “Tech”
'A___'“A” followed by 3 characters

Examples:

sqlCopyEditSELECT * FROM emails WHERE email LIKE '%@gmail.com';
SELECT * FROM cities WHERE name LIKE '_elhi'; -- matches 'Delhi'

17. Case Sensitivity in LIKE

  • MySQL: case-insensitive by default (on most collations)
  • PostgreSQL: case-sensitive
  • Use ILIKE in PostgreSQL for case-insensitive match:
sqlCopyEditSELECT * FROM names WHERE name ILIKE 'a%';

18. Real-World Examples

1. Active Regions:

sqlCopyEditSELECT * FROM sales
WHERE region IN ('North', 'West');

2. High Scores:

sqlCopyEditSELECT name FROM students
WHERE marks BETWEEN 85 AND 100;

3. Gmail Users:

sqlCopyEditSELECT name, email FROM users
WHERE email LIKE '%@gmail.com';

19. Best Practices

  • Use IN over multiple OR conditions for readability
  • Use BETWEEN only for inclusive boundaries
  • Use % carefully with LIKE; avoid starting with % if index performance matters
  • Avoid LIKE on very large unindexed text fields
  • Use aliases for cleaner queries when combining with SELECT, JOIN, or subqueries

20. Summary and Whatโ€™s Next

The IN, BETWEEN, and LIKE operators enhance your ability to write clear and concise filtering conditions in SQL. They are powerful tools for conditional logic, especially in WHERE clauses, enabling more expressive queries.

Using the IN, BETWEEN, and LIKE Operators in SQL

0
sql course

Table of Contents

  1. Introduction
  2. Why Use Conditional Operators?
  3. The Role of IN, BETWEEN, and LIKE
  4. Basic Syntax Recap
  5. The IN Operator
  6. IN with Numbers
  7. IN with Strings
  8. IN with Subqueries
  9. NOT IN Clause
  10. Performance Tips for IN
  11. The BETWEEN Operator
  12. BETWEEN with Numbers
  13. BETWEEN with Dates
  14. NOT BETWEEN Clause
  15. The LIKE Operator
  16. Using % and _ in LIKE
  17. Case Sensitivity in LIKE
  18. Real-World Examples
  19. Best Practices
  20. Summary and Whatโ€™s Next

1. Introduction

SQL offers several powerful comparison operators that go beyond =, >, or <. Among them, IN, BETWEEN, and LIKE are highly useful for writing more readable and flexible conditional logic.


2. Why Use Conditional Operators?

These operators allow you to:

  • Match multiple values with ease
  • Filter based on ranges
  • Perform pattern-based text searches

All three are especially useful in filtering rows with specific rules in the WHERE clause.


3. The Role of IN, BETWEEN, and LIKE

OperatorPurpose
INMatch one of several values
BETWEENMatch a value within a range
LIKEMatch a pattern in a string

4. Basic Syntax Recap

sqlCopyEditSELECT * FROM table_name
WHERE column IN (value1, value2, ...);

SELECT * FROM table_name
WHERE column BETWEEN value1 AND value2;

SELECT * FROM table_name
WHERE column LIKE 'pattern';

5. The IN Operator

The IN operator checks whether a value exists in a list or a subquery result.

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

6. IN with Numbers

sqlCopyEditSELECT * FROM orders
WHERE status_id IN (1, 2, 5);

7. IN with Strings

sqlCopyEditSELECT * FROM products
WHERE category IN ('Books', 'Electronics', 'Toys');

8. IN with Subqueries

sqlCopyEditSELECT * FROM users
WHERE id IN (
  SELECT user_id FROM orders
  WHERE total > 1000
);

This checks if a user has made high-value purchases.


9. NOT IN Clause

Negates the IN condition:

sqlCopyEditSELECT * FROM customers
WHERE country NOT IN ('India', 'Nepal');

โš ๏ธ Caution: If any value in the list is NULL, it may yield no results.


10. Performance Tips for IN

  • Avoid large IN lists (consider a join instead)
  • IN is faster and cleaner than multiple OR conditions
  • Use indexed columns in the IN list for better performance

11. The BETWEEN Operator

The BETWEEN operator matches values inclusively within a given range.

sqlCopyEditSELECT * FROM products
WHERE price BETWEEN 100 AND 500;

This returns products priced from 100 to 500 inclusive.


12. BETWEEN with Numbers

sqlCopyEditSELECT * FROM students
WHERE marks BETWEEN 40 AND 75;

13. BETWEEN with Dates

sqlCopyEditSELECT * FROM orders
WHERE order_date BETWEEN '2024-01-01' AND '2024-01-31';

Great for monthly reports or time-bound queries.


14. NOT BETWEEN Clause

sqlCopyEditSELECT * FROM inventory
WHERE quantity NOT BETWEEN 10 AND 50;

Excludes values within the specified range.


15. The LIKE Operator

LIKE is used for pattern matching in string fields. It uses:

  • %: matches any number of characters
  • _: matches a single character
sqlCopyEditSELECT * FROM customers
WHERE name LIKE 'A%';

Finds names starting with โ€œAโ€.


16. Using % and _ in LIKE

PatternDescription
'A%'Starts with A
'%India'Ends with “India”
'%Tech%'Contains “Tech”
'A___'“A” followed by 3 characters

Examples:

sqlCopyEditSELECT * FROM emails WHERE email LIKE '%@gmail.com';
SELECT * FROM cities WHERE name LIKE '_elhi'; -- matches 'Delhi'

17. Case Sensitivity in LIKE

  • MySQL: case-insensitive by default (on most collations)
  • PostgreSQL: case-sensitive
  • Use ILIKE in PostgreSQL for case-insensitive match:
sqlCopyEditSELECT * FROM names WHERE name ILIKE 'a%';

18. Real-World Examples

1. Active Regions:

sqlCopyEditSELECT * FROM sales
WHERE region IN ('North', 'West');

2. High Scores:

sqlCopyEditSELECT name FROM students
WHERE marks BETWEEN 85 AND 100;

3. Gmail Users:

sqlCopyEditSELECT name, email FROM users
WHERE email LIKE '%@gmail.com';

19. Best Practices

  • Use IN over multiple OR conditions for readability
  • Use BETWEEN only for inclusive boundaries
  • Use % carefully with LIKE; avoid starting with % if index performance matters
  • Avoid LIKE on very large unindexed text fields
  • Use aliases for cleaner queries when combining with SELECT, JOIN, or subqueries

20. Summary and Whatโ€™s Next

The IN, BETWEEN, and LIKE operators enhance your ability to write clear and concise filtering conditions in SQL. They are powerful tools for conditional logic, especially in WHERE clauses, enabling more expressive queries.