INSERT with RETURNING

Learn how the Postgres RETURNING clause gives an insert handler the new row back in the same statement, including its database generated id

The RETURNING clause turns an INSERT into a statement that both writes a row and hands it back. Without it, an insert tells the handler only how many rows changed, and the handler must run a second query to learn the id Postgres assigned. With it, one statement does both jobs: the row is written, and the written row comes back, id included, in the same round trip.

Where This Fits

The last page showed how query! reads rows, and its examples only ever selected rows that already existed. Creating a row is the other half of that picture. The handler still uses query!, still binds values with $1 placeholders, and still reads the result as an anonymous record. The only new idea is the RETURNING list at the end of the INSERT, which makes the database send the new row back instead of staying silent about it.

Think of it like a coat check that hands you a ticket. You hand over the coat, and in the same motion you receive the ticket that identifies it. You do not walk away and come back later to ask which ticket belongs to your coat. The INSERT is handing over the coat, and RETURNING is the ticket coming back in the same motion.

The Smallest Working Version

The smallest example is one handler that creates a user and returns the created user with status 201. It builds on the project from the last page: the same users table, the same pool module, the same error type, and the same .env file with DATABASE_URL.

The project needs these dependencies:

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

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

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

The error type is unchanged from the last page. A missing row becomes NotFound, and any other database error becomes InternalError after being written to the server log:

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
            }
        }
    }
}

The pool module is unchanged:

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
}

The handler takes the new user as JSON, checks the input, inserts the row, and returns the row Postgres sends back:

src/handlers.rs
use axum::{
    Json,
    extract::State,
    http::StatusCode,
};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;

use crate::errors::AppError;

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

#[derive(Debug, Deserialize)]
pub struct CreateUser {
    pub name: String,
    pub email: String,
}

fn valid_email(email: &str) -> bool {
    let Some((local, domain)) = email.split_once('@') else {
        return false;
    };
    !local.is_empty() && domain.contains('.')
}

fn check_user_input(name: &str, email: &str) -> Result<(), AppError> {
    if name.trim().is_empty() {
        return Err(AppError::ValidationError(
            "name must not be empty".to_string(),
        ));
    }
    if !valid_email(email) {
        return Err(AppError::ValidationError(
            "email must look like name@example.com".to_string(),
        ));
    }
    Ok(())
}

pub async fn create_user(
    State(pool): State<PgPool>,
    Json(input): Json<CreateUser>,
) -> Result<(StatusCode, Json<User>), AppError> {
    check_user_input(&input.name, &input.email)?;
    let row = sqlx::query!(
        "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id, name, email",
        input.name,
        input.email
    )
    .fetch_one(&pool)
    .await?;
    Ok((
        StatusCode::CREATED,
        Json(User {
            id: row.id,
            name: row.name,
            email: row.email,
        }),
    ))
}

The library wires the route, and main builds the pool and serves:

src/lib.rs
pub mod db;
pub mod errors;
pub mod handlers;

use axum::{
    Router,
    routing::post,
};
use handlers::create_user;
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/users", post(create_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 the database up:

DATABASE_URL=postgres://postgres:password@127.0.0.1:5432/ch12_depth cargo run

Create a user:

curl -X POST http://127.0.0.1:3000/users \
  -H "content-type: application/json" \
  -d '{"name":"Asha","email":"asha@example.com"}'

The response carries status 201 and the row exactly as the database stored it, including the id Postgres generated:

{"id":1,"name":"Asha","email":"asha@example.com"}

Send the same email again, and the insert fails, because the email column is UNIQUE. With the error conversion as it stands on this page, that failure becomes a 500 with the shared shape:

curl -i -X POST http://127.0.0.1:3000/users \
  -H "content-type: application/json" \
  -d '{"name":"Asha Again","email":"asha@example.com"}'
HTTP/1.1 500 Internal Server Error
{"error":"something went wrong"}

That 500 is honest but unhelpful: the client sent a duplicate email, and the server answers as if something broke inside. Turning that specific database failure into a 409 is the subject of its own page later in this cluster. For now, notice that the failure happens inside the same query! call, and the ? operator is what carries it out of the handler.

Working Setup:

If the first curl prints {"id":1,"name":"Asha","email":"asha@example.com"} with status 201, the insert ran, RETURNING sent the row back, and the handler returned the database generated id. The id is the proof: the client never sent it, so it could only have come from Postgres.

Understanding the INSERT Call Line by Line

