SQL / MySQL Beginner Queries · 6 min read

SQL BETWEEN and IN

Lesson 29 of 33 in the SQL / MySQL learning path.

How do I filter lessons by a seat range or a list of tracks?

BETWEEN includes the two endpoints. IN matches a list of discrete values.

A seat range and a track list are different questions. Using the wrong one returns the wrong catalog.

Syntax & Parameters

Syntax
WHERE seats BETWEEN 10 AND 30 AND track IN ('php', 'sql')

Example

queries.sql
SELECT id, title, track, seats
FROM lessons
WHERE published_at IS NOT NULL
  AND seats BETWEEN 10 AND 30
  AND track IN ('php', 'sql')
ORDER BY seats, title;
-- BETWEEN includes 10 and 30.
-- A seat count of 9 or 31 is excluded.
-- IN is a list, not a range.
-- An empty IN () is a syntax error.
-- Put the bounds in low-to-high order.
-- Bind each value. Do not paste a raw id list into the text.

Expected Output

Published php and sql lessons whose seats are from 10 through 30 inclusive.

Line-by-Line Walkthrough

  1. Only published lessons are considered.
  2. BETWEEN 10 AND 30 keeps both ends.
  3. IN limits the tracks to php and sql.
  4. Results sort by seats, then title.
  5. 9 and 31 are out.
  6. Swap the bounds and MySQL still accepts it, but the range is empty if low is greater than high in some comparisons. Write low then high.
  7. NULL seats fail the BETWEEN test.
  8. Do not build IN from unsanitized text. Bind each value.

Common Pitfalls & Security

Check the edge before you ship it.

  • BETWEEN is inclusive. People often want a half-open range.
  • NOT IN with a NULL in the list surprises people and can match nothing.
  • A giant IN list is a sign you need a join to a real table.
  • String-building the IN clause is SQL injection.

Best Practices & Modern Standards

Use BETWEEN for inclusive numeric ranges and IN for a short explicit list.

Bind every value. Do not concatenate ids into the SQL text.

Real-World Use

An admin filter shows php and sql workshops with 10 to 30 seats so a room booking matches the catalog.

Frequently Asked Questions

Is 10 included?

Yes. BETWEEN includes both endpoints.

What about NULL seats?

NULL fails the comparison, so those rows are excluded.

Can IN be empty?

No. An empty list is a syntax error. Skip the predicate when the list is empty.

Is this safe with user input?

Only if each value is a bound parameter. Do not paste a comma-separated string into the query.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…