Python Practice › SQLite Programs › Program 12
Customers without orders
Write a Python program to find customers who have not placed any order.
Output
[('Meena',), ('Ravi',)]Approach
LEFT JOINand check for NULL.
Solution
import sqlite3 conn = sqlite3.connect(":memory:")conn.executescript(""" CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT); CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER); INSERT INTO customers VALUES (1, 'Asha'), (2, 'Ravi'), (3, 'Meena'); INSERT INTO orders VALUES (10, 1), (11, 1);""")print(conn.execute("""SELECT c.name FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL ORDER BY c.name""").fetchall())Output
[('Meena',), ('Ravi',)]Learn the concept
New to this topic? Read the lesson, then come back.