Click here to Skip to main content
15,886,059 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,
May be the Question's title is not correctly defined what i actually wanted to ask. Here is the more specific description of my question

I have a following table 'User' in my database which has a column i.e. Category which contains multiple values but separated by commas

S.no.         Name         Category
1             Ankit         Ex Soldier, Senior Citizen
2               Ritu           Widow, Senior Citizen
3             Akash               Ex soldier

I wanted to search the record on the basis of category

for eg. If i search
SQL
select * from User where Category='Senior Citizen'

Then it must show Ankit and Ritu record.
How to do this.
plz help
thanks
Posted
Updated 6-Jul-15 21:22pm
v2
Comments
Herman<T>.Instance 7-Jul-15 3:25am    
where category LIKE '%Senior Citizen%'
Member 11589183 7-Jul-15 3:35am    
thank u so much :)

Try,

select * from User where Category like '%Senior Citizen%'
 
Share this answer
 
the easiest solution is
you can use LIKE clause
SQL
SELECT * FROM USER WHERE Category LIKE '%Senior Citizen%'
 
Share this answer
 
SQL
where category LIKE '%Senior Citizen%'


More about LIKE keyword in SQL:
see here[^].
 
Share this answer
 
v2
Basically, although you can do it, you shouldn't. Storing data as comma delimited values in an SQL column is a bad idea - it's hard to work with, it's very hard to edit, and it wastes huge amounts of space.
Instead, create a second table which holds your categories:
ID     Description
1      Ex Soldier
2      Senior Citizen
3      Widow

And a third table which correlates those values to your User table:
ID     UserID     CatID
1      1          1
2      1          2
3      2          3
4      2          2
5      3          1
You then use JOINs to cross correlate the tables.
It may seem more complex to set up - and it is - but it's a lot faster for SQL to process (particularly when you get a serious number of records), it's a lot more space efficient, and it's a lot easier to update and maintain later. It also eliminates the possibility of a user entering "Ex-soldier" instead of "Ex Soldier" and your text based checks failing as a result.
 
Share this answer
 
Comments
Member 11589183 7-Jul-15 3:57am    
thanks this info is really helpful. :)
OriginalGriff 7-Jul-15 4:03am    
You're welcome!
It's a lot easier to do this at the early stages - the later you leave it the harder it is to change the fundamentals of your DB design. And when you come to changing a user classification to indicate they have remarried and are no longer a widow for example - that's a total PITA with comma delimited data! :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900