
Introduction
In the last post Updating/Deleting rows with Go, we learned to manipulate rows in PostgreSQL database in Go project using database/sql package that ships with Go, along with github.com/lib/pq Postgres driver. In this post, we’ll learn how to query rows i.e. SELECT
Prerequisites
To be able to achieve our objective i.e. Select rows from PostgreSQL using Go, there are some prerequisites. Sticking to core subject of this blog, I won’t cover them, however I’m providing with some references
Install PostgreSQL, setup an instance and create a test database – https://www.postgresqltutorial.com/install-postgresql/
Install Go and configure workspace – https://www.callicoder.com/golang-installation-setup-gopath-workspace/
For purpose of this tutorial, I’m using Postgres 11 and Go 1.13.xx
Objective – Querying rows in a PostgreSQL table using Go lang database/sql package
In following steps, I’ll demonstrate how to query rows
Step 1. SQL Table definition
We’ll reuse our table EMP that has following columns
-- create a sample table EMP
CREATE TABLE emp (
empno SERIAL PRIMARY KEY,
ename TEXT,
sal INT,
email TEXT UNIQUE NOT NULL
);
Step 2. SELECT statement in SQL (multiple rows)
Lets first write down our DML statements for update and delete
-- select row from table
SELECT ename, sal
FROM emp
ORDER BY sal desc;
Step 3. Connecting to PostgreSQL instance from Go lang
As always, we first need to make a connection to PostgreSQL instance. Since the code to make a connecting to PostgreSQL database is same, I’ll skip repeating it here, however if you need a refresher please visit the earlier post Connecting to PostgreSQL db from Go lang project
Step 4. Preparing Go lang code
SELECT row in EMP table
For reading rows, we will use db.Query() method, fetch ename and sal column from EMP table and output rows sorted by sal. Next, we will assign results to variables, one row at a time, with row.Scan().
// query rows from a table
var (
ename string
sal int
)
rows, err := db.Query("SELECT ename, sal FROM emp order by sal desc")
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
err := rows.Scan(&ename, &sal)
if err != nil {
panic(err)
}
fmt.Println("\n", ename, sal)
}
err = rows.Err()
if err != nil {
panic(err)
}
Lets understand the code above:
- We’re using
db.Query()to send the query to the database and checking for any error - Next we iterate over the rows with
rows.Next(). - Read the columns in each row into variables with
rows.Scan()and print them to console withfmt.Println(). - Finally, we check for errors after we’re done iterating over the rows.
Step 5. Putting this all together
package main
// querying all rows from the database with Go lang sql package
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
const (
host = "localhost"
port = 5432
user = "postgres"
password = "postgres"
dbname = "connect-db"
)
var (
ename string
sal int
)
func main() {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
rows, err := db.Query("SELECT ename, sal FROM emp order by sal desc")
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
err := rows.Scan(&ename, &sal)
if err != nil {
panic(err)
}
fmt.Println("\n", ename, sal)
}
err = rows.Err()
if err != nil {
panic(err)
}
}
What-If, you only want to query one single row?
There could be scenario when you would only want to query a single row, ex. lookup rows for a employee with highest salary. In this case, we can skip the for loop, instead use below shortcut approach.
var name string
err = db.QueryRow("SELECT ename FROM emp ORDER BY sal DESC LIMIT 1;").Scan(&name)
if err != nil {
panic(err)
}
fmt.Println(name)
Errors from the query are deferred until Scan() is called, and then are returned with variable output.
Conclusion
In this post we learned how to query rows (single or multiple) from a PostgreSQL table using Go lang database/sql package that ships with Go, along with github.com/lib/pq Postgres driver.
Like what I write? Please join my mailing list, and I’ll let you know whenever I write another post. No spam, I promise! 👨💻
One thought on “Querying rows from PostgreSQL from Go lang project”