Reputation: 4436
I have a comma separated list of names in a database called owners (sometimes there is one owner sometimes there are multiple owners... if there are more than 1 the names are comma separated). I want to find whether a certain name appears as the first name in the owners field. So I need to search for a pattern as e.g. with the like command in sql, but I need to restrict it to the part before the first comma. Note that I want that the entry
John Doe, Katrin
is found if my pattern is "John". Is that possible at all? I am looking for a solution in sqlalchemy, but if there is a solution in sql I am sure I can find the sqlalchemy version myself. thanks carl
Upvotes: 0
Views: 275
Reputation: 5890
You can get away with using LIKE
as it is as the front of the string. The %
match anything. Here it is in sqlalchemy
session.query(Object).filter(Object.column.like('THENAME,%'))
If you want to match just "Jon Doe" with just "Jon" you will need a regex
session.query(Object).filter(Object.column.op('regexp')('r^Jon[^,]*,'))
This will match anything starting ^
with Jon
followed by any number of non ,
chars [^,]*
followed by ,
Upvotes: 1
Reputation: 49270
In SQL server, you could do:
select colname
where substring(lower(colname), 1, charindex(',',lower(colname))-1) like '%john%'
You could do the same in Oracle as
select colname
where substr(lower(colname), 1, instr(lower(colname),',')-1) like '%john%'
As you can see the functions are specific to databases.
Upvotes: 2