Databases with SQLite · 2 / 15 Theory

Querying data with SELECT

SELECT is the SQL command you will use the most. The examples in this article use this products table:

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE products (name TEXT, price INTEGER, category TEXT)")
con.executemany("INSERT INTO products VALUES (?, ?, ?)", [
    ("bread", 2, "food"), ("milk", 3, "food"), ("pencil", 1, "stationery"),
    ("notebook", 4, "stationery"), ("wine", 12, "drinks"),
])

print(con.execute("SELECT COUNT(*) FROM products").fetchone()[0])   # 5

Choosing columns and filtering with WHERE

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE products (name TEXT, price INTEGER, category TEXT)")
con.executemany("INSERT INTO products VALUES (?, ?, ?)", [
    ("bread", 2, "food"), ("milk", 3, "food"), ("pencil", 1, "stationery"),
    ("notebook", 4, "stationery"), ("wine", 12, "drinks"),
])

print(con.execute("SELECT name, price FROM products WHERE price >= 3 ORDER BY price").fetchall())
# [('milk', 3), ('notebook', 4), ('wine', 12)]

print(con.execute("SELECT name FROM products WHERE category = 'food' AND price < 3").fetchall())
# [('bread',)]

print(con.execute("SELECT * FROM products WHERE name = 'wine'").fetchall())
# [('wine', 12, 'drinks')]

Useful conditions: =, <> (different), <, >, <=, >=, combined with AND, OR and NOT. Note that SQL writes = (not ==) and texts go between single quotes. For values that come from the user, always use ? parameters (article 3). Practise with Filter by price.

IN, BETWEEN, LIKE and IS NULL

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE products (name TEXT, price INTEGER, category TEXT)")
con.executemany("INSERT INTO products VALUES (?, ?, ?)", [
    ("bread", 2, "food"), ("milk", 3, "food"), ("pencil", 1, "stationery"),
    ("notebook", 4, "stationery"), ("wine", 12, "drinks"),
])

def names(sql):
    return [f[0] for f in con.execute(sql)]

print(names("SELECT name FROM products WHERE category IN ('drinks', 'stationery') ORDER BY name"))
# ['notebook', 'pencil', 'wine']
print(names("SELECT name FROM products WHERE price BETWEEN 2 AND 4 ORDER BY name"))
# ['bread', 'milk', 'notebook']
print(names("SELECT name FROM products WHERE name LIKE 'p%' ORDER BY name"))
# ['pencil']
print(names("SELECT name FROM products WHERE category IS NULL"))
# []
  • IN (a, b, c): the value is one of the list.
  • BETWEEN a AND b: between two values, including the ends.
  • LIKE 'p%': the text starts with p. % stands for any number of characters and _ for exactly one. In SQLite it is not case-sensitive for ASCII letters.
  • IS NULL / IS NOT NULL: to check whether the value is missing (= NULL does not work).

Sorting with ORDER BY

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE products (name TEXT, price INTEGER, category TEXT)")
con.executemany("INSERT INTO products VALUES (?, ?, ?)", [
    ("bread", 2, "food"), ("milk", 3, "food"), ("pencil", 1, "stationery"),
    ("notebook", 4, "stationery"), ("wine", 12, "drinks"),
])

print(con.execute("SELECT name, price FROM products ORDER BY price DESC").fetchall())
# [('wine', 12), ('notebook', 4), ('milk', 3), ('bread', 2), ('pencil', 1)]

print(con.execute("SELECT name, category FROM products ORDER BY category, price DESC").fetchall())
# [('wine', 'drinks'), ('milk', 'food'), ('bread', 'food'), ('notebook', 'stationery'), ('pencil', 'stationery')]

ASC (the default) sorts from lowest to highest and DESC from highest to lowest. You can give several columns: the second breaks ties of the first. Texts are sorted by character code, so uppercase letters come before lowercase ones.

Paging with LIMIT and OFFSET

LIMIT n returns at most n rows and OFFSET k skips the first k. Together they are used for paging: page p of size s starts at OFFSET (p - 1) * s.

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE products (name TEXT, price INTEGER, category TEXT)")
con.executemany("INSERT INTO products VALUES (?, ?, ?)", [
    ("bread", 2, "food"), ("milk", 3, "food"), ("pencil", 1, "stationery"),
    ("notebook", 4, "stationery"), ("wine", 12, "drinks"),
])

print(con.execute("SELECT name, price FROM products ORDER BY price DESC LIMIT 2").fetchall())
# [('wine', 12), ('notebook', 4)]

page, size = 2, 2
print(con.execute("SELECT name, price FROM products ORDER BY price DESC LIMIT ? OFFSET ?", (size, (page - 1) * size)).fetchall())
# [('milk', 3), ('bread', 2)]

It is what Paged ranking does. Always use a complete ORDER BY (with a tiebreaker) so that pages are stable.

DISTINCT and named rows

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE products (name TEXT, price INTEGER, category TEXT)")
con.executemany("INSERT INTO products VALUES (?, ?, ?)", [
    ("bread", 2, "food"), ("milk", 3, "food"), ("pencil", 1, "stationery"),
    ("notebook", 4, "stationery"), ("wine", 12, "drinks"),
])

print(con.execute("SELECT DISTINCT category FROM products ORDER BY category").fetchall())
# [('drinks',), ('food',), ('stationery',)]

con.row_factory = sqlite3.Row      # rows can be read by column name
row = con.execute("SELECT name, price FROM products ORDER BY price DESC LIMIT 1").fetchone()
print(row["name"], row["price"])   # wine 12
print(dict(row))                   # {'name': 'wine', 'price': 12}

DISTINCT removes duplicates. With row_factory = sqlite3.Row each row behaves like a tuple and like a dictionary, which makes the code more readable.