I am running into trouble getting a sum() value from a Postgres database using PGX drive for Golang.
Here is my code:. I added a second variable because the row is returning two values.
var cartItemPriceFloat float64 var secondVariable string
row, err := global.Db.Query(context.Background(), "select sum(shopping_cart_rows.shopping_cart_row_product_quantity * products.product_price) as cart_item_price from shopping_cart_rows inner join products on products.product_id=shopping_cart_rows.shopping_cart_row_product_id where shopping_cart_rows.shopping_cart_row_user_id=$1", userId)
if err != nil {
fmt.Println("Error retrieving cart item price: ", err)
}
fmt.Println("The output from the query is ", row)
err2 := row.Scan(&cartItemPriceFloat, &secondVariable)
if err2 != nil {
fmt.Println("Error scanning query result into cartItemPriceFloat: ", err2)
}
fmt.Println("cartItemPriceFloat = ", cartItemPriceFloat)
fmt.Println("secondVariable = ", secondVariable)
The terminal output is:
The output from the query is &{0xc0003b6000 0xc0003ac7f0 } Error scanning query result into cartItemPriceFloat: number of field descriptions must equal number of values, got 1 and 0 cartItemPriceFloat = 0 secondVariable =
I am probably missing something simple. All I want is the value of cartItemPriceFloat. BTW, when I run this query in the Postgres console, it returns the correct value.
Your query returns a single scalar,
cart_item_price
:You must scan for only one field and one row. Use
QueryRow
instead: