user3090649
user3090649

Reputation: 21

SQL LIKE only one letter

When i use LIKE statement in my SQL,

for example,

      SELECT * FROM table WHERE name = "%k"

It will return all rows, where name ends on k.

It can return : Ok, OOk, OOOk,

How i can do same statement but with one letter, so it returns only Ok.

Or 2 letters, so it returns only OOk?

Upvotes: 3

Views: 8989

Answers (5)

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

_ is a single character wildcard.

SELECT * FROM table WHERE name = `_k`

See this IBM Reference

Upvotes: 11

Serge S.
Serge S.

Reputation: 4915

You should use an underscore (_) character. See the documentation about operator LIKE.

So, the query you need (1 or 2 chars before k) is:

SELECT * FROM table WHERE name LIKE '_k' OR name LIKE '__k'

Upvotes: 2

Schuere
Schuere

Reputation: 1649

depending on the length you provide

For 1 character 'X' followed by k

Select * 
from table 
where length(name) = 2 
AND name = "%k"

For 2 character 'X' followed by k

Select * 
from table 
where length(name) = 3
AND name = "%k"

Upvotes: 0

atripathi
atripathi

Reputation: 908

Use the _ wildcard. It matches only a single character.

_k for Ok. __k for Ook

Upvotes: 1

Dan
Dan

Reputation: 10710

Use the equality operator (=) or the IN operator instead of the LIKE operator:

SELECT * FROM table WHERE name IN ('Ok', 'OOk')

Upvotes: 0

Related Questions