Tuesday, September 24, 2024

PostgreSQL CLI tutorial 2024

PostgreSQL, a robust and feature-rich relational database management system (RDBMS), powers countless websites and applications. Its popularity stems from its reliable transactions, efficient concurrency without read locks, and comprehensive SQL support. This guide will walk you through essential PostgreSQL management tasks using the command line, often referred to as PSQL connect to database.

Understanding PostgreSQL Roles and Databases

PostgreSQL employs a concept called "roles" for authentication and authorization, similar to regular Unix accounts. However, PostgreSQL uses the term "role" to differentiate between user privileges. The installation process typically sets up PostgreSQL with ident authentication, where roles are linked to Unix/Linux system accounts. If a role exists in PostgreSQL, a Unix/Linux username with the same name can access the system using that role.

Connecting to the PostgreSQL Account

During installation, a postgres account is created with a built-in PostgreSQL role. To interact with PostgreSQL, you need to log in to this account using the following command:

      $ sudo -iu postgres
    

Once logged in, you can access the PostgreSQL prompt using:

      $ psql
    

This will allow you to interact with the database management system. To exit the PostgreSQL prompt, run:

      \q
    

Accessing the PostgreSQL Prompt Without Switching Accounts

You can also execute desired commands directly through sudo without switching accounts. For example, if you only want to log in to the PostgreSQL prompt, you can use:

      $ sudo -u postgres psql
    

This will grant you access to the PostgreSQL prompt as the postgres role without requiring you to log in as the postgres user.

To exit the prompt, use the command:

      \q
    

Creating a New Role

After installing PostgreSQL, you have access to the postgres role. To create new roles, use the createuser command. The --interactive flag will prompt you for necessary values.

For instance, create a new PostgreSQL role with the following command:

      $ sudo -u postgres createuser --interactive
    

The command will guide you through the process, prompting for details such as the role name and whether it should be a superuser. You can explore additional options using the man createuser command.

Creating a New Database

PostgreSQL automatically creates a database with the same name as a newly created role, granting the role access to it.

In our previous example, we created a user named "master," who automatically has access to the "master" database. You can create the database manually with the createdb command:

      $ createdb master
    

Alternatively, if you prefer using sudo for each command without switching accounts, you can use:

      $ sudo -u postgres createdb master
    

Accessing the PostgreSQL Prompt with a New Role

To use ident-based authentication, you need a Linux user with the same name as the role and the same PostgreSQL database.

If such a user doesn't exist, create one using the adduser command with sudo privileges:

      $ sudo adduser master
    

Follow the on-screen prompts to complete the account creation. Once the account is available, switch to it and log in to the database using:

      $ sudo -iu master
      $ psql
    

Or, you can use a single command:

      $ sudo -u master psql
    

This will automatically log you in.

If you need to connect to a different database than the current user's default database, specify the database name:

      $ psql -d postgres
    

To verify your connection details, use the command:

      \conninfo
    

The output will display information like:

      You are connected to database "master" as user "master" via socket in "/var/run/postgresql" at port "5432".
    

Creating and Deleting Tables

Once connected to the PostgreSQL database system, you can perform basic tasks, such as creating tables to store data. Let's create a table to represent servers in a data center.

The basic syntax for creating a table is:

CREATE TABLE table_name (
column_name1 col_type (field_length) column_constraints,
column_name2 col_type (field_length),
column_name3 col_type (field_length)
);
    

This structure defines the table name, columns, column types, maximum data length, and constraints.

Create a table named "datacenter" to store server information:

CREATE TABLE datacenter (
equip_id serial PRIMARY KEY,
rackname varchar (50) NOT NULL,
color varchar (25) NOT NULL,
location varchar (25) check (location in ('north', 'south', 'west', 'east', 'northeast', 'southeast', 'southwest', 'northwest')),
install_date date
);
    

This table stores server data, including an auto-incrementing integer column (equip_id) as the primary key, along with the rack name, color, location, and installation date.

To view the newly created table, use the command:

      \d
    

The output will display a list of relations, including the datacenter table and the datacenter_equip_id_seq sequence, which handles auto-incrementing values for the equip_id column.

To see only the tables, excluding sequences, use:

      \dt
    

Adding, Querying, and Deleting Data in a Table

After creating a table, you can insert data into it. Use the INSERT statement, specifying the table name, column names, and data values:

INSERT INTO datacenter (rackname, color, location, install_date) VALUES ('mercurius', 'red', 'south', '2020-02-16');
INSERT INTO datacenter (rackname, color, location, install_date) VALUES ('venus', 'grey', 'northwest', '2021-09-05');
    

Remember to enclose string values in single quotes. Avoid providing data for the equip_id column as it's auto-incrementing.

To view the inserted data, use the SELECT statement:

      SELECT * FROM datacenter;
    

The output will display the table contents, including the automatically generated equip_id values.

To delete data from the table, use the DELETE statement with a WHERE clause to specify the condition:

      DELETE FROM datacenter WHERE rackname = 'mercurius';
    

Run the SELECT statement again to confirm the deletion.

Adding and Removing Columns from a Table

You can easily add new columns to an existing table using the ALTER TABLE statement:

      ALTER TABLE datacenter ADD last_maint date;
    

This adds a last_maint column of type date to the datacenter table.

Use the SELECT * FROM datacenter; command to view the table information, confirming the new column.

Updating Data in a Table

The UPDATE statement allows you to modify existing data in a table. For example, to change the color of the "venus" rack to red:

      UPDATE datacenter SET color = 'red' WHERE rackname = 'venus';
    

Use the SELECT * FROM datacenter; command to verify the update.

Conclusion: Mastering PostgreSQL from the Command Line

This guide provided a comprehensive overview of fundamental PostgreSQL management tasks using the command line, covering role creation, database creation, table management, data manipulation, and more. By mastering these commands, you gain the ability to effectively manage and interact with your PostgreSQL database, ensuring efficient and reliable operation.

Remember, this is just the beginning of your PostgreSQL journey. Explore further and delve into advanced features like user-defined functions, views, and indexing to optimize your database for performance and scalability.

If you're looking for a seamless PostgreSQL experience, consider utilizing PostgreSQL hosting services that provide managed support. This allows you to focus on your application's core functionalities without needing to worry about the intricate details of database management.

0 comments:

Post a Comment