1

A bit of a noob question, but would appreciate the help.

I want to use the result of one select statement in a different one in a specific way.

The first select statemnent:

SELECT DISTINCT id FROM customers WHERE country = 'Neverland';

The result will be a one-column table with distinct IDs. Now I want to select all these IDs from a different table.

SELECT * FROM shipments WHERE [the id is contained within the first select statement]

Thanks!

1

The easy answer would be to combine both queries, directly, using subqueries (IN). So, assuming the column on shipments is also called id (substitute it with the real name, if different):

SELECT * 
FROM shipments 
WHERE id IN ( SELECT DISTINCT id 
              FROM customers 
              WHERE country = 'Neverland')

It may be nice to learn a bit about JOINs, while those may seem more complicated at first, they may have in some cases a better query plan or logically less complex once you learn about those:

SELECT *
FROM shipments
JOIN customers
ON shipments.id = customers.id
WHERE shipments.country = 'Neverland'

(again, you may need to adapt it to the particular column names, and cardinality relation- show no duplicate shipments, etc.).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.