The handler has three parts worth slowing down for: the input check, the statement itself, and the 201 return. The input check is familiar from the validation pages, so the new material is the statement and the return.

The RETURNING list

"INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id, name, email",

An INSERT names the table, the columns to fill, and the values for those columns. The RETURNING clause comes last, and it lists the columns Postgres should send back from the row it just wrote. It behaves like the column list of a SELECT that runs on the new row: any column of the table can be listed, including generated ones like id and defaulted ones like created_at, and the values are the stored values, not the values the client sent. The macro checks this list at compile time like any other part of the SQL, so a misspelled column in RETURNING is a compile error, not a run time surprise.

The columns named in RETURNING decide the shape of the anonymous record. Listing id, name, email produces a record with exactly those three fields, which is why the handler can build a User from it. Listing * would return every column, including created_at, which the User struct does not hold and the macro cannot decode without a date and time crate feature. List the columns the response needs, and no others.

Why fetch_one fits an insert

.fetch_one(&pool)
.await?;

An INSERT with RETURNING always produces exactly one row: the row it inserted. There is no zero-rows case, because the statement either inserts the row or fails. fetch_one is the right method for that shape, and the ? converts a failure, such as a duplicate email, into AppError on the way out. Using fetch_optional here would compile, but it would be misleading: the None case could never happen, and the reader would wonder when it does.

The 201 return

Ok((
    StatusCode::CREATED,
    Json(User {
        id: row.id,
        name: row.name,
        email: row.email,
    }),
))

The handler returns a tuple, a status code paired with a JSON body, inside a Result. Axum knows how to turn that tuple into a response, and the status code is part of the value, not a separate setting. 201 Created is the status that means a new resource exists now, and the body is the resource itself. Returning 200 here would work mechanically, but it would tell the client the wrong story: 200 means the request succeeded, while 201 means the request succeeded and something new was created. Clients and their libraries read that distinction, so the handler should say what actually happened.

RETURNING Reads the Stored Row:

The values in the returned row are the values Postgres stored, after defaults and any database-side changes. The id comes from the SERIAL sequence, and created_at would come from its NOW() default. When a column has a default the client does not send, RETURNING is the only way the handler learns the stored value without a second query.

The Concept Behind RETURNING

Without RETURNING, an insert and a read are two separate statements, and two statements can disagree. Between the insert and the read, another request could change the row, the read could use a different key and find the wrong row, or the row could be deleted outright. The handler would then return stale or missing data for a row it just created. RETURNING closes that gap by making the write and the read one statement. Postgres inserts the row and reads the same row back inside the same statement, so nothing can happen in between.

A beginner should think of it as asking the database to show its work. The database already holds the new row the moment the insert finishes. RETURNING asks it to show that row before moving on, instead of making the handler ask again in a separate trip. One statement, one round trip, one consistent answer.

A Second SELECT Can Return the Wrong Row:

Reading the new row back with a second query keyed on email looks correct, and usually is, until two requests insert the same email at nearly the same time. One of them fails on the unique constraint, but the other reads back a row that may be the one it inserted or may be a row inserted a moment earlier by someone else. The RETURNING form never has this problem, because the row it returns is the row the statement inserted.

Why One Statement Beats Two

The two-statement form costs a second round trip to the database, which is slower, but speed is the smaller reason. The larger reason is correctness under concurrency, the situation where two requests run at the same time. A web server handles many requests at once, and two creates for different users can overlap in time. Each statement on its own is safe, but the pair is not atomic: the database can interleave other work between them.

The single-statement form removes the interleaving entirely. There is no gap for other work to slip into, because there is only one statement. The row returned is the row inserted, every time, no matter how many requests run at once. That guarantee is worth more than the saved round trip, and it is the reason RETURNING is the standard way to write a create handler in Postgres.

A Richer Complete Example

A create handler rarely lives alone. The reader usually creates a user and then reads it back, so here the create handler sits next to the read handler from the last page, sharing the same User struct and the same routes file. The two handlers together show the full create-and-read loop.

Add the read handler to src/handlers.rs:

src/handlers.rs
pub async fn get_user(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
) -> Result<Json<User>, AppError> {
    let row = sqlx::query!(
        "SELECT id, name, email FROM users WHERE id = $1",
        id
    )
    .fetch_one(&pool)
    .await?;
    Ok(Json(User {
        id: row.id,
        name: row.name,
        email: row.email,
    }))
}

Wire both routes in src/lib.rs:

src/lib.rs
pub mod db;
pub mod errors;
pub mod handlers;

