29

I realise that it would be a lot easier if I could modify the table when it was created, but assuming I can't, I have a table that is such as:

abcd
abde
abdf
abff
bbsdf
bcggs
... snip large amount
zza

The values in the table are not fixed length. I have a string to match such as abffagpokejfkjs . If it was the other way round, I could do

SELECT * from table where value like 'abff%'

but I need to select the value that matches the start of a string that is provided.

Is there a quick way of doing that, or does it need an itteration through the table to find a match?

2
  • I don't understand the problem. What value are you trying to return? Why can you not just use LEFT(value, 4) or a LIKE? Commented Mar 12, 2012 at 12:48
  • I can't use LEFT as I don't know how many characters the result is - could be 1, could be 25. Could loop through all the numbers but doesn't sound fast. Commented Mar 12, 2012 at 12:54

2 Answers 2

51

Try this:

SELECT col1, col2 -- etc...
FROM your_table
WHERE 'abffagpokejfkjs' LIKE CONCAT(value, '%')

Note that this will not use an index effectively so it will be slow if you have a lot of records.

Also note that some characters in value (e.g. %) may be interpreted by LIKE as having a special meaning, which may undesirable.

Sign up to request clarification or add additional context in comments.

Comments

18

LIKE can be avoided, by truncating the comparison string to each value's length:

... WHERE LEFT('abffagpokejfkjs', LENGTH(value)) = value

1 Comment

I had to use CHAR_LENGTH. LENGTH returns number of bytes, which in case of non-ASCII strings may not be desired.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.