Reputation: 625
I have a simple table that looks like below
I need to find the 'ID' which has the Number 3
, so i wrote a query like below
select * from IDtable where Number like '%3%'
it is actually returning all the ID
since i have used like
and the Number
contains many values starting with 3
, how do i get the id
which contains 3
Upvotes: 1
Views: 364
Reputation: 164099
Concatenate a ,
at the start and at the end of the column and check if it contains ',3,'
with the operator LIKE
:
SELECT *
FROM IDtable
WHERE ',' || Number || ',' LIKE '%,3,%'
or with INSTR()
:
SELECT *
FROM IDtable
WHERE INSTR(',' || Number || ',', ',3,')
In Python, you should use a ?
placeholder for the parameter "3"
:
n = "3"
sql = """
SELECT *
FROM IDtable
WHERE ',' || Number || ',' LIKE '%,' || ? || ',%'
"""
cursor.execute(sql, (n,))
Note that a normalized table like:
ID Number Ab 2 Ab 9 Ab 16 ... ...... cD 3 cD 10 cD 17 ... ......
would save you all the trouble of querying with a complicated string expression which may prove bad for performance.
Upvotes: 1