Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify the last row in the result set postgres?

Tags:

postgresql

go

I am using Postgres 9.5 with and using golang library lib/pq to interact with database. I execute a select query which returns multiple rows and then I iterate using for rows.Next() Is there anyway I ca stop before the lat record. I want to print something else on console if its the last record. Something like the following:

for rows.Next() {

    var id string
    err = rows.Scan(&id)
    if err != nil {
        log.Printf("Error in rows.Scan: %s\n", err)
    }

    if (row is not last) {
        fmt.Println(id + "I am not last")
    } else {
        fmt.Println(id + "I am last")
    }
}
like image 648
codec Avatar asked Oct 30 '25 02:10

codec


1 Answers

You can impliment something like a do while loop in go.

notLast := rows.Next()
for notLast {
    //... rows.Scan
    notLast = rows.next()
    if notLast {
        fmt.Println(id + "I am not last")
    } else {
        fmt.Println(id + "I am last")
    }
}
like image 187
John S Perayil Avatar answered Nov 01 '25 19:11

John S Perayil