CRUD DELETE

Learn how a DELETE handler removes one user row from Postgres with sqlx and returns 204 when the row is gone and 404 when it never existed

A DELETE handler that removes a user takes an id from the URL, deletes that row from the users table, and answers 204 with an empty body. When no row has that id, the handler answers 404. Deleting is the only handler in this cluster that returns no body at all, because the resource is gone, and there is nothing left to show.

Where This Fits

The create handler adds rows, the read handlers fetch them, and the update handlers change them. This page adds the last of the four operations: removing a row for good. It takes the id from the path, like the single-row read, and it runs a DELETE instead of a SELECT. It also introduces the one check the other handlers never needed: counting how many rows the statement removed, because a DELETE that matches nothing must answer 404, not success.

Think of a shredder at the clinic desk. A patient asks for a file to be destroyed, the clerk finds the file by its number, feeds it through the shredder, and hands back nothing, because the file no longer exists. A request for a number with no file gets a plain answer that there is nothing to shred. The empty hand is the 204, and the plain answer is the 404.

The Smallest Working Version

Create a project with these files. It has one route, DELETE /users/{id}, and nothing else.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.9", features = ["runtime-tokio", "postgres", "macros", "derive"] }

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

The sqlx line needs four features. runtime-tokio runs sqlx on the Tokio runtime, postgres adds the Postgres driver, macros turns on the query! macro used below, and derive is listed for consistency with the other handlers, though this handler needs no FromRow struct. The tower dev-dependency is only for the test near the end of this page.

src/errors.rs
use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde_json::json;

#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
            AppError::ValidationError(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
            AppError::InternalError => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "something went wrong".to_string(),
            ),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}

impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> Self {
        match error {
            sqlx::Error::RowNotFound => AppError::NotFound,
            other => {
                eprintln!("database error: {other}");
                AppError::InternalError
            }
        }
    }
}
src/db.rs
use sqlx::{PgPool, postgres::PgPoolOptions};

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await
}
src/handlers.rs
use axum::{
    extract::{Path, State},
    http::StatusCode,
};
use sqlx::PgPool;

use crate::errors::AppError;

pub async fn delete_user(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
) -> Result<StatusCode, AppError> {
    let result = sqlx::query!("DELETE FROM users WHERE id = $1", id)
        .execute(&pool)
        .await?;
    if result.rows_affected() == 0 {
        return Err(AppError::NotFound);
    }
    Ok(StatusCode::NO_CONTENT)
}
src/lib.rs
pub mod db;
pub mod errors;
pub mod handlers;

use axum::{Router, routing::delete};
use handlers::delete_user;
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/users/{id}", delete(delete_user))
        .with_state(pool)
}
src/main.rs
use axum_project::{app, db::create_pool};

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url)
        .await
        .expect("failed to connect to the database");
    let router = app(pool);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, router).await.unwrap();
}

Create the table and one row before running the server:

psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" -c "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW());"
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" -c "TRUNCATE users RESTART IDENTITY;"
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" -c "INSERT INTO users (name, email) VALUES ('Asha', 'asha@example.com');"

The TRUNCATE line empties the table and resets the id sequence to 1, so the row inserted afterwards gets id 1 and the outputs below match. Run it whenever an earlier page already left rows in the table.

Start the server with the connection string in the environment:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" cargo run

The terminal prints Server running at http://127.0.0.1:3000 and waits. In a second terminal, delete the user with id 1:

curl -i -X DELETE http://127.0.0.1:3000/users/1

The server answers with status 204 and an empty body. There is no JSON, no message, and no content-length of anything but zero, because the resource is gone and there is nothing to describe:

HTTP/1.1 204 No Content

Confirm the row is gone by asking for it:

curl -i http://127.0.0.1:3000/users/1

That route does not exist in this smallest project, which only registers the DELETE route, so the answer is a 404 from Axum itself. Check the table directly instead:

psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" -c "SELECT id, name, email FROM users;"
 id | name | email
----+------+-------
(0 rows)

Delete the same id again, and the handler answers 404 with the shared error body, because the row is already gone:

curl -i -X DELETE http://127.0.0.1:3000/users/1
HTTP/1.1 404 Not Found
content-type: application/json
content-length: 30

{"error":"resource not found"}

Working Setup:

If the first DELETE prints a bare 204 with no body, the table shows zero rows, and the second DELETE prints a 404, the handler works end to end. The row was removed, the empty result was answered with silence, and the missing row was answered instead of pretending the delete succeeded.

Understanding the Handler Line by Line

The handler is the shortest in the cluster, and it has no request body and no response body. Its two new pieces are the execute finisher and the row-count check, and both exist because a DELETE returns no rows.

The two extractors

pub async fn delete_user(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
) -> Result<StatusCode, AppError> {

State(pool) pulls the connection pool from router state, and Path(id) parses the {id} part of the URL into an i32. There is no Json extractor, because a DELETE request carries no body. The return type is Result<StatusCode, AppError>, a status code on success and an AppError on failure, with no body type at all. That return type is the whole reason the response is empty: there is no Json value to serialize.

The DELETE with execute

    let result = sqlx::query!("DELETE FROM users WHERE id = $1", id)
        .execute(&pool)
        .await?;

sqlx::query! is the macro that checks a query at compile time and returns an anonymous record, a value whose fields are decided by the query rather than by a named struct. A DELETE returns no columns, so there is no struct to decode rows into, and query! is the right macro for it. execute is the finisher that runs the statement and returns a result holding the number of affected rows, dropping any returned rows. It is the finisher for statements that change data without returning it, which is INSERT without RETURNING, UPDATE without RETURNING, and DELETE. The ? converts a database failure into an AppError through the shared mapping.

The row-count check

    if result.rows_affected() == 0 {
        return Err(AppError::NotFound);
    }
    Ok(StatusCode::NO_CONTENT)
}

rows_affected is a method on the execute result that reports how many rows the statement changed. A DELETE that matches a row reports 1, and a DELETE that matches nothing reports 0. The handler checks that count itself, because execute never fails on an empty match. Deleting nothing is a successful statement from the database's point of view, and only the handler knows the client expected a row to be there. The if turns a zero count into NotFound, which becomes the 404, and a count of 1 falls through to StatusCode::NO_CONTENT, which is 204.

This check is the one place in the cluster where the handler, not the query finisher, decides that a missing row is a 404. The read and update handlers get that decision from fetch_one and its RowNotFound error. The delete handler cannot use fetch_one, because a DELETE returns no rows to fetch, so it reads the count instead. Same answer, different mechanism, and the reason is the shape of what the statement returns.

Execute Never Fails on Zero Rows:

A beginner sometimes assumes execute fails when nothing matches, the way fetch_one fails on no rows. It does not. execute reports success with a count of zero, and the handler must read that count. Forgetting the check makes every DELETE answer 204, including deletes of ids that never existed, and the client can never tell whether anything was actually removed.

The Concept Behind 204 No Content

Status 204 means the request succeeded and there is deliberately no body. It is the status for operations whose whole point is removal. A 200 with an empty body would also work mechanically, but 204 says something 200 does not: the emptiness is intentional, not a missing body. A client that receives 204 knows not to wait for bytes, not to parse a body, and not to treat the lack of content as an error. A client that receives 200 with no body has to guess whether the server forgot the body or meant to send none.

The 204 also fits the resource. After a DELETE, the user no longer exists, so there is no user to serialize. Returning the deleted row in the body is possible in Postgres, with DELETE ... RETURNING, and some APIs do it, but the common shape is silence. The client asked for the row to be gone, the row is gone, and the empty 204 is the confirmation.

A beginner can think of 204 as the nod after a shredder. The clerk does not hand back a copy of the shredded file, and does not write a receipt describing it. The nod says it is done, and the absence of paper says there is nothing left to hand over.