use axum::{
    Router,
    routing::{get, post},
};
use handlers::{create_user, get_user};
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/users", post(create_user))
        .route("/users/{id}", get(get_user))
        .with_state(pool)
}

Create a user, read the id from the response, and fetch the same user back:

curl -X POST http://127.0.0.1:3000/users \
  -H "content-type: application/json" \
  -d '{"name":"Ben","email":"ben@example.com"}'
{"id":2,"name":"Ben","email":"ben@example.com"}
curl http://127.0.0.1:3000/users/2
{"id":2,"name":"Ben","email":"ben@example.com"}

The two responses match field for field. That match is the point: the row the create handler returned is the row the database stored, and the read handler proves it by fetching the same row from scratch. When those two responses disagree, the create handler is returning something it invented instead of something the database stored, and RETURNING is the fix.

Returning Only the id

Sometimes the client needs the new id and nothing else, for example when it redirects to the new resource right after creating it. Listing a single column in RETURNING returns a record with a single field, and the handler can return just that number.

src/handlers.rs
pub async fn create_user_id(
    State(pool): State<PgPool>,
    Json(input): Json<CreateUser>,
) -> Result<(StatusCode, Json<i32>), AppError> {
    check_user_input(&input.name, &input.email)?;
    let row = sqlx::query!(
        "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id",
        input.name,
        input.email
    )
    .fetch_one(&pool)
    .await?;
    Ok((StatusCode::CREATED, Json(row.id)))
}

The response body is a bare number, 3, instead of a user object. The shape of the RETURNING list decides the shape of the record, and the record decides what the handler can return. A beginner should treat the RETURNING list like a SELECT list: it is the contract for what comes back, and changing it changes the record type the macro generates.

The Struct Form With query_as

The anonymous record works, and the field-by-field mapping is short. When many handlers select the same columns, the query_as! macro removes the mapping step by building the struct directly. It takes the struct name as its first argument, and the struct needs the FromRow derive.

src/handlers.rs
use sqlx::FromRow;

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

pub async fn create_user(
    State(pool): State<PgPool>,
    Json(input): Json<CreateUser>,
) -> Result<(StatusCode, Json<User>), AppError> {
    check_user_input(&input.name, &input.email)?;
    let user = sqlx::query_as!(
        User,
        "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id, name, email",
        input.name,
        input.email
    )
    .fetch_one(&pool)
    .await?;
    Ok((StatusCode::CREATED, Json(user)))
}

The SQL is unchanged, and the handler is shorter, because the record-to-struct step disappears. The compile-time checking is identical. Use query! when the returned columns vary between handlers, and use query_as! when the same row shape is returned in many places and the mapping has become noise.

Inserting Without RETURNING

Not every insert needs the row back. A background job that imports users from a file, or a handler that creates a row and then redirects the client elsewhere, may only need to know the insert worked. The execute method runs the statement and returns how many rows it affected, with no row to read.

src/handlers.rs
pub async fn import_user(pool: &PgPool, name: &str, email: &str) -> Result<(), AppError> {
    let result = sqlx::query!(
        "INSERT INTO users (name, email) VALUES ($1, $2)",
        name,
        email
    )
    .execute(pool)
    .await?;
    if result.rows_affected() != 1 {
        return Err(AppError::InternalError);
    }
    Ok(())
}

The rows_affected check is a guard, not a formality. An insert normally affects exactly one row, so anything else means the statement did something unexpected, and the helper reports it instead of silently succeeding. For a handler that answers a client, though, prefer RETURNING: the client almost always wants the created resource back, and the id is part of that resource.

RETURNING on UPDATE

The clause is not limited to inserts. An UPDATE with RETURNING sends back the row after the change, which is how an update handler returns the updated user without a second query. The shape is the same: the statement, a RETURNING list, and fetch_one.

src/handlers.rs
pub async fn replace_user(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
    Json(input): Json<CreateUser>,
) -> Result<Json<User>, AppError> {
    check_user_input(&input.name, &input.email)?;
    let row = sqlx::query!(
        "UPDATE users SET name = $1, email = $2 WHERE id = $3 RETURNING id, name, email",
        input.name,
        input.email,
        id
    )
    .fetch_one(&pool)
    .await?;
    Ok(Json(User {
        id: row.id,
        name: row.name,
        email: row.email,
    }))
}

When no row matches the id, the update changes nothing, RETURNING produces no row, and fetch_one errors with RowNotFound, which the error conversion turns into a 404. The update handler therefore needs no separate existence check: the statement itself reports the missing row through the same path the read handler uses.

