Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

How to Use psql with PostgreSQL on macOS

PostgreSQL is a powerful, open-source object-relational database system that uses and extends the SQL language. The psql command-line tool is a front-end to PostgreSQL that enables you to interact with the database server. It is essential for database administrators and developers who need to execute SQL queries, manage databases, and perform administrative tasks directly from the command line. This article will guide you on how to install and use psql on macOS, making necessary adjustments to align with the Apple environment.

Examples:

  1. Installing PostgreSQL and psql on macOS:

    To get started, you need to install PostgreSQL, which includes the psql tool. You can do this using Homebrew, a popular package manager for macOS.

    # Install Homebrew if you haven't already
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    
    # Install PostgreSQL
    brew install postgresql
    
    # Start PostgreSQL service
    brew services start postgresql
  2. Connecting to PostgreSQL using psql:

    Once PostgreSQL is installed, you can connect to the default database using the psql command.

    # Switch to the default PostgreSQL user
    sudo -i -u postgres
    
    # Connect to the PostgreSQL server
    psql

    Alternatively, you can connect to a specific database as a specific user:

    psql -U your_username -d your_database
  3. Basic psql Commands:

    Here are some basic commands to get you started with psql:

    • List all databases:

      \l
    • Connect to a database:

      \c your_database
    • List all tables in the current database:

      \dt
    • Describe a table:

      \d your_table
    • Execute a SQL query:

      SELECT * FROM your_table;
  4. Creating a New Database and Table:

    You can create a new database and table using the following commands:

    -- Create a new database
    CREATE DATABASE my_new_database;
    
    -- Connect to the new database
    \c my_new_database
    
    -- Create a new table
    CREATE TABLE my_table (
       id SERIAL PRIMARY KEY,
       name VARCHAR(100),
       age INT
    );
    
    -- Insert data into the table
    INSERT INTO my_table (name, age) VALUES ('Alice', 30), ('Bob', 25);
    
    -- Query the data
    SELECT * FROM my_table;

To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.