Level: AdvancedInterview

Go Database Interview Questions: SQL and Caching (Part 20)

Updated 10 min read
Go Database Interview Questions featured image: query, transaction and cache cards

These Go database interview questions cover database/sql, scanning rows, NULL values, transactions, the pool, pgx, sqlc, migrations and Redis. We gathered them from public interview lists, coding rounds and community threads. Then we rewrote them in plain words and grouped them by idea.

This post is questions only, so answer each one in your own words first. When you need help, read Go database tutorial with database/sql, Go PostgreSQL with pgx and Go Redis caching. Also, finish Part 19 on HTTP and REST APIs first, because most handlers end with a database call.

How to Use These Go Database Interview Questions

Answer each of these Go database interview questions out loud, then try the hard ones against a local PostgreSQL in Docker. Database bugs often hide in rare paths, such as a NULL column or a rolled back transaction. Finally, try the scenario questions, since they come from real outages.

The table below lists each section and its number of questions.

SectionWhat it testsQuestions
database/sql basicsDB, drivers and context15
Queries and NULLsScan, rows and Null types15
TransactionsBegin, Commit, Rollback and isolation14
Connection poolLimits, timeouts and stats14
Toolspgx, sqlc, ORMs and migrations14
CachingRedis, TTL and cache-aside14
Database coding tasksClassic interview programs10
Go Database Interview Questions diagram showing six question areas from database/sql to caching
The six areas covered in this question list, from database/sql to caching.

Go Database Interview Questions on database/sql

Before you answer, study Go database tutorial with database/sql. These Go database interview questions start with the standard package that every SQL driver plugs into.

  1. What is database/sql, and why does it need a separate driver?
  2. How does a blank import register a driver with sql.Register?
  3. What does sql.Open do, and why does it not connect right away?
  4. Why should you call db.PingContext after sql.Open?
  5. Is *sql.DB one connection or a pool, and is it safe for many goroutines?
  6. Why should you create one *sql.DB and share it across the app?
  7. What is the difference between QueryContext, QueryRowContext and ExecContext?
  8. Why should every call pass a context?
  9. How do placeholders differ between drivers, for example ? and $1?
  10. Why must you never build SQL with fmt.Sprintf and user input?
  11. What do prepared statements give you, and when are they worth it?
  12. What does sql.Result return after an insert or update?
  13. Does LastInsertId work with PostgreSQL, and what do you use instead?
  14. Scenario: when a new service opens a fresh *sql.DB in every handler, what goes wrong?
  15. Scenario: when a search box lets users inject SQL, how would you fix the query?

Go Database Interview Questions on Queries and NULLs

Before you answer, study Go sqlc vs GORM. Reading rows correctly is harder than it looks, so these Go database interview questions focus on the details.

  1. How do you loop over rows, and why must you call rows.Close?
  2. Why should you check rows.Err after the loop ends?
  3. What error does QueryRow return when no row matches, and how do you check it?
  4. Why does Scan need pointers to variables?
  5. What happens when you scan a NULL column into a plain string?
  6. How do sql.NullString and sql.NullInt64 work?
  7. What does the generic sql.Null type add in Go 1.22?
  8. When would you use a pointer field such as *string instead of a Null type?
  9. How do you scan a row into a struct without listing every field by hand?
  10. Why can SELECT * break your code when someone adds a column?
  11. How do you pass a list of IDs to an IN clause safely?
  12. What is the N plus 1 query problem, and how do you avoid it?
  13. How do you stream a large result set without loading it all into memory?
  14. Scenario: when a report endpoint leaks connections after an early return, what would you check?
  15. Scenario: when a profile page crashes on users with no phone number, how would you fix the scan?

Go Database Interview Questions on Transactions

