Install PostgreSQL on ubuntu 22.04

Relational database management systems are key components of many websites and applications. They provide a structured way to store, organize, and access information.

PostgreSQL or Postgres is a relational database management system that provides an implementation of the SQL query language. It is standards compliant and has many advanced features such as reliable transaction processing and concurrency without read locks.

This document explains how to install Postgres on Ubuntu 22.04 server. It also provides some instructions for general database administration.

Install PostgresSQL

Ubuntu's default repository contains Postgres packages, so you can install them using the apt packaging system.

Refresh the local package index:

sudo apt update

Then, install the Postgres package as well as the -contrib package which adds some extra utilities and functionality:

sudo apt install postgresql postgresql-contrib

Make sure the service is running using the systemctl start command:

sudo systemctl start postgresql.service

Now that the software is installed and running, we can look at how it works and how it differs from other relational database management systems you may have used.

Using PostgreSQL roles and databases

By default, Postgres handles authentication and authorization using a concept called roles. These are similar in some respects to regular Unix-style accounts, but Postgres does not distinguish between users and groups, preferring the more flexible term "role".

After installation, Postgres is set up to use peer authentication, which means that it associates the Postgres role with a matching Unix/Linux system account. If a role exists in Postgres, a Unix/Linux username with the same name can log in as that role.

The installation process creates a user account named postgres, which is associated with the default Postgres role. In order to use Postgres, you log into this account.

There are several ways to access Postgres using this account.

Switch to postgres account

Switch to the postgres account on the server by typing:

sudo -i -u postgres

You can now instantly access the PostgreSQL prompt by typing:

psql

From there you are free to interact with the database management system as needed.

Exit the PostgreSQL prompt by typing:

\q

This will take you back to the postgres Linux user's command line.

Access the Postgres command line without switching accounts

You can also use sudo directly to run the command you want using the postgres account.

For example, in the last example, you are instructed to enter the Postgres prompt by first switching to the postgres user and then running psql to open the Postgres prompt. You can do this in one step by running a single command psql using sudo as the postgres user, as follows:

sudo -u postgres psql

This will allow you to log into Postgres directly without the need for an intervening bash shell.

Likewise, you can exit an interactive Postgres session by typing:

\q

Many use cases require multiple Postgres roles. Continue reading below to learn how to configure these.

Create new role

Currently, you have the postgres role configured in the database. You can create a new role from the command line using the createuser command. The --interactive flag will prompt you for a name for the new role and ask if it should have superuser privileges.

If you are logged in as a postgres account, you can create a new user by typing:

createuser --interactive

If instead you prefer to use sudo for every command without switching from a normal account, type:

sudo -u postgres createuser --interactive

The script will prompt you to make some choices and, based on your answers, execute the correct Postgres commands to create a user that matches your specifications.

Output
Enter name of role to add: sammy
Shall the new role be a superuser? (y/n) y

You can get more control by passing some extra flags. Check the options by looking at the man page for the createuser command:

man createuser

Your Postgres installation now has a new user, but you haven't added any databases yet. This process is described in the next section.

Set a login password for the role:

alter role sammy with password 'sammy123';

Create database

Another assumption that the Postgres authentication system makes by default is that for any role used to log in, that role will have a database with the same name that it can access.

This means that if the user name you created in the previous section is sammy, by default the role will try to connect to the database also called "sammy". You can create the appropriate database using the createdb command.

If you are logged in as a postgres account, you would type the following:

createdb sammy

If instead you prefer to use sudo for every command without switching from your normal account, you can type:

sudo -u postgres createdb sammy

This flexibility provides multiple ways to create databases as needed.

Open Postgres command line using new role

To log in using peer authentication, you need a Linux user with the same name as your Postgres role and database.

If there is no matching Linux user available, you can use the adduser command to create one. You must do this from a non-root account with sudo privileges (meaning, not logged in as the postgres user):

sudo adduser sammy

Once this new account is available, you can switch and connect to the database by typing:

sudo -i -u sammy
psql

Or you can:

sudo -u sammy psql

Assuming all components are configured correctly, this command will automatically log you in.

If you want your users to connect to a different database, you can do this by specifying the database as follows:

psql -d postgres

Once logged in, you can check your current connection information by typing:

\conninfo
Output
You are connected to database "sammy" as user "sammy" via socket in "/var/run/postgresql" at port "5432".

This is useful if you are connecting to a non-default database or a non-default user.

Create and delete tables

Now that you know how to connect to a PostgreSQL database system, you can learn some basic Postgres administration tasks.

