Calculating values in a query

Introduction to Databases in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Math operators

  • addition +
  • subtraction -
  • multiplication *
  • division /
  • modulus %
  • Work differently on different data types
Introduction to Databases in Python

Calculating difference

stmt = select([census.columns.age,           
        (census.columns.pop2008 -
        census.columns.pop2000).label('pop_change')
    ])

stmt = stmt.group_by(census.columns.age) stmt = stmt.order_by(desc('pop_change'))
stmt = stmt.limit(5)
results = connection.execute(stmt).fetchall() print(results)
[(61, 52672), (85, 51901), (54, 50808), (58, 45575),
(60, 44915)]
Introduction to Databases in Python

Case statement

  • Used to treat data differently based on a condition
  • Accepts a list of conditions to match and a column to return if the condition matches
  • The list of conditions ends with an else clause to determine what to do when a record doesn't match any prior conditions
Introduction to Databases in Python

Case example

from sqlalchemy import case

stmt = select([ func.sum( case([ (census.columns.state == 'New York', census.columns.pop2008) ], else_=0))])
results = connection.execute(stmt).fetchall() print(results)
[(19465159,)]
Introduction to Databases in Python

Cast statement

  • Converts data to another type
  • Useful for converting...
    • integers to floats for division
    • strings to dates and times
  • Accepts a column or expression and the target Type
Introduction to Databases in Python

Percentage example

from sqlalchemy import case, cast, Float

stmt = select([ (func.sum( case([ (census.columns.state == 'New York', census.columns.pop2008) ], else_=0)) / cast(func.sum(census.columns.pop2008), Float) * 100).label('ny_percent')])
results = connection.execute(stmt).fetchall() print(results)
[(Decimal('6.4267619765'),)]
Introduction to Databases in Python

Let's practice!

Introduction to Databases in Python

Preparing Video For Download...