Skip to content

SQL LIKE & Wildcards πŸ”ΒΆ

Prerequisites: WHERE Clause

Mentor's Note: Sometimes you don't know the full name or code you are looking for. You might only remember it "starts with A" or "contains the word tech". The LIKE operator is the "Search Engine" of SQL. πŸ’‘


🌟 The Scenario: The Lost Contact πŸ“±ΒΆ

Imagine you are searching for a friend in your phone book. - The Hint: You remember their name starts with "Sha". - The Pattern: Sha% - The Result: You find "Sharma", "Shanti", and "Shakti". βœ…


🎨 Visual Logic: The Wildcard Tools¢

Wildcard Meaning Analogy
% (Percent) Any number of characters (0 to many) The "Infinite Bridge" πŸŒ‰
_ (Underscore) Exactly one character The "Single Step" πŸ‘£

πŸ’» 1. Using the % WildcardΒΆ

A. "Starts With" PatternΒΆ

-- Scenario: Find all names starting with 'V'
SELECT * FROM students
WHERE name LIKE 'V%'; -- Finds: Vishnu, Vikram, Vijay

B. "Ends With" PatternΒΆ

-- Scenario: Find emails ending in '.com'
SELECT * FROM students
WHERE email LIKE '%.com';

C. "Contains" PatternΒΆ

-- Scenario: Find any name that has 'sh' anywhere
SELECT * FROM students
WHERE name LIKE '%sh%'; -- Finds: Vishnu, Rahul, Akash

πŸ’» 2. Using the _ WildcardΒΆ

The underscore matches exactly one character. Use it when the length is fixed.

-- Scenario: Find 4-letter names starting with 'A'
SELECT * FROM students
WHERE name LIKE 'A___'; -- (A followed by 3 underscores)
-- Finds: Amit, Ajay | Skips: Arjun (5 letters)

πŸ’» 3. Case Sensitivity & Dialects πŸ› οΈΒΆ

Searching for 'apple' vs 'Apple' behaves differently depending on your database.

  • MySQL: Usually case-insensitive.
  • Oracle: Strictly Case-Sensitive (Must match exact casing).
  • PostgreSQL: Case-sensitive by default, but you can use ILIKE for case-insensitive searching!
-- PostgreSQL Specific: Case-Insensitive Search
SELECT * FROM students WHERE name ILIKE 'vishnu';

πŸ’‘ Pro Tip: Performance WarningΒΆ

"Avoid starting a pattern with a wildcard like %name. This forces the database to scan every single row because it can't use an index. Patterns like name% are much faster!"


πŸ“ˆ Learning PathΒΆ