Full answer
CREATE TABLE baskets_bad (id INTEGER PRIMARY KEY, product_ids TEXT);
INSERT INTO baskets_bad VALUES (1, '1,2'), (2, '10,11'), (3, '11,12');
CREATE TABLE basket_items (basket_id INTEGER, product_id INTEGER, PRIMARY KEY (basket_id, product_id));
INSERT INTO basket_items VALUES (1,1),(1,2),(2,10),(2,11),(3,11),(3,12);Searching the list for product 1 with LIKE matches too much:
SELECT id, product_ids FROM baskets_bad WHERE product_ids LIKE '%1%' ORDER BY id;| id | product_ids |
|---|---|
| 1 | 1,2 |
| 2 | 10,11 |
| 3 | 11,12 |
A join table answers the same question exactly:
SELECT basket_id FROM basket_items WHERE product_id = 1 ORDER BY basket_id;| basket_id |
|---|
| 1 |
Counting how many baskets contain each product is an ordinary GROUP BY on the join table:
SELECT product_id, COUNT(*) AS baskets FROM basket_items GROUP BY product_id ORDER BY baskets DESC, product_id;| product_id | baskets |
|---|---|
| 11 | 2 |
| 1 | 1 |
| 2 | 1 |
| 10 | 1 |
| 12 | 1 |
The LIKE query returns all three baskets, although only the first one contains product 1; the other two hold products such as 10, 11 and 12, whose text happens to include a '1'. Wrapping the list in commas and searching for ',1,' fixes this particular case but still cannot use an index, cannot enforce that ids exist, and gets worse when the list is edited, sorted or counted. The join table makes every one of those operations a plain query, lets the database reject unknown products through the foreign key, and allows extra columns on the relationship, such as quantity. When a list is only ever stored and displayed as a whole and never queried, an array or JSON column is a defensible shortcut, but membership searches then need the right index, such as GIN in PostgreSQL.
CREATE TABLE baskets_bad (id INTEGER PRIMARY KEY, product_ids TEXT);
INSERT INTO baskets_bad VALUES (1, '1,2'), (2, '10,11'), (3, '11,12');
CREATE TABLE basket_items (basket_id INTEGER, product_id INTEGER, PRIMARY KEY (basket_id, product_id));
INSERT INTO basket_items VALUES (1,1),(1,2),(2,10),(2,11),(3,11),(3,12);
SELECT id, product_ids FROM baskets_bad WHERE product_ids LIKE '%1%' ORDER BY id;
SELECT basket_id FROM basket_items WHERE product_id = 1 ORDER BY basket_id;
SELECT product_id, COUNT(*) AS baskets FROM basket_items GROUP BY product_id ORDER BY baskets DESC, product_id;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- LIKE on a list matches substrings
- No foreign keys or indexes on list items
- Join table gives one row per pair
- Composite primary key prevents duplicates
- Arrays or JSON suit store-and-display only
Common mistakes
- Splitting lists in application code for every query
- Fixing substring matches with more string tricks
Follow-ups
- How would you migrate existing lists into a join table?
- When is a PostgreSQL array column acceptable?
Tips
- Run the LIKE query before explaining the model