Working with hierarchical tables

Introduction to Databases in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Hierarchical tables

  • Contain a relationship with themselves
  • Commonly found in:
    • Organizational
    • Geographic
    • Network
    • Graph
Introduction to Databases in Python

Hierarchical tables - example

hierarchical_table.jpg

Introduction to Databases in Python

Hierarchical tables - alias()

  • Requires a way to view the table via multiple names
  • Creates a unique reference that we can use
Introduction to Databases in Python

Querying hierarchical data

managers = employees.alias()

stmt = select( [managers.columns.name.label('manager'), employees.columns.name.label('employee')])
stmt = stmt.select_from(employees.join( managers, managers.columns.id == employees.columns.manager)
stmt = stmt.order_by(managers.columns.name)
print(connection.execute(stmt).fetchall())
[(u'FILLMORE', u'GRANT'),
 (u'FILLMORE', u'ADAMS'),
 (u'HARDING', u'TAFT'), ...
Introduction to Databases in Python

group_by and func

  • It's important to target group_by() at the right alias
  • Be careful with what you perform functions on
  • If you don't find yourself using both the alias and the table name for a query, don't create the alias at all
Introduction to Databases in Python

Querying hierarchical data

managers = employees.alias()

stmt = select([managers.columns.name, func.sum(employees.columns.sal)])
stmt = stmt.select_from(employees.join( managers, managers.columns.id == employees.columns.manager)
stmt = stmt.group_by(managers.columns.name) print(connection.execute(stmt).fetchall())
[(u'FILLMORE', Decimal('96000.00')),
 (u'GARFIELD', Decimal('83500.00')),
 (u'HARDING', Decimal('52000.00')),
 (u'JACKSON', Decimal('197000.00'))]
Introduction to Databases in Python

Let's practice!

Introduction to Databases in Python

Preparing Video For Download...