What Happens When a Request Arrives

The path from a create request to a stored row runs through one statement:

POST /users arrives with {"name":"Asha","email":"asha@example.com"}
        |
        v
Router matches POST /users and runs create_user
        |
        v
Json extractor parses the body into CreateUser
        |
        v
check_user_input rejects an empty name or a bad email with 422
        |
        v
query! sends INSERT with name and email bound as $1 and $2
        |
        v
Postgres writes the row, assigns id from the sequence
        |
        v
RETURNING sends the stored row back in the same statement
        |
        v
fetch_one builds the anonymous record
        |
        v
Handler builds User and returns it with status 201

Validation runs before the database is touched, so a bad name or email never reaches Postgres and never costs a round trip. The database is the second check, not the first: it enforces the unique email rule that no input check can guarantee on its own.

Testing It

The test creates a user through the router and checks the status, the id, and the stored values in one pass. It clears the table first so the new row always gets id 1.

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

async fn test_app() -> axum::Router {
    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");
    sqlx::query("TRUNCATE TABLE users RESTART IDENTITY")
        .execute(&pool)
        .await
        .expect("failed to clear users");
    app(pool)
}

#[tokio::test]
async fn create_user_returns_201_with_database_id() {
    let router = test_app().await;
    let response = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/users")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"name":"Asha","email":"asha@example.com"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    let text = String::from_utf8(body.to_vec()).unwrap();
    assert!(text.contains("\"id\":1"), "body was {text}");
    assert!(text.contains("\"name\":\"Asha\""), "body was {text}");
}

