Most applications fall into a category called “CRUD” apps. CRUD stands for “Create, Read, Update, Delete”. Diesel provides support for all four pieces, but in this guide we’re going to look at the different ways to go about creating INSERT statements.

The examples for this guide are going to be shown for PostgreSQL, but you can follow along with any backend. The full code examples for all backends are linked at the bottom of this guide.

An insert statement always starts with insert_into. The first argument to this function is the table you’re inserting into.

For this guide, our schema will look like this:

Since our functions are going to only operate on the users table, we can put use schema::users::dsl::*; at the top of our function, which will let us write insert_into(users) instead of insert_into(users::table). If you’re importing table::dsl::*, make sure it’s always inside a function, not the top of your module.

If all of the columns on a table have a default, the simplest thing we can do is call .default_values. We could write a function that ran that query like this:

It’s worth noting that this code will still compile, even if you don’t have default values on all of your columns. Diesel will ensure that the value you’re assigning has the right type, but it can’t validate whether the column has a default, any constraints that could fail, or any triggers that could fire.

We can use debug_query to inspect the generated SQL. The exact SQL that is generated may differ depending on the backend you’re using. If we run println!("{}", debug_query::<Pg, _>(&our_query));, we’ll see the following:

If we want to actually provide values, we can call .values instead. There are a lot of different arguments we can provide here. The simplest is a single column/value pair using .eq.

This will generate the following SQL:

If we want to provide values for more than one column, we can pass a tuple.

This will generate the following SQL:

Insertable

Working with tuples is the typical way to do an insert if you just have some values that you want to stick in the database. But what if your data is coming from another source, like a web form deserialized by Serde? It’d be annoying to have to write (name.eq(user.name), hair_color.eq(user.hair_color)).

Diesel provides the Insertable trait for this case. Insertable maps your struct to columns in the database. We can derive this automatically by adding #[derive(Insertable)] to our type.

This will generate the same SQL as if we had used a tuple.

If one of the fields is None, the default value will be inserted for that field.

That will generate the following SQL:

Batch Insert

If we want to insert more than one row at a time, we can do that by passing a &Vec or slice of any of the forms used above. Keep in mind that you’re always passing a reference here.

On backends that support the DEFAULT keyword (all backends except SQLite), the data will be inserted in a single query. On SQLite, one query will be performed per row.

For example, if we wanted to insert two rows with a single value, we can just use a Vec.

Which generates the following SQL:

Note that on SQLite, you won’t be able to use debug_query for this, since it doesn’t map to a single query. You can inspect each row like this:

If we wanted to use DEFAULT for some of our rows, we can use an option here.

Note that the type here is Option<Eq<Column, Value>> not Eq<Column, Option<Value>>. Doing column.eq(None) would insert NULL not DEFAULT. This generates the following SQL:

We can do the same thing with tuples.

Which generates the following SQL:

Once again, we can use an Option for any of the fields to insert DEFAULT.

Which generates the following SQL:

Finally, Insertable structs can be used for batch insert as well.

This generates the same SQL as if we had used a tuple:

The RETURNING Clause

On backends that support the RETURNING clause (such as PostgreSQL), we can get data back from our insert as well. MySQL and SQLite do not support RETURNING clauses. To get back all of the inserted rows, we can call .get_results instead of .execute.

Given this struct:

We can use get_results with this test:

To inspect the SQL generated by .get_results or .get_result, we will need to call .as_query before passing it to debug_query. The query in the last test generates the following SQL:

You’ll notice that we’ve never given an explicit value for created_at and updated_at in any of our examples. With Diesel, you typically won’t set those values in Rust. Typically these columns get set with DEFAULT CURRENT_TIMESTAMP, and a trigger is used to change updated_at on updates. If you’re using PostgreSQL, you can use a built-in trigger by running SELECT diesel_manage_updated_at('users'); in a migration.

If we expect one row instead of multiple, we can call .get_result instead of .get_results.

This generates the same SQL as get_results:

Finally, if we only want a single column back, we can call .returning() explicitly. This code would return the inserted ID:

Which generates the following SQL:

“Upsert”

Every type of insert statement covered in this guide can also be used for “insert or update” queries, also known as “upsert”. The specifics of upsert are covered extensively in the API documentation.

For PostgreSQL, see the pg::upsert module. For MySQL and SQLite, upsert is done via REPLACE. See replace_into for details.

Diesel does not have support for MySQL’s ON DUPLICATE KEY conflict, as its results are non-deterministic, and unsafe with replication.

Conclusion

While there are a lot of examples in this guide, ultimately the only difference between various kinds of insert statements is the argument passed to .values.

All examples in this guide are run as part of Diesel’s test suite. You can find the full code examples for each backend at these links: