Sobes.tech
Junior — Middle

How are temporary tables used in working with databases?

sobes.tech AI

Answer from AI

Temporary tables in a database are used to store intermediate results or temporary data within a single session or transaction. They are useful when you need to perform complex calculations, break down a task into stages, or avoid multiple accesses to the main table.

In Go (Golang), temporary tables are created and used through SQL queries sent via the database driver. For example, you can create a temporary table, fill it with data, perform necessary operations, and then the temporary table will automatically be deleted when the session ends.

Example of using a temporary table in PostgreSQL through Go:

import (
    "database/sql"
    _ "github.com/lib/pq"
    "log"
)

func useTempTable(db *sql.DB) error {
    // Create a temporary table
    _, err := db.Exec(`CREATE TEMP TABLE temp_users AS SELECT id, name FROM users WHERE active = true`)
    if err != nil {
        return err
    }

    // Use the temporary table for further queries
    rows, err := db.Query(`SELECT * FROM temp_users WHERE name LIKE 'A%'`)
    if err != nil {
        return err
    }
    defer rows.Close()

    for rows.Next() {
        var id int
        var name string
        if err := rows.Scan(&id, &name); err != nil {
            return err
        }
        log.Println(id, name)
    }
    return nil
}

Thus, temporary tables help optimize complex queries and simplify data processing logic within the database.