Why the Second DELETE Answers 404

Deleting the same id twice answers 204 the first time and 404 the second time. That difference is deliberate, and it follows from the row count. The first DELETE removes the row, so the count is 1. The second DELETE finds nothing, so the count is 0, and the handler reports the row as missing. The client learns that the row is already gone, which is useful information: a retry that answers 404 tells the client the first request already landed, instead of leaving it unsure.

Some APIs answer 204 for a delete of a missing row, on the grounds that the end state is the same either way: the row is gone. That shape is also defensible, and it makes retries silent. This app answers 404, because its error contract treats "the resource named in the URL does not exist" the same way in every handler, and a DELETE is no exception. The choice is a design decision, and the app makes it once, in this handler, the same way the read and update handlers make it.

Delete Is Idempotent in Effect, Not in Status:

Sending the same DELETE twice leaves the table in the same state, because the row is gone after the first one and there is nothing left to remove. The status differs, 204 then 404, because the second request found nothing to delete. The data is idempotent even when the status is not, and a client that retries a DELETE should accept either status as proof the row is gone.

A Richer Complete Example

The smallest version deletes one user. A realistic session deletes a user, lists the survivors, and deletes a missing id, showing how the table changes and how the handler answers each case. Seed three rows first, with the full app running, the one that registers every route:

psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" -c "INSERT INTO users (name, email) VALUES ('Asha', 'asha@example.com'), ('Ravi', 'ravi@example.com'), ('Meera', 'meera@example.com');"

Delete the middle user:

curl -i -X DELETE http://127.0.0.1:3000/users/2
HTTP/1.1 204 No Content

List the survivors, and the deleted row is gone while the other two keep their ids:

curl http://127.0.0.1:3000/users
[{"id":1,"name":"Asha","email":"asha@example.com"},{"id":3,"name":"Meera","email":"meera@example.com"}]

The ids are 1 and 3, with no row numbered 2. Deleting a row never renumbers the survivors, and the sequence never reuses the deleted id. A later insert gets id 4, not id 2, because the sequence counts upward and never looks back.

Delete a missing id, and the answer is the 404 from the smallest example. The table does not change, because there was nothing to remove, and the other rows are untouched. A DELETE affects exactly the rows its WHERE clause matches, and a clause that matches nothing changes nothing.

The DELETE with RETURNING Variation

Postgres can return the deleted row, the same way it returns an inserted or updated row. The handler below answers 200 with the deleted user instead of 204 with nothing, and it shows the trade-off between the two shapes.

src/handlers.rs
use axum::Json;
use serde::Serialize;
use sqlx::FromRow;

#[derive(Debug, Serialize, FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
}

pub async fn delete_user_returning(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
) -> Result<Json<User>, AppError> {
    let user = sqlx::query_as!(
        User,
        "DELETE FROM users WHERE id = $1 RETURNING id, name, email",
        id
    )
    .fetch_one(&pool)
    .await?;
    Ok(Json(user))
}

Two things changed. The SQL gained RETURNING id, name, email, and the call changed from query! with execute to query_as! with fetch_one. The missing-row check moved from the row count into fetch_one, which fails with RowNotFound when the DELETE matches nothing, and the shared mapping turns that into a 404. The response is 200 with the deleted user, which lets the client show a message like "Asha was deleted" or offer an undo.

This version is useful when the client needs the deleted values, for a confirmation screen or an audit log. The 204 version is the common default, because most clients only need to know the delete succeeded. Pick the shape the client actually uses, and do not return a row the client throws away.

What Happens Without the WHERE Clause

A DELETE without a WHERE clause removes every row in the table. The statement below compiles, runs, and empties the table in one step, and the handler would then answer 204, because rows_affected would be the number of rows that were there, which is not zero. There is no warning, no confirmation, and no undo.

