0

I need help for sql query LIKE. Value for column in database is same below:

 record 1 : "3,13,15,20"
 record 2 : "13,23,14,19"
 record 3 : "3,14,15,19,20"......

for now I want to get the most accurate record with a value of 3 This is my query :

SELECT * FROM accounts where type like '%3%' 

This query will find all record with value exist is '3' eg: 13,23 .... And It does not solve my problem.

6
  • 2
    Don't store data as comma separated items. It will only cause you lots of trouble. Commented Aug 6, 2018 at 11:05
  • Please specify database engine you're using in tags Commented Aug 6, 2018 at 11:05
  • 1
    Also, a table has rows, not records... Commented Aug 6, 2018 at 11:06
  • 1
    @TimBiegeleisen, same people who say field instead of column? (The ANSI SQL specification uses row and column exclusively.) Commented Aug 6, 2018 at 11:12
  • 1
    @jarlh: you're absolutely right - relational databases have tables with rows and columns - but it seems like a struggle in vain to try and convince the IT crowd to be precise and use the proper, correct lingo :-( Commented Aug 6, 2018 at 12:04

1 Answer 1

3

Try this:

SELECT *
FROM accounts
WHERE CONCAT(',', type, ',') LIKE '%,3,%';

enter image description here

Demo

This trick places commas around the end of the type CSV string, so that we all we have to do is then check for ,3, anywhere in that string.

By the way, it is generally not desirable to store CSV data like this in your SQL tables. Instead, consider normalizing your data and storing those CSV values across separate rows.

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

Comments

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.