6.21. SQL Select Subquery
IN (SELECT ...)
- subquery
6.21.1. Subqueries
SELECT *
FROM astronauts
WHERE agency IN (
SELECT name FROM agencies);
SELECT *
FROM astronauts
WHERE career IN (
SELECT name FROM job_names);
SELECT *
FROM logs
WHERE level in (
SELECT level
FROM logs
GROUP BY level
HAVING COUNT(*) > 5
);
6.21.2. Assignments
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: Database Subquery In
# - Difficulty: easy
# - Lines: 2
# - Minutes: 3
# %% English
# 1. Write SQL query to select data:
# - table: `users`
# - columns: `firstname`, `lastname`
# - where: has 2 or more members
# - use: subquery
# 2. Run doctests - all must succeed
# %% Polish
# 1. Napisz zapytanie SQL aby wybrać dane:
# - tabela: `users`
# - kolumny: `firstname`, `lastname`
# - gdzie: mająca 2 lub więcej członków
# - użyj: podzapytania
# 2. Uruchom doctesty - wszystkie muszą się powieść
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> from pprint import pprint
>>> from pathlib import Path
>>> import sqlite3
>>> database = Path(__file__).parent.parent / 'shop.db'
>>> with sqlite3.connect(database) as db:
... db.row_factory = sqlite3.Row
... data = map(dict, db.execute(result).fetchall())
>>> pprint(list(data), sort_dicts=False, width=79)
[{'firstname': 'Mark', 'lastname': 'Watney'},
{'firstname': 'Melissa', 'lastname': 'Lewis'},
{'firstname': 'Rick', 'lastname': 'Martinez'},
{'firstname': 'Beth', 'lastname': 'Johanssen'},
{'firstname': 'Chris', 'lastname': 'Beck'}]
"""
# Write SQL query to select data:
# - table: `users`
# - columns: `firstname`, `lastname`
# - where: has 2 or more members
# - use: subquery
# type: str
result = """
SELECT `firstname`, `lastname`
FROM `users`
WHERE `group`
"""
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: Database Subquery CTE
# - Difficulty: easy
# - Lines: 2
# - Minutes: 3
# %% English
# 1. Write SQL query to select data:
# - table: `users`
# - columns: `firstname`, `lastname`
# - where: has 2 or more members
# - use: CTE - Common Table Expression
# 2. Run doctests - all must succeed
# %% Polish
# 1. Napisz zapytanie SQL aby wybrać dane:
# - tabela: `users`
# - kolumny: `firstname`, `lastname`
# - gdzie: mająca 2 lub więcej członków
# - użyj: CTE - Common Table Expression
# 2. Uruchom doctesty - wszystkie muszą się powieść
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> from pprint import pprint
>>> from pathlib import Path
>>> import sqlite3
>>> database = Path(__file__).parent.parent / 'shop.db'
>>> with sqlite3.connect(database) as db:
... db.row_factory = sqlite3.Row
... data = map(dict, db.execute(result).fetchall())
>>> pprint(list(data), sort_dicts=False, width=79)
[{'firstname': 'Mark', 'lastname': 'Watney'},
{'firstname': 'Melissa', 'lastname': 'Lewis'},
{'firstname': 'Rick', 'lastname': 'Martinez'},
{'firstname': 'Beth', 'lastname': 'Johanssen'},
{'firstname': 'Chris', 'lastname': 'Beck'}]
"""
# Write SQL query to select data:
# - table: `users`
# - columns: `firstname`, `lastname`
# - where: has 2 or more members
# - use: CTE - Common Table Expression
# type: str
result = """
SELECT `firstname`, `lastname`
FROM `users`
WHERE `group` IN (
SELECT `group`
FROM `users`
GROUP BY `group`
HAVING COUNT(`group`) >= 2
)
"""