Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php select from mysql where title begins with A (and A alone)

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

like image 371
SoulieBaby Avatar asked Jan 15 '10 03:01

SoulieBaby


3 Answers

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.

like image 63
Tyler Carter Avatar answered Oct 22 '22 04:10

Tyler Carter


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

like image 21
Ignacio Vazquez-Abrams Avatar answered Oct 22 '22 02:10

Ignacio Vazquez-Abrams


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]'
like image 7
Mark Byers Avatar answered Oct 22 '22 04:10

Mark Byers