Our SQLAlchemy journey thus far has covered managing database connections and model creation. Yet, how do we extract the data we want from our database?
SQLAlchemy's ORM query API simplifies the way we write database queries. Instead of writing raw SQL queries, we can construct queries on our SQLAlchemy session by chaining together methods to retrieve data. We're going to dive into SQLAlchemy's extensive query API to get an idea of all the ways we can query our data.
Create a Session
We covered SQLAlchemy session creation in the previous post and explained the concept of engines in the post before that. If you skipped those posts, don't. The below is copy+pasta courtesy:
Basic Query Syntax
Let's quickly become familiar with the basic structure of SQLAlchemy's query API. SQLAlchemy session objects have a
query() method that accepts the raw class of a data model we've previously defined. Below are the humble beginnings of a query to run on
Customer model; or in other words, a query on the customers SQL table:
.query(Customer) on our session isn't a valid query until we add one more method to the chain. All session queries end with a final method to shape/anticipate the result(s) of our query:
all()will return all records which match our query as a list of objects. If we were to use all on the query above, we would receive all customer records with the Python data type
first()returns the first record matching our query, despite how many records match the query (what constitutes "first" depends on how your table is sorted). This is the equivalent of adding
LIMIT 1to a SQL query. As a result, the Python type to be returned would be
one()is extremely useful for cases where a maximum of one record should exist for the query we're executing (think of querying by primary key). This syntax is notably useful when verifying whether or not a record exists prior to creating one.
scalar()returns a single value if one exists, None if no values exist, or raises an exception if multiple records are returned.
get([VALUE(S)])searches against a model's primary key to return rows where the primary key is equal to the value provided.
get()also accepts tuples in the event that multiple foreign keys should be searched. Lastly,
get()can also accept a dictionary and return rows where the columns (dictionary keys) match the values provided.
To create more complex queries, we'd add to our query by chaining methods on our original query:
If we execute a query that returns multiple records, we'll need to loop through them to see the results:
The SQLAlchemy ORM will return an instance of a class by default, which means the above will result in the following output:
If you're looking to get dictionaries instead, use the built-in
This instead returns dictionary objects for each row:
Of course, you could also create your own object instead to receive only the columns you want/need:
This outputs something a bit cleaner:
Probably the most common method you'll use on a query is the
filter() is the equivalent of a SQL WHERE clause to return only rows that match the criteria we want:
We could write the above query using the
filter_by() method instead like so:
filter_by() accepts keyword arguments (note the difference in syntax here:
filter() checks a conditional against a column object whereas
filter_by() finds columns which match the arguments we pass).
filter_by() can only search for exact values and serves as a kind of shorthand for simple filtering queries.
We can do more than filter on simple conditionals. SQLAlchemy has a
like() method which works in an equivalent manner to SQL's
As expected, this will give us all rows where the customer's first name starts with a J:
High-level Query Methods
In addition to
filter(), there are a few basic methods we should be familiar with. Each of these corresponds to SQL keywords you're probably familiar with:
limit([INTEGER]): Limits the number of rows to a maximum of the number provided.
order_by([COLUMN]): Sorts results by the provided column.
offset([INTEGER]): Begins the query at row n.
This next part involves executing JOIN queries between models, which requires us to define relationships on our models first. Things are a bit out of order at the moment, as I actually don't cover this until the next post. Sorry for the mess, I'm working on it!
Performing JOINs & UNIONs
We've touched on JOINs a bit previously, but we're about to kick it up a notch. We have two data models we're working with: one for customers, and one for orders. Each customer
We perform our JOIN using the
join() method. The first parameter we pass is the data model we'll be joining with on the "right." We then specify what we'll be joining "on": the customer_id column of our order model, and the id column of our customer model.
Our outer loop gives us each customer, and our inner loop adds each order to the appropriate customer. Check out an example record:
Our friend Jerry here has two orders: one for some Coronas, and another for creamers. Get at it, Jerry.
In addition to simple JOINs, we can perform outer JOINs using the same syntax:
We can perform UNIONs and UNION ALLs as well:
To perform a union all, simply replace
Aggregate Functions and Stats
As with all SQL-like query languages, we can perform some aggregate stats as well. The following are available to us:
count([COLUMN]): Counts the number of records in a column.
count(distinct([COLUMN])): Counts the distinct number of records in a column.
sum([COLUMN]): Adds the numerical values in a column.
Here's how we'd perform a query that counts the values in a column:
This query can easily be modified to only count distinct values:
Of course, we can use the
group_by() method on queries based on aggregates as well.
group_by() works similarly to what we'd expect from SQL and Pandas:
We've spent an awful lot of time going over how to extract data from our database, but haven't talked about modifying our data yet! The last item on our agenda today is looking at how to add, remove, and change records using the SQLAlchemy ORM.
The first way we can add data is by using the
add() expects an instance of a class (data model specifically) to be passed, and will create a new database row as a result:
An alternative way to add data is by using the
insert() method. Unlike
insert() is called on an SQLAlchemy Table object and doesn't rely on receiving a data model.
insert() is not part of the ORM:
Building on the syntax of
insert(), we can drop in the
update() method to change an existing record's values. We chain in the
where() method to specify which rows should be updated:
On any query we execute, we can append the
delete() method to delete all rows which are contained in that query (be careful!). The below deletes all records where the first_name column contains a value of "Carl":
delete() accepts the synchronize_session parameter, which determines how deletions should be handled:
Falsewon't perform the delete until the session is committed.
'fetch'selects all rows to be deleted and removes matched rows.
'evaluate'will evaluate the objects in the current session to determine which rows should be removed.
Never Stop Exploring™
There's a lot we've left out for the sake of simplicity. There are plenty of cool methods left to explore, like the
correlate() method, for instance. You're armed with enough to be dangerous in SQLAlchemy now, but I encourage anybody to look over the query documentation and find the cool things we didn't speak to in detail here.
I'm still working on throwing together the source code for this post in the Github repo below. The source for the previous chapters can be found there as well. In the meantime, I apologize for being a bit of a shit show: