Python Practice › SQLite Programs › Program 12

Customers without orders

EasySQLite Programs · 12 of 20

Write a Python program to find customers who have not placed any order.

Advertisement
Output
[('Meena',), ('Ravi',)]

Approach

  1. LEFT JOIN and check for NULL.

Solution

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

More sqlite programs

← All 20 SQLite Programs

Leave a Comment