The basic syntax for creating a table is as follows:

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 command names the table and then defines the columns along with the column types and maximum length of the field data. Alternatively, you can add constraints for each column.

For demonstration purposes, create the following table:

CREATE TABLE playground (
    equip_id serial PRIMARY KEY,
    type 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 command creates a table for inventory of playground equipment. The first column in the table will hold the device ID number of the sequence type, which is an auto-incrementing integer. This column also has the constraint of PRIMARY KEY, which means that the values ​​in it must be unique and cannot be null.

The next two lines create columns for device type and color, neither of which can be empty. The rows after these create a position column whose constraint requires that the value be one of eight possible values. The last line creates a date column recording the date you installed the device.

For two of the columns (equip_id and install_date), the command does not specify the field length. The reason for this is that some data types do not require the length to be set because the length or format is implicit.

Check your new table by typing:

\d

get:

Output
                  List of relations
 Schema |          Name           |   Type   | Owner 
--------+-------------------------+----------+-------
 public | playground              | table    | sammy
 public | playground_equip_id_seq | sequence | sammy
(2 rows)

Your playground table is here, but there's also something called playground_equip_id_seq, which is of type sequence. This is a representation of the sequence type you provide for the equip_id column. This keeps track of the next number in the sequence and creates it automatically for such columns.

If you just want to see the table without the sequences, you can type:

\dt
Output
          List of relations
 Schema |    Name    | Type  | Owner 
--------+------------+-------+-------
 public | playground | table | sammy
(1 row)

With the table ready, let's use it to practice managing data.

Add, query and delete data in the table

Now that you have a table, you can insert some data into it. For example, add slides and swings by calling the table you want to add to, naming the columns, and then providing data for each column, as follows:

INSERT INTO playground (type, color, location, install_date) VALUES ('slide', 'blue', 'south', '2017-04-28');
INSERT INTO playground (type, color, location, install_date) VALUES ('swing', 'yellow', 'northwest', '2018-08-16');

Care should be taken when entering data to avoid some common hang-ups. For one, don't put quotes around the column names, but the column values ​​you enter do need quotes.

Another thing to remember is that you did not enter a value for the equip_id column. This is because it is automatically generated every time you add a new row to the table.

Retrieve the information you added by typing:

SELECT * FROM playground;
Output
 equip_id | type  | color  | location  | install_date 
----------+-------+--------+-----------+--------------
        1 | slide | blue   | south     | 2017-04-28
        2 | swing | yellow | northwest | 2018-08-16
(2 rows)

Please note that your equip_id has been filled in successfully and all other data is organized correctly.

If the slide on the playground is broken and you have to delete it, you can also delete the row from the table by typing:

DELETE FROM playground WHERE type = 'slide';

Check the table again:

SELECT * FROM playground;

get:

Output
 equip_id | type  | color  | location  | install_date 
----------+-------+--------+-----------+--------------
        2 | swing | yellow | northwest | 2018-08-16
(1 row)

Notice that the slide row is no longer part of the table.

Add and delete columns from the table

After you create a table, you can modify it by adding or removing columns. Add a column to display the last maintenance visit for each device by typing:

ALTER TABLE playground ADD last_maint date;

Review your table information again. New column added but no data entered:

SELECT * FROM playground;
Output
 equip_id | type  | color  | location  | install_date | last_maint 
----------+-------+--------+-----------+--------------+------------
        2 | swing | yellow | northwest | 2018-08-16   | 
(1 row)

If you find that your staff uses a separate tool to track maintenance history, you can remove that column by typing:

ALTER TABLE playground DROP last_maint;

This will delete the last_maint column and any values ​​found in it, but leave all other data unchanged.

Update data in table

So far, you have learned how to add records to a table and how to delete them, but this tutorial has not yet covered how to modify existing entries.

You can update the value of an existing entry by querying for the required record and setting the column to the value you wish to use. You can query the swing record (which will match every swing in your table) and change its color to red. If you are painting your swing set this may be useful:

UPDATE playground SET color = 'red' WHERE type = 'swing';

You can verify that the operation was successful by querying the data again:

SELECT * FROM playground;
Output
 equip_id | type  | color | location  | install_date 
----------+-------+-------+-----------+--------------
        2 | swing | red   | northwest | 2018-08-16
(1 row)

The slide is now registered as red.

in conclusion

You have now set up PostgreSQL on your Ubuntu 22.04 server.

Guess you like

Origin blog.csdn.net/weixin_39636364/article/details/131175994