Sobes.tech
Senior

How is data stored in a database?

sobes.tech AI

Answer from AI

Data in a database is stored as structured records, organized into tables (in relational databases) or as documents, key-value pairs, graphs, etc. (in non-relational databases).

Main principles of data storage:

  • File system: Data is physically stored in files on disk.
  • Pages and blocks: Data is divided into fixed-size pages for efficient reading and writing.
  • Indexes: Additional structures are created for quick searching, pointing to data locations.
  • Transactions and logs: Transaction logs are used to ensure data integrity and recovery.

In the context of Go (Golang), data from the database is usually read and written through drivers and ORM, which interact with the DBMS, and the data itself is serialized into an appropriate format (e.g., JSON, binary) and stored.

Example of simple data saving to a database using Go and SQL:

import (
	"database/sql"
	_ "github.com/lib/pq" // driver for PostgreSQL
)

func saveUser(db *sql.DB, name string, age int) error {
	_, err := db.Exec("INSERT INTO users(name, age) VALUES($1, $2)", name, age)
	return err
}

Thus, data in the database is stored in a structured form optimized for quick access and integrity.