Filtering and targeting data

Introduction to Databases in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Where clauses

stmt = select([census])

stmt = stmt.where(census.columns.state == 'California')
results = connection.execute(stmt).fetchall()
for result in results: print(result.state, result.age)
California 0
California 1
California 2
California 3
California 4
California 5
...
Introduction to Databases in Python

Where clauses

  • Restrict data returned by a query based on Boolean conditions
  • Compare a column against a value or another column
  • Often use comparisons ==, <=, >=, or !=
Introduction to Databases in Python

Expressions

  • Provide more complex conditions than simple operators
  • E.g.in_(), like(), between()
  • Many more in documentation
  • Available as method on a Column
Introduction to Databases in Python

Expressions

stmt = select([census])

stmt = stmt.where(census.columns.state.startswith('New'))
for result in connection.execute(stmt): print(result.state, result.pop2000)
New Jersey 56983
New Jersey 56686
New Jersey 57011
...
Introduction to Databases in Python

Conjunctions

  • Allow us to have multiple criteria in a where clause
  • Eg. and_(), or_(), not_()
Introduction to Databases in Python

Conjunctions

from sqlalchemy import or_

stmt = select([census])
stmt = stmt.where( or_(census.columns.state == 'California', census.columns.state == 'New York' ) )
for result in connection.execute(stmt): print(result.state, result.sex)
New York M
...
California F
Introduction to Databases in Python

Let's practice!

Introduction to Databases in Python

Preparing Video For Download...