#[tokio::test]
async fn create_user_with_empty_name_returns_422() {
    let router = test_app().await;
    let response = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/users")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"name":"","email":"asha@example.com"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

Run the tests with the database running:

DATABASE_URL=postgres://postgres:password@127.0.0.1:5432/ch12_depth cargo test

Both tests should pass:

test create_user_returns_201_with_database_id ... ok
test create_user_with_empty_name_returns_422 ... ok

The two tests share one table, and the test binary runs tests in parallel by default, so the truncate step of one test can interleave with the requests of the other. Run them one thread at a time to keep the table steady while the tests run:

DATABASE_URL=postgres://postgres:password@127.0.0.1:5432/ch12_depth cargo test -- --test-threads=1

The first test proves the whole chain: validation passed, the insert ran, RETURNING produced the row, and the id in the body is the one Postgres assigned. The second test proves validation runs before the insert: an empty name never reaches the database, so no row is created and no database error is possible.

The Test Database Is Not the Dev Database:

These tests truncate the users table. Running them against a database that holds real data wipes it. Keep a separate database for tests, or at least a database whose contents do not matter, and point DATABASE_URL at it when running cargo test. The tests in this cluster use ch12_depth as the dev database, and a test run against it is only safe while its rows are throwaway.

Common Beginner Mistakes

Inserting and then selecting by email

// Wrong - two statements, and the second one can read the wrong row
sqlx::query!("INSERT INTO users (name, email) VALUES ($1, $2)", input.name, input.email)
    .execute(&pool)
    .await?;
let row = sqlx::query!("SELECT id, name, email FROM users WHERE email = $1", input.email)
    .fetch_one(&pool)
    .await?;

This pair works when one request runs at a time, and breaks under load. Between the two statements, another request can insert the same email, delete the row, or change it, and the SELECT returns whatever the table holds at that later moment. The fix is the single statement with RETURNING, which reads the row it inserted and nothing else.

Using execute and expecting a row

// Wrong - execute returns a count, not a row, so there is nothing to build a User from
let result = sqlx::query!(
    "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id, name, email",
    input.name,
    input.email
)
.execute(&pool)
.await?;

execute runs the statement and discards any returned rows, so the RETURNING clause is wasted and the handler has no row to return. The compiler does not stop this, because the SQL is valid and execute accepts any statement. The fix is to match the method to the intent: fetch_one when the statement returns a row, execute when it does not.

Returning 200 for a create

// Wrong - the client cannot tell a create from an ordinary success
Ok(Json(User {
    id: row.id,
    name: row.name,
    email: row.email,
}))

A bare Json return defaults to status 200, which says the request succeeded but says nothing about a new resource. A client that creates a user and then checks for 201 to confirm the creation will treat this response as a failure of its own logic, or as a sign the resource already existed. The fix is the tuple return (StatusCode::CREATED, Json(user)), which states the outcome in the status line where clients look for it.

Listing created_at in RETURNING without a decoder

// Wrong - the macro cannot decode TIMESTAMPTZ without a date and time feature
let row = sqlx::query!(
    "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id, name, email, created_at",
    input.name,
    input.email
)
.fetch_one(&pool)
.await?;

The created_at column is a timestamp, and the project has no date and time crate feature enabled, so the macro fails to compile with a message about a missing decoder. The fix is to leave created_at out of the RETURNING list, since the response does not carry it. When a handler genuinely needs the timestamp, the fix is to enable a date and time feature on sqlx and use its type, not to force the value into a String.

Skipping validation because the database will catch it

// Wrong - the database rejects bad input with a 500, not a helpful 422
pub async fn create_user(
    State(pool): State<PgPool>,
    Json(input): Json<CreateUser>,
) -> Result<(StatusCode, Json<User>), AppError> {
    let row = sqlx::query!(
        "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id, name, email",
        input.name,
        input.email
    )
    .fetch_one(&pool)
    .await?;
    Ok((StatusCode::CREATED, Json(User { id: row.id, name: row.name, email: row.email })))
}

The database enforces NOT NULL and UNIQUE, so an empty name or a duplicate email does reach the database and does fail there. But the failure comes back as a database error, which the conversion turns into a 500, and the client learns nothing about what was wrong with its input. The fix is to keep the input check in the handler, before the query, so bad input gets a 422 with a message that names the problem, and the database stays the backstop for the rules only it can enforce.

Final Complete Example

Here is everything from this page in one project: the create handler with its validation, the read handler that proves the stored row matches, the router, and the entry point.

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

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

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
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::{
    Json,
    extract::{Path, State},
    http::StatusCode,
};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;

use crate::errors::AppError;

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

#[derive(Debug, Deserialize)]
pub struct CreateUser {
    pub name: String,
    pub email: String,
}

fn valid_email(email: &str) -> bool {
    let Some((local, domain)) = email.split_once('@') else {
        return false;
    };
    !local.is_empty() && domain.contains('.')
}

fn check_user_input(name: &str, email: &str) -> Result<(), AppError> {
    if name.trim().is_empty() {
        return Err(AppError::ValidationError(
            "name must not be empty".to_string(),
        ));
    }
    if !valid_email(email) {
        return Err(AppError::ValidationError(
            "email must look like name@example.com".to_string(),
        ));
    }
    Ok(())
}

pub async fn create_user(
    State(pool): State<PgPool>,
    Json(input): Json<CreateUser>,
) -> Result<(StatusCode, Json<User>), AppError> {
    check_user_input(&input.name, &input.email)?;
    let row = sqlx::query!(
        "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id, name, email",
        input.name,
        input.email
    )
    .fetch_one(&pool)
    .await?;
    Ok((
        StatusCode::CREATED,
        Json(User {
            id: row.id,
            name: row.name,
            email: row.email,
        }),
    ))
}

pub async fn get_user(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
) -> Result<Json<User>, AppError> {
    let row = sqlx::query!(
        "SELECT id, name, email FROM users WHERE id = $1",
        id
    )
    .fetch_one(&pool)
    .await?;
    Ok(Json(User {
        id: row.id,
        name: row.name,
        email: row.email,
    }))
}
src/lib.rs
pub mod db;
pub mod errors;
pub mod handlers;

use axum::{
    Router,
    routing::{get, post},
};
use handlers::{create_user, get_user};
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/users", post(create_user))
        .route("/users/{id}", get(get_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, create a user, and read the same user back. The two responses should match, and the id in the first response is the id Postgres assigned, not an id the client chose.

Summary

RETURNING closes the gap between writing a row and knowing what was written. One statement inserts the row and sends the stored row back, so the handler learns the database generated id and any defaulted values without a second query and without a window where another request could change the answer. The handler reads the result with fetch_one, because an insert returns exactly one row, and answers with 201 and the created resource, because that is what actually happened.

The decision framework is short. When the client needs the created row, or the code needs the generated id, use INSERT ... RETURNING with fetch_one and return the row. When nothing needs the row, use execute and check rows_affected. When the row is needed but comes from a second query, stop and use RETURNING instead, because the second query is a second chance for the answer to change. The same clause works on UPDATE, where it returns the row after the change, and the same fetch shapes apply there. The same thinking extends from single statements to the schema itself: the table these statements run against can be created by the application at startup, instead of by hand.