Get Values Back

Learn about the values returned by queries in Ecto.

Return value of queries

In each of the examples we’ve seen so far, Ecto returns a tuple. This is the standard return value for the *_all functions.

  • The first item in the tuple is the number of records affected by the operation.
  • The second item contains the values that we asked the database to return. We haven’t been using that option so far, so we keep getting nil. Let’s try it now.

The returning option lets us specify any values we’d like returned to us after the operation completes. This option takes a list of the field names we’re interested in and Ecto returns the values as a map.

Note: This option works in Postgres but not in MySQL.

Example

To try this out, let’s go back to inserting new records. When we first set up our database, we made the id column the primary key, and we asked the database to assign these IDs automatically. We can use returning to have Ecto show us the IDs after inserting the records.

Get hands-on with 1200+ tech skills courses.