// Wrong - every row in the table is deleted
let result = sqlx::query!("DELETE FROM users")
    .execute(&pool)
    .await?;

The WHERE id = $1 clause is the only thing standing between a single-row delete and a whole-table wipe. Read it before running any DELETE, and never write a DELETE in a handler without one. The compile-time check cannot catch a missing WHERE, because the SQL is valid without it. Only the reader can. In a real app, a delete endpoint is also the place where a confirmation step, a permission check, or a soft delete belongs, and none of those live in the SQL itself.

A DELETE Without WHERE Empties the Table:

The most dangerous line on this page is a DELETE with no WHERE clause. It compiles, it runs, and it removes every row. The WHERE id = $1 clause is the only guard, and the compiler cannot check for it. Before running any DELETE, read the statement and confirm the WHERE names the id from the path.

The Request Flow

The path of a delete request through the app looks like this:

Client sends DELETE /users/1
        |
        v
Axum parses 1 from the path into an i32
        |
        v
Handler runs DELETE ... WHERE id = $1
        |
        +-- database failure --> 500 with {"error": "something went wrong"}
        |
        v
Postgres removes the row and reports how many rows changed
        |
        +-- 0 rows --> 404 with {"error": "resource not found"}
        |
        v
Handler returns 204 with an empty body

The decision point sits after the database answers, not inside the query. The handler reads the count, and the count decides the status. Every other handler in the cluster decides earlier, through fetch_one, and the delete handler is the exception because its statement returns no rows.

Testing the DELETE Handler

The test below inserts a row, deletes it through the router, and checks the 204. A second test deletes a missing id and checks the 404, and a third test deletes a row and then reads the table to prove the row is gone.

tests/delete_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use axum_project::{app, db::create_pool};
use tower::ServiceExt;

async fn pool() -> sqlx::PgPool {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    create_pool(&database_url).await.unwrap()
}

async fn seed(pool: &sqlx::PgPool) -> i32 {
    sqlx::query!("DELETE FROM users").execute(pool).await.unwrap();
    sqlx::query!("INSERT INTO users (name, email) VALUES ('Asha', 'asha@example.com')")
        .execute(pool)
        .await
        .unwrap();
    sqlx::query!("SELECT id FROM users WHERE email = 'asha@example.com'")
        .fetch_one(pool)
        .await
        .unwrap()
        .id
}

#[tokio::test]
async fn delete_user_returns_204_and_removes_the_row() {
    let pool = pool().await;
    let id = seed(&pool).await;
    let router = app(pool.clone());
    let response = router
        .oneshot(
            Request::builder()
                .method("DELETE")
                .uri(format!("/users/{id}"))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NO_CONTENT);
    let count: i64 = sqlx::query_scalar!("SELECT COUNT(*) FROM users")
        .fetch_one(&pool)
        .await
        .unwrap()
        .unwrap_or(0);
    assert_eq!(count, 0);
}

