I have two tables with the following setup:
category: (id, name)
item: (id, name, category_id) - category_id is foreign key to category table
Now I am writing a query to retrieve a subset from the category table of only used categories:
SELECT c.id, c.name
FROM category c
WHERE c.id IN (SELECT DISTINCT category_id FROM item)
The above query works fine. I’m just wondering if this is the most optimal way of doing the query or if there’s something else that I could do via a join or something
Transforming the
IN (SELECT)toEXISTS (SELECT ... WHERE )might help:Another possibility (I expect it to be slower, but it always depends on your db):
Or you could use
DISTINCTinstead ofGROUP BY:And if speed is that important, don’t forget to call
ANALYZEfrom time to time:http://www.sqlite.org/lang_analyze.html
Some other variants for fun:
Another: