Proper use of `get_by!`/`get_by` when querying column with unique_constraint & unique_index

Greetings,

I’m a beginner with an “idiomatic”/“best practice” question.

Let’s say you have a schema with the following in place:

  • Ecto schema with a field called :sku
  • Ecto changeset that invokes unique_constraint on :sku for inserts/updates
  • Ecto migration that applies create unique_index to :sku

It is my understanding that this would prevent a duplicate :sku from entering the database at both the code level and the database level. Is this correct? If so, then would calling get_by! be redundant/unecessary for “must be unique” queries or would it still be considered best practice for “should never happen” scenarios even with code & db protections in place?

Thanks!

Both get_by! And get_by will raise if you return multiple records. The difference is that ! will also raise if there are NO records, and get_by will return nil.

Your index will prevent the duplicates, but duplicates aren’t where those two functions behave differently.

2 Likes

Thank you for your answer!