#[tokio::test]
async fn delete_missing_user_returns_404() {
    let pool = pool().await;
    let router = app(pool);
    let response = router
        .oneshot(
            Request::builder()
                .method("DELETE")
                .uri("/users/999999")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

The first test uses pool.clone() because the router takes ownership of the pool, and the test still needs the pool afterwards to count the rows. PgPool is cheap to clone, because the clone shares the same connections underneath. query_scalar! is a macro that fetches a single value, here the row count, instead of a whole row. Run them with the database URL set:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" cargo test -- --test-threads=1
test delete_user_returns_204_and_removes_the_row ... ok
test delete_missing_user_returns_404 ... ok

The --test-threads=1 flag runs the tests one at a time. The tests share one table, and running them at the same time could make one test delete rows another test is reading.

Common Beginner Mistakes

Returning 200 with a message body

// Wrong - the client asked for removal, not a message about removal
Ok((StatusCode::OK, Json(json!({ "message": "deleted" }))))

A 200 with a message body works, and it is the shape many beginners reach for, because a message feels friendlier than silence. The cost is a body the client must parse for no information: the message says only what the status already said. The 204 is the standard answer for a delete, and clients written against it expect no body. Use 204, and let the empty response be the confirmation.

Checking rows_affected with the wrong comparison

// Wrong - a delete that removed two rows would also be treated as missing
if result.rows_affected() != 1 {
    return Err(AppError::NotFound);
}

The WHERE id = $1 clause plus the primary key guarantee that at most one row can match, so != 1 and == 0 agree in practice. The == 0 check states the intent directly: nothing was deleted, so the row was missing. The != 1 check states a different intent, that exactly one row must change, and it would mislabel a future change, like a WHERE clause that matches several rows, as a missing resource. Write the check that names the case it handles.

Forgetting that delete is permanent

A DELETE removes the row from the table, and Postgres has no undo for it outside a backup. There is no recycle bin, no trash folder, and no "deleted" flag unless the table has one. A beginner who tests a delete handler against a database with real data loses that data. Test deletes against a throwaway database, seed the rows the test needs, and never point a delete handler at data a person cares about until the handler is proven.

Test Deletes Against a Throwaway Database:

The tests on this page run DELETE FROM users to clear the table before seeding. That statement empties the table in one step. Run it only against a database that holds nothing important, and keep the test database separate from any database with real users in it.

Checking That Everything Compiles

Before running cargo run, run cargo check. The query! macro needs the database at compile time, so DATABASE_URL must be set for the check as well as for the run:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" cargo check

If the output ends with a Finished line and no errors, there are no type errors, and the SQL passed the compile-time check against the real table. Then run cargo run to start the server.

Final Complete Example

Here is everything from this page put together. The project has one route, one handler, and the shared error and pool files.

src/errors.rs
use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde_json::json;

#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
            AppError::ValidationError(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
            AppError::InternalError => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "something went wrong".to_string(),
            ),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}

impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> Self {
        match error {
            sqlx::Error::RowNotFound => AppError::NotFound,
            other => {
                eprintln!("database error: {other}");
                AppError::InternalError
            }
        }
    }
}
src/db.rs
use sqlx::{PgPool, postgres::PgPoolOptions};

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await
}
src/handlers.rs
use axum::{
    extract::{Path, State},
    http::StatusCode,
};
use sqlx::PgPool;

use crate::errors::AppError;

pub async fn delete_user(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
) -> Result<StatusCode, AppError> {
    let result = sqlx::query!("DELETE FROM users WHERE id = $1", id)
        .execute(&pool)
        .await?;
    if result.rows_affected() == 0 {
        return Err(AppError::NotFound);
    }
    Ok(StatusCode::NO_CONTENT)
}
src/lib.rs
pub mod db;
pub mod errors;
pub mod handlers;

use axum::{Router, routing::delete};
use handlers::delete_user;
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/users/{id}", delete(delete_user))
        .with_state(pool)
}
src/main.rs
use axum_project::{app, db::create_pool};

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url)
        .await
        .expect("failed to connect to the database");
    let router = app(pool);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, router).await.unwrap();
}

Run it with:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" cargo run

Then delete a user with:

curl -i -X DELETE http://127.0.0.1:3000/users/1

Summary

A delete handler is the shortest handler in the cluster, and its brevity hides the one decision that matters: a DELETE that matches nothing is a 404, not a success. The statement returns no rows, so the handler reads the affected-row count instead of fetching a row, and the count decides the status. A count of 1 becomes a 204 with an empty body, because the resource is gone and there is nothing left to show. A count of 0 becomes a 404, because the resource named in the URL never existed.

The decision to carry forward is about what the client learns from the status. A 204 says the row is gone, and the client can move on. A 404 says the row was already gone, and the client learns its first request already landed. Both answers are useful, and neither needs a body. The danger in a delete handler is never the response shape. It is the WHERE clause, which is the only thing standing between one deleted row and an empty table, and it deserves a read before every run.