SQL · Module 4 · Lesson 41 min read

BETWEEN, IN, LIKE & ILIKE

BETWEEN – inclusive ranges

amount BETWEEN 1000 AND 3000 = amount >= 1000 AND amount <= 3000 (both ends included)

  • Works with numbers, dates and text
  • NOT BETWEEN for outside the range
  • ⚠️ With timestamps, BETWEEN '2026-11-01' AND '2026-11-30' misses everything after midnight on the 30th. For time ranges prefer a half-open range: >= '2026-11-01' AND < '2026-12-01'

IN – match any value in a list

city IN ('Pokhara', 'Lalitpur') = city = 'Pokhara' OR city = 'Lalitpur'

  • NOT IN (…) – ⚠️ if the list contains a NULL, NOT IN returns nothing (more in Unit 8)
  • The list can be a subquery: user_id IN (SELECT id FROM users WHERE …)

LIKE – pattern matching (case-sensitive)

WildcardMatches
%any number of characters (including none)
_exactly one character
  • 'Fuel%' starts with Fuel; '%bill' ends with bill; '%cafe%' contains cafe
  • '_ari%' – second to fourth letters are "ari" (Hari)
  • Match a literal % or _ with an escape: LIKE '50\%%'

ILIKE – case-insensitive LIKE (PostgreSQL)

title ILIKE '%GROCER%' finds Groceries, groceries, GROCERIES

Performance

  • LIKE 'abc%' (prefix) can use a B-tree index
  • LIKE '%abc%' (contains) scans every row → use a trigram index (pg_trgm) or full-text search for big tables (Unit 13)

More power

  • SIMILAR TO and regular expressions ~, ~* (Unit 5)

Example

SQL
-- BETWEEN (inclusive)
SELECT title, amount FROM expenses
WHERE amount BETWEEN 1000 AND 1500
ORDER BY amount;
-- Bus pass 1000, Bike service 1200, Dinner 1250, Electricity bill 1350, Internet bill 1500 (x2)

-- Dates: November expenses (half-open range is the safest habit)
SELECT title, spent_on FROM expenses
WHERE spent_on >= '2026-11-01' AND spent_on < '2026-12-01'
  AND user_id = 4;

-- IN
SELECT name, city FROM users WHERE city IN ('Pokhara', 'Lalitpur');
SELECT title FROM expenses WHERE category_id IN (9, 10) AND user_id = 1;   -- bills

-- LIKE patterns
SELECT DISTINCT title FROM expenses WHERE title LIKE '%bill';       -- ends with "bill"
SELECT name FROM users WHERE name LIKE '_a%';                       -- 2nd letter is "a"
-- Ravi Thapa, Maya Karki, Hari Shrestha

-- ILIKE: case-insensitive search box
SELECT title, amount FROM expenses WHERE title ILIKE '%GROCER%';

-- Search notes, ignoring NULL notes automatically
SELECT title, note FROM expenses WHERE note ILIKE '%dinner%';
-- Dinner at Thamel | Birthday dinner