Phoenix/Elixir: Chain Composable Queries with Ecto Named Bindings.

Photo by Karine Avetisyan on Unsplash

What are composable queries?

Composable queries are a way of building queries to your database such that you can combine them.

Composable Queries

Query methods like join, select, and where take in a query and return another query.

Pipe-based syntax

Pipe-based syntax in Ecto composes queries together, passing the query through a series of query methods. Here’s an example using multiple join calls to add the author, comments, and tags for a list of posts:

Positional Bindings.

Notice that when you call the join method and attach another schema such as Author or Comment onto the post, the binding for the post’s comment and author are based on the position in the list.

Chain Composable Queries.

The goal is to create reusable and chainable methods by extracting common queries you make into their own method. When I say chain, I mean that you can call the extracted query methods in a pipe chain like so:

Named Bindings

You can solve the problem of positional bindings by using named bindings. Where positional bindings are bound to the next position in a list, named bindings allow you to set their name. Like so:


You learned about composable Ecto queries using the Pipe-based syntax. You learned how to extract those composable Ecto queries into separate methods, and you learned how to use named bindings to deal with the position conflicts caused by positional bindings.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Brooklin Myers

Brooklin Myers


Software Engineer. I create educational content focused on technology for mobile and web applications.