Junior — Middle
What approaches are used for storing text data in the PostgreSQL database?
sobes.tech AI
Answer from AI
In PostgreSQL, the following data types are commonly used for storing text data:
TEXT— for storing strings of arbitrary length without restriction.VARCHAR(n)— for strings with a length limit ofn.CHAR(n)— for fixed-length strings ofn, where shorter strings are padded with spaces.
In Go, the string type is typically used to work with these types. When working with the database through drivers (e.g., database/sql with lib/pq), strings from Go are automatically mapped to the corresponding PostgreSQL text types.
Example of inserting a string into the database:
import (
"database/sql"
_ "github.com/lib/pq"
)
func insertText(db *sql.DB, text string) error {
_, err := db.Exec("INSERT INTO my_table (text_column) VALUES ($1)", text)
return err
}
Thus, for storing text data in PostgreSQL, choose the appropriate type depending on length requirements and constraints, and use regular strings in Go.