Making a query which selects the news that contain a specific word

191 views Asked by At
       CREATE TABLE IF NOT EXISTS news (
           title TEXT PRIMARY KEY,
           newsletter_description TEXT NOT NULL
       );

I need to write a query which selects all the news that contain the word "apple" or "watermelon"(or both) in their title or in their newsletter_description and I am not very sure about how I can do that. (case insensitive, it can also be "AppLe" or "WaterMelon")

5

There are 5 answers

2
ozanmut On BEST ANSWER
SELECT * FROM NEWS
WHERE title LIKE "%apple%" OR 
      title LIKE "%watermelon%" OR
      newsletter_description LIKE "%apple%" OR 
      newsletter_description LIKE "%watermelon% 

SQlite implemented LIKE operator case insensitive for ASCII characters by default. Unless you use unicode characters in your text you can use above query.

However if you use unicode chars, using lower or upper functions doesn't work either. So there is no point in using lower or upper functions at all.

https://www.sqlite.org/c3ref/strlike.html

enter image description here

0
Sujitmohanty30 On

You can use like operator and to have case insensitive search you can either use lower or upper on the actual column and also have to convert the input to lower/upper before passing to the query accordingly,

select * 
  from news 
 where lower(newsletter_description) like '%watermelon%' 
    or lower(newsletter_description) like '%apple%'
    or lower(title) like '%watermelon%' 
    or lower(title) like '%apple%';
    
2
pixel On

You can use « lower(title) like '%apple%' » In fact the lower put all the field in minuscule, that help you to find the word needed without knowing how he is written

0
swang41 On

Naive way will be select * from new where lower(title) like ‘%apple%’ or lower(title) like ‘%watermelon%’ or lower(newsletter_description) like ‘%apple%’ or lower(newsletter_description) like ‘%watermelon%’;

0
forpas On

Use a CTE that returns all the words that you search for and join it to the table:

with cte(word) as (values ('apple'), ('watermelon'))
select n.*
from news n inner join (select '%' || word || '%' word from cte) c
on n.title like c.word or n.newsletter_description like c.word