Junior — Middle
How does the removal of outdated records from the database occur?
sobes.tech AI
Answer from AI
Removing outdated records from a database in Go typically involves executing an SQL query through a database driver. To do this:
- Establish a connection to the database (for example, using the
database/sqlpackage). - Execute a DELETE query with a condition that identifies outdated records (for example, based on date).
Example of deleting records older than a certain date:
import (
"database/sql"
"log"
"time"
_ "github.com/lib/pq" // example for PostgreSQL
)
func deleteOldRecords(db *sql.DB, cutoff time.Time) error {
query := `DELETE FROM records WHERE created_at < $1`
result, err := db.Exec(query, cutoff)
if err != nil {
return err
}
rowsAffected, _ := result.RowsAffected()
log.Printf("Deleted records: %d", rowsAffected)
return nil
}
Thus, deletion occurs through an SQL query with a filter, and the Go code is responsible for executing this query and handling the result.