Return the number of rows in a Postgres database table using diesel

I am trying to count the number of rows in a Postgres database table using diesel and use the returned value in a conditional statement

You can use the count function directly on a table to count the rows. For example, using the posts table and establish_connection function from the Getting Started guide:

use schema::posts;

let conn = establish_connection();
let count = posts::table.count().get_results(&conn).unwrap();

if count > 5 {
    println!("That's a lot of posts!");
}
1 Like

This exact code did not work but it really helped me map out what I needed to do.

This compiled for my use case,

let count: i64 = users.count().get_result(conn).unwrap();

also should have mentioned that i'm using it with actix-web = "3"

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.