views:

300

answers:

5

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

+1  A: 

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
+4  A: 

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.

Chacha102
I think second example is supposed to end in `'%A%'`
ctshryock
Yes, that would be correct. Fixed.
Chacha102
Thanks muchly, I also forgot to ask how to do it if the title begins with a number?
SoulieBaby
Replace the Letter `A` with a Number like `1%`.
Chacha102
can it be done where it's a number wildcard, like it could be any number?
SoulieBaby
Then you start getting into MySQL Regex's. You might want to ask a separate question for that.
Chacha102
+1  A: 

try:

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

so on and so forth

ctshryock
+2  A: 

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

Ignacio Vazquez-Abrams
+1  A: 

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
Come to steal the accepted answer away from me eh? (Just Kidding) Added a link to your answer.
Chacha102
thanks guys muchly appreciated :)
SoulieBaby
@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