29

I'm sure this is super easy, but can't seem to figure it out.. I need to select all titles from my database where the title starts with A, or B, or C etc. Here's what I've tried so far:

SELECT * FROM weblinks WHERE catid = 4 AND title LIKE 'A'

but returns nothing.. Could someone help me out with this?

Cheers

SoulieBaby
  • 5,405
  • 25
  • 95
  • 145

5 Answers5

63

For titles starting in 'A' use a % after the A

SELECT * FROM weblinks WHERE catid = 4 AND title LIKE 'A%'

For titles with the letter 'A' in it, use % on either side of A

SELECT * FROM weblinks WHERE catid = 4 AND title LIKE '%A%'

For titles ending in the letter 'A', use % before the A

SELECT * FROM weblinks WHERE catid = 4 AND title LIKE '%A'

Basically % is a wildcard. It tells MySQL that anything can be in the location.

For having numbers as the first letter, check out Mark's answer.

Community
  • 1
  • 1
Tyler Carter
  • 60,743
  • 20
  • 130
  • 150
7

The wildcards for LIKE are % and _, where % matches 0 or more characters and _ matches exactly one character.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
7

The existing answers are correct for beginning with A:

SELECT * FROM weblinks WHERE catid = 4 AND title LIKE 'A%'

For beginning with any number you can use the REGEXP operator:

SELECT * FROM weblinks WHERE catid = 4 AND title REGEXP '^[0-9]'
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 1
    Come to steal the accepted answer away from me eh? (Just Kidding) Added a link to your answer. – Tyler Carter Jan 15 '10 at 03:27
  • 3
    @Soulie: you should probably accept Chacha's answer since you changed the question after he had already answered it correctly. Next time, if you make a substantial change to a question, start a new question rather than changing an existing one. – Mark Byers Jan 15 '10 at 03:33
2

try:

SELECT * FROM weblinks WHERE catid = 4 AND ((title like 'A%') OR (title like 'B%'))

so on and so forth

catsby
  • 11,276
  • 3
  • 37
  • 37
1

SELECT * FROM weblinks WHERE catid = 4 AND title LIKE 'A%'

% tells "anything", so it's "A" then anything. Only works with the LIKE comparison operator.

zneak
  • 134,922
  • 42
  • 253
  • 328