Before you answer, study Go PostgreSQL with pgx. Transactions protect money and stock counts, so these Go database interview questions often come with follow-ups.

  1. How do you start a transaction with BeginTx, and what options can you pass?
  2. Why is defer tx.Rollback right after BeginTx a common pattern?
  3. What happens when you call Rollback after a successful Commit?
  4. Why must every query inside a transaction use tx and not db?
  5. What are the isolation levels, and which one is the PostgreSQL default?
  6. What problems do dirty reads, non-repeatable reads and phantom reads cause?
  7. How does SELECT FOR UPDATE help with a stock counter?
  8. What is optimistic locking with a version column?
  9. How do you retry a transaction after a serialization failure?
  10. Why should a transaction never wait on a slow HTTP call?
  11. How do you write a helper that runs a function inside a transaction?
  12. How do you keep a transaction and a message publish consistent, for example with an outbox table?
  13. Scenario: when two users buy the last item at the same time, how would you stop overselling?
  14. Scenario: when a money transfer debits one account but fails to credit the other, how would you fix it?

Go Database Interview Questions on the Connection Pool

Before you answer, study Go database tutorial again. Pool settings decide how a service behaves under load, so these Go database interview questions test real numbers.

  1. What do SetMaxOpenConns and SetMaxIdleConns control?
  2. Why is an unlimited number of open connections dangerous?
  3. What does SetConnMaxLifetime solve, for example with load balancers?
  4. What does SetConnMaxIdleTime do?
  5. How do you read pool numbers with db.Stats?
  6. What does WaitCount in the stats tell you?
  7. How do you size the pool for ten service replicas and one database?
  8. Why can a long transaction block other requests?
  9. How does a query timeout through context free a connection?
  10. When would you add a connection pooler such as PgBouncer?
  11. How do read replicas change the way you route queries?
  12. How do you find slow queries from a Go service?
  13. Scenario: when every request waits for a connection during a traffic spike, which stats would you check?
  14. Scenario: when the database says too many connections after a scale-up, how would you fix it?

Go Database Interview Questions on Tools

Before you answer, study Go sqlc vs GORM and Go database migrations. Teams argue about tools, so these questions ask you to explain your trade-offs.

  1. What does pgx give you that database/sql does not?
  2. When would you use pgxpool instead of database/sql with the pgx driver?
  3. What does sqlc generate from SQL files?
  4. What are the pros and cons of an ORM such as GORM?
  5. Why do many Go teams prefer plain SQL over an ORM?
  6. What is a database migration, and why do you version it?
  7. Should migrations run at app start or in a separate step, and why?
  8. How do you write a migration that is safe to run on a live table?
  9. What is your plan when a bad migration reaches production?
  10. How do you test database code, with a real database in Docker or with mocks?
  11. Why do many teams use testcontainers-go for integration tests?
  12. How do you seed test data and clean it up between tests?
  13. Scenario: when adding a column locks a large table for minutes, how would you change the migration?
  14. Scenario: when a team wants to switch from GORM to sqlc, how would you plan the move?

Caching with Redis

Before you answer, study Go Redis caching and Go in-memory cache with TTL. A cache can make a service fast or wrong, so these Go database interview questions test both sides.

  1. What is the cache-aside pattern, and when does the app fill the cache?
  2. How do you pick a TTL for a cached value, for example for prices?
  3. How do you invalidate a cache entry after an update?
  4. What is a cache stampede, and how does singleflight help?
  5. When should you cache a not found result?
  6. Why can a cache return stale data, and when is that acceptable?
  7. When is an in-memory cache better than Redis?
  8. How do you store a struct in Redis, as JSON or as a hash?
  9. How would you build a rate limiter with Redis?
  10. What happens to your service when Redis goes down?
  11. How do you set timeouts on Redis calls?
  12. How do you warm a cache after a deploy?
  13. Scenario: when users see an old price after an update, how would you fix the cache flow?
  14. Scenario: when a popular key expires and the database load spikes, what would you change?

Go Database Interview Questions for Coding Rounds

Before you answer, write each task by hand against a local database. Interviewers watch your error checks and your transaction handling, not only whether the code runs.

  1. Write a function that loads a user by ID and returns a clear not found error.
  2. List orders with pagination and close the rows properly.
  3. Insert an order and its items inside one transaction.
  4. Transfer money between two accounts with row locks.
  5. Write a repository interface and a fake for unit tests.
  6. Add a cache-aside layer in front of a user lookup.
  7. Write a migration that adds an index without long locks.
  8. Read a column that may be NULL with sql.Null.
  9. Scenario: when an interviewer asks you to design the tables for a library system, which tables and keys would you start with?
  10. Scenario: when a bulk import of one million rows is too slow, how would you speed it up?

