DevPath
Mid lesson · 12 min

Read database rows safely

Close resources, scan nulls, and check iteration errors.

Own the rows lifetime

After QueryContext succeeds, defer rows.Close. Iterate with rows.Next, scan each row, then check rows.Err when the loop ends. A failure can occur during iteration even if the initial query succeeded. Return that error with enough context to identify the operation.

Match nullable data

A SQL NULL cannot always scan into an ordinary Go value. Use an appropriate sql.Null type or a pointer and decide how the domain should represent 'unknown'. Avoid turning null into zero silently when zero has real meaning.

rows, err := db.QueryContext(ctx, query, ownerID)
if err != nil { return nil, err }
defer rows.Close()
for rows.Next() { /* scan */ }
if err := rows.Err(); err != nil { return nil, err }

Test the failure point

Use a fake row source or database fixture that yields multiple rows, a null column, and an iteration failure. Assert that a failed scan does not return a misleading partial success unless the API explicitly promises partial results. Keep the query parameterized and pass the caller's context.

Check your understanding

Why check rows.Err after a loop that ended normally?

Show explanation

Next can stop because iteration failed, not only because there are no more rows. rows.Err reports that failure.

Put this lesson into practice

A practice activity at this level in the same module.

Try: Fan out with a bounded worker pool

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.