Introduction
Imagine you have a big table full of information, but you only want to see a few specific columns. The projection operation helps you pick just those columns you need from a database table, making the data easier to understand and use.
Imagine you have a large photo album with many pictures, but you want to create a smaller album showing only the faces of people. You cut out just the faces from each photo and paste them into a new album, ignoring the backgrounds and other details.
┌───────────────┐ │ Original Table│ │───────────────│ │ ID │ Name │ Age│ │ 1 │ Anna │ 25 │ │ 2 │ Bob │ 30 │ │ 3 │ Anna │ 25 │ └────┴──────┴────┘ ↓ Projection (select Name) ┌───────────────┐ │ Projected Set │ │───────────────│ │ Name │ │ Anna │ │ Bob │ └───────────────┘
import sqlite3 conn = sqlite3.connect(':memory:') cur = conn.cursor() cur.execute('CREATE TABLE people (id INTEGER, name TEXT, age INTEGER)') cur.execute("INSERT INTO people VALUES (1, 'Anna', 25)") cur.execute("INSERT INTO people VALUES (2, 'Bob', 30)") cur.execute("INSERT INTO people VALUES (3, 'Anna', 25)") cur.execute('SELECT DISTINCT name FROM people') for row in cur.fetchall(): print(row[0])