Code Reading Questions

Read each program carefully and predict the output before you run it. Then explain the result in your own words.

package main

import (
    "database/sql"
    "fmt"
)

func main() {
    var email sql.NullString
    _ = email.Scan(nil)
    fmt.Println(email.Valid, email.String == "")
    _ = email.Scan("asha@example.com")
    fmt.Println(email.Valid, email.String)

    var age sql.Null[int64]
    _ = age.Scan(int64(31))
    v, _ := age.Value()
    fmt.Println(age.V, age.Valid, v)

    var score sql.NullInt64
    err := score.Scan("not a number")
    fmt.Println(err != nil, score.Valid)
}
  1. What do the first three lines print, and how does Valid change after each Scan?
  2. What does the last line print, and why should you always check the error from Scan?

The second program is a tiny cache-aside layer in front of a fake store.

package main

import (
    "errors"
    "fmt"
    "time"
)

var ErrNoRows = errors.New("no rows")

type store struct{ calls int }

func (s *store) userName(id int) (string, error) {
    s.calls++
    if id == 1 {
        return "Asha", nil
    }
    return "", ErrNoRows
}

type cache struct {
    data map[int]string
    at   map[int]time.Time
    ttl  time.Duration
}

func (c *cache) get(id int, now time.Time, db *store) (string, error) {
    if v, ok := c.data[id]; ok && now.Sub(c.at[id]) < c.ttl {
        return v, nil
    }
    v, err := db.userName(id)
    if err != nil {
        return "", fmt.Errorf("user %d: %w", id, err)
    }
    c.data[id], c.at[id] = v, now
    return v, nil
}

func main() {
    db := &store{}
    c := &cache{data: map[int]string{}, at: map[int]time.Time{}, ttl: time.Minute}
    t0 := time.Date(2026, 9, 21, 9, 0, 0, 0, time.UTC)
    for _, sec := range []int{0, 10, 59, 61} {
        name, _ := c.get(1, t0.Add(time.Duration(sec)*time.Second), db)
        fmt.Println(sec, name, db.calls)
    }
    _, err := c.get(2, t0, db)
    _, err2 := c.get(2, t0, db)
    fmt.Println(errors.Is(err, ErrNoRows), err2, db.calls)
}
  1. How many times does the store run for user 1, and why does the call at 61 seconds go to the store?
  2. Why does user 2 hit the store twice, and how would negative caching change that?

Quick Revision Table for Go and SQL

Use the table below as a final check before your interview. It lists the database/sql calls you will use most.

CallReturnsWatch out for
QueryContext*sql.RowsClose rows and check rows.Err
QueryRowContext*sql.Rowsql.ErrNoRows on no match
ExecContextsql.ResultRowsAffected for updates
BeginTx*sql.TxDefer Rollback, then Commit
SetMaxOpenConnsNothingSize it for every replica
db.Statssql.DBStatsWaitCount shows pool pressure

Also, many interviewers ask you to compare database/sql and pgx directly. The diagram below shows the difference side by side.

Go database diagram comparing database/sql with pgx
database/sql works with many databases, while pgx is built only for PostgreSQL and gives you more of its features.

Official Resources

These official pages explain the rules behind these questions.

Quick Recap

  • These Go database interview questions cover database/sql, queries, transactions, the pool, tools and caching.
  • One shared *sql.DB is a safe pool, so create it once and pass a context to every call.
  • Close rows, check rows.Err and handle sql.ErrNoRows on purpose.
  • Defer Rollback after BeginTx, and run every statement on the tx.
  • Size the pool for all replicas, and watch WaitCount in db.Stats.
  • Cache with a TTL, plan invalidation and protect hot keys from stampedes.

What’s Next?

By now, you have Go database interview questions for SQL, transactions and caching. Study the answers in your own notes, then check them against the Go interview topics study guide.

Next up: Go security interview questions (Part 21)