SQL Builders: Order

Episode #318 • Mar 24, 2025 • Subscriber-Only

We add sorting to our SQL builder, which will give us a powerful, succinct syntax for controlling the order of results. We will start small but build up to parameter packs and even a custom result builder to get the most flexibility out of our API.

Collection
SQL Building
SQL Builders: Order
Locked

Unlock This Episode

Our Free plan includes 1 subscriber-only episode of your choice, plus weekly updates from our newsletter.

Sign in with GitHub

Introduction

Stephen

We now have the basics of a query builder library implemented, and it already is more powerful than probably any Swift SQL library out there. It is capable of expressing complex selections from a table, including columns, aggregates, and even subqueries. And best of all, we are able to leverage some of Swift’s most advanced features, such as key paths, macros and variadic generics, to provide a lot of type safety and static checks that give us a lot of confidence we are writing valid SQL statements.

But there is still a lot more functionality in a SQL SELECT statement that we need to support. You can filter rows from a SELECT by using a WHERE clause with complex predicate logic. You can join multiple tables together so that you can cross reference data between tables. You can group aggregate results together, like if you wanted to select all tags along with a count of the number of reminders assigned to each tag. And a lot more.

Brandon

But for right now we are going to concentrate on ordering. Once you have performed a select you will typically have a big list of rows, and you often want to order those rows in particular manner. SQL has great support for sorting, allowing you to sort by any number of fields in any direction, and you can even perform computations in the ordering, such as sorting a text column by ignoring the case of characters.

Let’s first see what SQL has to offer when it comes to ordering, and then see how we can recreate all of it in our query builder.

Ordering in SQL


References

Downloads

Get started with our free plan

Our free plan includes 1 subscriber-only episode of your choice, access to 71 free episodes with transcripts and code samples, and weekly updates from our newsletter.

View plans and pricing