LEFT JOIN with NULL result rows
📖 Scenario: You are managing a small online bookstore database. You have two tables: books and sales. The books table lists all books available, and the sales table records sales transactions for some of these books. Some books may not have any sales yet.
🎯 Goal: Write a SQL query using LEFT JOIN to list all books along with their sales count. For books with no sales, the sales count should show as NULL.
📋 What You'll Learn
Create a table called
books with columns book_id (integer) and title (text).Create a table called
sales with columns sale_id (integer) and book_id (integer).Insert exactly these rows into
books: (1, 'The Great Gatsby'), (2, '1984'), (3, 'To Kill a Mockingbird').Insert exactly these rows into
sales: (101, 1), (102, 1), (103, 3).Write a
LEFT JOIN query to join books with sales on book_id.Select
books.book_id, books.title, and the count of sales.sale_id as sales_count.Group the results by
books.book_id and books.title.Ensure that books with no sales show
sales_count as NULL (do not replace with zero).💡 Why This Matters
🌍 Real World
Online stores often need to report all products with their sales, including those with no sales yet. LEFT JOIN helps show all products even if no sales exist.
💼 Career
Understanding LEFT JOIN and handling NULL results is essential for database querying in roles like data analyst, backend developer, and database administrator.
Progress0 / 4 steps