hi,
i have two entities products and categories. both have many-to-many relation. how can i get the products that are not related with the categories. i mean the ones which not not mapped in junction table.

thank you!
daniyal nawaz

Dani AI

Generated

Two common approaches have already been suggested by (subquery) and (outer join). Both find products with no mapping, but there are practical differences to watch for. The safest, null-safe pattern is a correlated NOT EXISTS check; it avoids the NULL-trap of NOT IN and is easy to read and index.

Here is a concise, robust example — pick the exact columns you need instead of *:

SELECT p.product_id, p.name
FROM products p
WHERE NOT EXISTS (
  SELECT 1
  FROM junction_table j
  WHERE j.product_id = p.product_id
);

Performance and correctness tips:

  • Ensure junction_table.product_id is indexed. For example, add an index if needed: CREATE INDEX idx_junction_product ON junction_table(product_id);
  • Use EXPLAIN to compare plans for the NOT EXISTS and the left-join variants on your data. On large tables the optimizer choice and available indexes determine which is faster.
  • Avoid NOT IN if the subquery can ever return NULL values — that makes the predicate behave unexpectedly. If product_id is declared NOT NULL with a foreign key, NOT IN is safer, but NOT EXISTS is still preferable for clarity.
  • Prefer listing required columns instead of SELECT * to reduce I/O.

If the goal is "not related to a particular category (or set of categories)," constrain the subquery on category_id accordingly. Also verify referential integrity (no stray NULL keys) before relying on NOT IN logic.

Recommended Answers

All 2 Replies

SELECT * FROM products WHERE product_id NOT IN (SELECT DISTINCT product_id FROM junction_table)

Try this :

select products .*,junction_table.product_id from products 
left outer join junction_table
  on junction_table.product_id=products .product_id
having junction_table.product_id is null
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.