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!

asked Nov 30, 2018 at 17:33

1 Answer 1

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.).

Akina
20.8k2 gold badges20 silver badges22 bronze badges
answered Nov 30, 2018 at 18:10

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.