Using Subquery with IN Operator in SQL
📖 Scenario: You work at a bookstore that keeps two tables: books and orders. The books table has details about each book, and the orders table records which books customers have ordered.You want to find all books that have been ordered at least once.
🎯 Goal: Build an SQL query using a subquery with the IN operator to list all books that appear in the orders.
📋 What You'll Learn
Create a table called
books with columns book_id (integer) and title (text).Create a table called
orders with columns order_id (integer) and book_id (integer).Insert the exact data into
books: (1, 'The Great Gatsby'), (2, '1984'), (3, 'To Kill a Mockingbird'), (4, 'Moby Dick').Insert the exact data into
orders: (101, 2), (102, 3), (103, 2).Write a SELECT query to find all books where
book_id is in the list of book_ids from orders using a subquery with the IN operator.💡 Why This Matters
🌍 Real World
Bookstores and many businesses use subqueries with IN to find related records across tables, like finding products that have sales.
💼 Career
Knowing how to write subqueries with IN is a fundamental SQL skill for data analysts, database developers, and backend engineers.
Progress0 / 4 steps