CRUD Operations
Query and execute.
CRUD Operations is a free Learn Rust Coding lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
CRUD with sqlx
CRUD means Create, Read, Update, Delete. sqlx splits these into two execution styles:
fetch_*for queries that return rowsexecutefor statements that change data
Create (INSERT)
Insert a row with bound parameters and run it via execute. Use RETURNING to get the generated id back.
use sqlx::{Pool, Postgres};
async fn create(pool: &Pool<Postgres>, name: &str) -> i32 {
let rec = sqlx::query!(
"INSERT INTO users (name) VALUES ($1) RETURNING id",
name
).fetch_one(pool).await.unwrap();
rec.id
}Read one row
fetch_one expects exactly one row and errors otherwise. Use fetch_optional when the row may be absent.
use sqlx::{Pool, Postgres};
async fn find(pool: &Pool<Postgres>, id: i32) -> Option<String> {
let rec = sqlx::query!("SELECT name FROM users WHERE id = $1", id)
.fetch_optional(pool)
.await
.unwrap();
rec.map(|r| r.name)
}Read many rows
fetch_all returns a Vec of all matching rows.
use sqlx::{Pool, Postgres};
async fn all_names(pool: &Pool<Postgres>) -> Vec<String> {
let rows = sqlx::query!("SELECT name FROM users ORDER BY id")
.fetch_all(pool)
.await
.unwrap();
rows.into_iter().map(|r| r.name).collect()
}Update
UPDATE statements use execute, which returns a result carrying the number of affected rows.
use sqlx::{Pool, Postgres};
async fn rename(pool: &Pool<Postgres>, id: i32, name: &str) -> u64 {
let res = sqlx::query!("UPDATE users SET name = $1 WHERE id = $2", name, id)
.execute(pool)
.await
.unwrap();
res.rows_affected()
}Delete
DELETE also uses execute. Check rows_affected() to know whether anything was removed.
use sqlx::{Pool, Postgres};
async fn delete(pool: &Pool<Postgres>, id: i32) -> bool {
let res = sqlx::query!("DELETE FROM users WHERE id = $1", id)
.execute(pool)
.await
.unwrap();
res.rows_affected() > 0
}Modeling CRUD in plain Rust
CRUD against an in-memory map mirrors the same operations sqlx performs against a table.
use std::collections::HashMap;
fn main() {
let mut users: HashMap<i32, String> = HashMap::new();
users.insert(1, "Alice".to_string()); // create
println!("{:?}", users.get(&1)); // read
users.insert(1, "Alicia".to_string()); // update
println!("{:?}", users.get(&1));
users.remove(&1); // delete
println!("{:?}", users.get(&1));
}Transactions
Group multiple statements atomically with a transaction. Either all succeed on commit or none apply.
use sqlx::{Pool, Postgres};
async fn transfer(pool: &Pool<Postgres>) {
let mut tx = pool.begin().await.unwrap();
sqlx::query!("UPDATE acct SET bal = bal - 10 WHERE id = 1")
.execute(&mut *tx).await.unwrap();
sqlx::query!("UPDATE acct SET bal = bal + 10 WHERE id = 2")
.execute(&mut *tx).await.unwrap();
tx.commit().await.unwrap();
}Rolling back
If a transaction guard is dropped without commit, sqlx rolls back automatically. You can also call rollback explicitly.
use sqlx::{Pool, Postgres};
async fn maybe(pool: &Pool<Postgres>, ok: bool) {
let mut tx = pool.begin().await.unwrap();
sqlx::query!("INSERT INTO log (msg) VALUES ('x')").execute(&mut *tx).await.unwrap();
if ok { tx.commit().await.unwrap(); } else { tx.rollback().await.unwrap(); }
}Streaming large reads
For huge result sets, fetch returns a stream so you process rows without loading them all into memory.
use sqlx::{Pool, Postgres};
use futures::TryStreamExt;
async fn stream(pool: &Pool<Postgres>) {
let mut rows = sqlx::query!("SELECT id FROM big_table").fetch(pool);
while let Some(row) = rows.try_next().await.unwrap() {
println!("id {}", row.id);
}
}Handling errors
Database calls return Result. Propagate with ? in functions returning Result<_, sqlx::Error> instead of unwrapping.
use sqlx::{Pool, Postgres};
async fn count(pool: &Pool<Postgres>) -> Result<i64, sqlx::Error> {
let rec = sqlx::query!("SELECT COUNT(*) as n FROM users")
.fetch_one(pool)
.await?;
Ok(rec.n.unwrap_or(0))
}Quick Check
Test your understanding of CRUD operations.
Recap
You learned CRUD with sqlx:
fetch_one,fetch_optional,fetch_allread rowsexecutechanges data and reportsrows_affected()RETURNINGretrieves generated values- Transactions with
begin/commit/rollbackensure atomicity
Next: migrations to evolve the schema.
Frequently asked questions
Is the “CRUD Operations” lesson free?
Yes — the full text of “CRUD Operations” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “CRUD Operations”?
Query and execute. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “CRUD Operations” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.