SQLite Where
Filter Rows
Use WHERE to select only the rows that match a condition.
The examples on this page use this players table:
| name | score |
|---|---|
| Emil | 120 |
| Tobias | 95 |
| Linus | 150 |
| Lene | 80 |
To keep the examples short, they show only the code for the SELECT statement. Click "Try it Yourself" to see the complete code, which also creates the table and adds the rows.
Example
Select the players with a score greater than 100:
cur.execute("""
SELECT * FROM players
WHERE score > 100
""")
for row in cur.fetchall():
print(row)
Try it Yourself »
Operators
You can use these operators in a WHERE condition:
| Operator | Description |
|---|---|
| = | Equal |
| != | Not equal |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal |
| <= | Less than or equal |
Note: In SQL, equal is written with one =. In Python, it is written with two: ==.
Find Text
Text values are written in single quotes:
Example
Select the player named Linus:
cur.execute("""
SELECT * FROM players
WHERE name = 'Linus'
""")
print(cur.fetchall())
Try it Yourself »
Use a Value From a Variable
Use a ? placeholder, like you learned in the SQLite Insert chapter:
Example
Select the player with the name in the variable name:
name = "Linus"
cur.execute(
"SELECT * FROM players WHERE name = ?",
(name,)
)
print(cur.fetchall())
Try it Yourself »
Note: The values must be a tuple, even if there is only one value. A tuple with one value needs a comma: (name,). Without the comma, (name) is just a string in parentheses, and you get an error.
AND and OR
Use AND when both conditions must be true, and OR when one of them is enough:
Example
Select the players with a score between 90 and 130:
cur.execute("""
SELECT * FROM players
WHERE score > 90 AND score < 130
""")
for row in cur.fetchall():
print(row)
Try it Yourself »
Search With LIKE
Use LIKE to search for a pattern in text. The % sign means any number of characters:
Example
Select the players whose name starts with L:
cur.execute("""
SELECT * FROM players
WHERE name LIKE 'L%'
""")
for row in cur.fetchall():
print(row)
Try it Yourself »
'L%' matches text that starts with L, and '%s' matches text that ends with s.
In SQLite, LIKE does not care about upper and lower case for the English letters, so 'l%' gives the same result.