PyPika

0.51.1 · active · verified Thu Apr 09

PyPika is a SQL query builder API for Python, allowing users to construct SQL queries programmatically. It supports various SQL dialects like PostgreSQL, MySQL, Oracle, and Redshift, and even JQL. The library is actively maintained, with frequent patch and minor releases, currently at version 0.51.1.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to construct basic SELECT queries, including filtering with WHERE, using aggregate functions, and performing JOINs and GROUP BY clauses using PyPika's fluent API.

from pypika import Query, Table, Field
from pypika import functions as fn

customers = Table('customers')
orders = Table('orders')

# Basic SELECT statement
q1 = Query.from_(customers).select(customers.id, customers.name, customers.email)
print(f"\nBasic Select:\n{q1.get_sql()}")

# Select with WHERE clause and function
q2 = Query.from_(orders).select(orders.id, orders.amount).where(orders.amount > 100)
print(f"\nSelect with WHERE:\n{q2.get_sql()}")

# Select with JOIN and GROUP BY
q3 = Query.from_(customers).join(orders).on(customers.id == orders.customer_id) \
    .groupby(customers.name).select(customers.name, fn.Sum(orders.amount))
print(f"\nSelect with JOIN and GROUP BY:\n{q3.get_sql()}")

view raw JSON →