0

I have to search a single string in multiple coloumn in SQLITE but I am unable to get the results, I am using the following query to do the search:

Select * 
From MyTable 
Where (col1 || '--' || col2) like '%abc xyz 123%'

Let's say I have 'abc' in col1 and 'xyz 123' in col2.

Any help.

4
  • Try this: Select *from yourtable where col1 like 'searchstring' or col2 like 'searchstring' etc.\ Commented Nov 8, 2013 at 5:47
  • Your query does the search but it will fail in above mentioned scenario. Commented Nov 8, 2013 at 6:43
  • How can you say it will fail. Did you try it.It wont Fail. You need to Pass different string for col. Select * From Yourtable where col1 like 'abc' or col2 like 'xyz 123'. Commented Nov 8, 2013 at 7:09
  • I don't want to separate both string and can I know which string is part of col1 or col2 as I have to search complete string for both coloumns. Commented Nov 8, 2013 at 11:43

3 Answers 3

1

Lets say I have 'abc' in col1 and 'xyz 123' in col2.

col1 || '--' || col2 is equal 'abc--xyz 123', so will not match '%abc xyz 123%'!

You should use

 SELECT * FROM MyTable WHERE col1 || ' ' || col2 LIKE '%abc xyz 123%'

or

 SELECT * FROM MyTable WHERE col1 || '--' || col2 LIKE '%abc--xyz 123%'

Note: parenthesis are not needed as || has higher precedence than LIKE.

0

The operands of your LIKE statement have to match criteria. If you are looking for a "single string" exact match from concatenation of the fields in those two columns and the (col1) field has 'abc' while the (col2) field has 'xyz 123' ...then the left-hand operand of your LIKE is the concatenation (col1 || col2) and the right-hand operand is the concatenation ('%abc%' || '%xyz 123%') resulting in the statement:

SELECT * FROM MyTable WHERE (col1 || col2) LIKE '%abc%'||'%xyz 123%';

or

SELECT * FROM MyTable WHERE (col1 || '--' || col2) LIKE '%abc%'||'--'||'%xyz 123%';

Example:

C:\SQLite3>sqlite3 test
    SQLite version 3.8.1 2013-10-17 12:57:35
    Enter ".help" for instructions
    Enter SQL statements terminated with a ";"
    sqlite> CREATE table MyTable (col1 text, col2 text);
    sqlite> INSERT into MyTable (col1, col2) values ('abc', 'xyz 123');
    sqlite> SELECT * FROM MyTable WHERE (col1 || col2) LIKE '%abc xyz 123%';
    sqlite> SELECT * FROM MyTable WHERE (col1 || col2) LIKE '%abc%' || 'xyz 123%';
    abc|xyz 123
    sqlite> SELECT * FROM MyTable WHERE (col1 ||'--'|| col2) LIKE '%abc xyz 123%';
    sqlite> SELECT * FROM MyTable WHERE (col1 ||'--'|| col2) LIKE '%abc%'||'--'||'%xyz 123%';
    abc|xyz 123
    sqlite>
0

Correct answer is that I have to modify the above query a little bit like this,

Select * From MyTable Where (col1 || ' ' || col2) like '%abc xyz 123%'
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.