Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select specific items in IN sql

I have a table "products" with a column called "store_id".
This table has a lot af products from many stores.
I need to select 4 ramdom products from 4 specific stores (id: 1, 34, 45, 100).
How can I do that?

I’ve tried to like this:

SELECT * FROM products WHERE store_id IN (1, 34, 45, 100)

But that query returns duplicated records (by store_id).
I need the following result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

store_id title
1 title a
34 title b
45 title c
100 title d

>Solution :

Use the DISTINCT construct to get unique records for the desired column:

SELECT distinct on (store_id) store_id, title FROM products WHERE store_id IN (1, 34, 45, 100);

Demo in sqldaddy.io

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading