Как удалить postgresql ubuntu
Перейти к содержимому

Как удалить postgresql ubuntu

  • автор:

Linux downloads (Ubuntu)

PostgreSQL is available in all Ubuntu versions by default. However, Ubuntu «snapshots» a specific version of PostgreSQL that is then supported throughout the lifetime of that Ubuntu version. The PostgreSQL project maintains an Apt repository with all supported of PostgreSQL available.

Included in Distribution

Ubuntu includes PostgreSQL by default. To install PostgreSQL on Ubuntu, use the apt (or other apt-driving) command:

apt install postgresql

PostgreSQL Apt Repository

If the version included in your version of Ubuntu is not the one you want, you can use the PostgreSQL Apt Repository. This repository will integrate with your normal systems and patch management, and provide automatic updates for all supported versions of PostgreSQL throughout the support lifetime of PostgreSQL.

The PostgreSQL Apt Repository supports the current versions of Ubuntu:

  • noble (24.04, LTS)
  • mantic (23.10, non-LTS)
  • jammy (22.04, LTS)
  • focal (20.04, LTS)

on the following architectures:

  • amd64
  • arm64 (LTS releases only)
  • ppc64el (LTS releases only)
  • s390x (LTS releases only)

Automated repository configuration:

sudo apt install -y postgresql-common sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh

Copy Script

To manually configure the Apt repository, follow these steps:

# Import the repository signing key: sudo apt install curl ca-certificates sudo install -d /usr/share/postgresql-common/pgdg sudo curl -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc --fail https://www.postgresql.org/media/keys/ACCC4CF8.asc # Create the repository configuration file: sudo sh -c 'echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list' # Update the package lists: sudo apt update # Install the latest version of PostgreSQL: # If you want a specific version, use 'postgresql-16' or similar instead of 'postgresql' sudo apt -y install postgresql

Copy Script

For more information about the apt repository, including answers to frequent questions, please see the PostgreSQL Apt Repository wiki page.

Packages

The repository contains many different packages including third party addons. The most common and important packages are (substitute the version number as required):

postgresql-client-16 client libraries and client binaries
postgresql-16 core database server
postgresql-doc-16 documentation
libpq-dev libraries and headers for C language frontend development
postgresql-server-dev-16 libraries and headers for C language backend development

How to uninstall the postgresql

The simplest way to do this is open a terminal and type:

sudo apt-get --purge remove postgresql 

This will remove the postgresql package. There may be chances that additional packages are also installed so you can search them by typing:

dpkg -l | grep postgres 

and purge all those packages by sudo apt-get —purge remove .

34.3k 39 39 gold badges 98 98 silver badges 191 191 bronze badges
answered Feb 27, 2018 at 23:29
Murtaza Manasawala Murtaza Manasawala
241 1 1 silver badge 4 4 bronze badges

Thanks! But still i got some left. Is there a possible way i can delete the postgresql «folder by folder»

Feb 28, 2018 at 22:55
By purging you can delete all the dependencies. Visit postgresql documentation.
Mar 1, 2018 at 2:31
sudo apt-get —purge remove postgresql*
Jan 2, 2019 at 1:25

To completely uninstall PostgreSQL

sudo apt-get purge postgres.* 

I just want to add that any packages installed using apt, apt-get or from .deb files for example, can be uninstalled using:

sudo apt-get purge package_name.* 

List package and all of its dependencies to check what are being uninstalled:

dpkg --list | grep package_name.* 

.* after package_name is very important to regex match all possible dependencies associated with a package.

answered Nov 3, 2022 at 16:46
William Le William Le
133 5 5 bronze badges

To completely remove Postgres with dependent packages, I used the following commands on my Ubuntu 20.04.

First check the postgres installed version
dpkg -l | grep postgres

Then use the following command to remove all dependencies. Use your version number.

$ sudo apt-get --purge remove postgresql-12 postgresql-client-12 postgresql-client-common postgresql-common 

Как полностью удалить PostgreSQL: подробная инструкция

PostgreSQL – это мощная и гибкая система управления базами данных, которая пользуется большой популярностью у разработчиков и администраторов. В некоторых случаях может возникнуть необходимость полного удаления PostgreSQL с вашей системы, например, при переходе на другую базу данных или при установке более новой версии.

В этой статье мы расскажем подробную инструкцию о том, как полностью удалить PostgreSQL с вашей системы.

Шаг 1: Остановка служб и удаление кластеров

  1. Перед удалением PostgreSQL необходимо остановить все связанные с ним службы. Для этого вы можете воспользоваться командной строкой или специальными инструментами управления службами в вашей операционной системе.
  2. После остановки служб необходимо удалить все существующие кластеры PostgreSQL. Для этого вы можете воспользоваться командой pg_dropcluster с указанием версии PostgreSQL и имени кластера.

Шаг 2: Удаление файлов и директорий

После остановки служб и удаления кластеров необходимо удалить все файлы и директории, связанные с PostgreSQL. Пожалуйста, будьте внимательны при выполнении этого шага, так как удаление неправильных файлов может привести к нежелательным последствиям.

Шаг 3: Удаление переменных окружения

Последним шагом в процессе удаления PostgreSQL является удаление переменных окружения, связанных с этой системой. Обычно они настраиваются в файле ~/.bashrc или ~/.bash_profile . Откройте нужный файл в текстовом редакторе и удалите все строки, содержащие информацию о PostgreSQL.

После выполнения всех этих шагов PostgreSQL должен быть полностью удален с вашей системы. Не забудьте перезагрузить систему, чтобы изменения вступили в силу полностью.

Шаг 1: Остановка службы PostgreSQL

Перед удалением PostgreSQL необходимо остановить службу базы данных. Для этого следуйте инструкциям:

  1. Откройте меню “Пуск” и найдите раздел “Службы”.
  2. В списке служб найдите службу с названием “PostgreSQL” и щелкните правой кнопкой мыши на ней.
  3. В появившемся контекстном меню выберите пункт “Остановить”.

Теперь служба PostgreSQL будет остановлена, и вы сможете продолжить процесс удаления программы.

Шаг 2: Удаление PostgreSQL из системы

Перед началом процесса удаления PostgreSQL рекомендуется сделать резервную копию всех необходимых данных. Также убедитесь, что у вас есть права администратора для выполнения необходимых действий.

Следуйте инструкциям ниже, чтобы полностью удалить PostgreSQL из вашей системы:

  1. Отключите и остановите все службы PostgreSQL, запущенные на вашем компьютере. Для этого откройте меню “Пуск”, найдите “Службы” или “Управление службами” и запустите данный утилиту. В списке служб найдите все службы PostgreSQL, щелкните правой кнопкой мыши и выберите “Остановить”. Затем щелкните правой кнопкой мыши на каждой службе и выберите “Отключить”.
  2. Удалите директорию с установленным PostgreSQL. Обычно она находится по пути “C:\Program Files\PostgreSQL”. Щелкните правой кнопкой мыши на директории и выберите “Удалить”. Если у вас были несколько установок PostgreSQL, удалите соответствующие директории.
  3. Удалите записи о PostgreSQL из системного реестра. Откройте редактор реестра, нажав сочетание клавиш Win + R, введите “regedit” и нажмите Enter. В редакторе реестра откройте раздел HKEY_LOCAL_MACHINE\SOFTWARE и найдите папку “PostgreSQL”. Щелкните правой кнопкой мыши на папке и выберите “Удалить”.
  4. Удалите записи о PostgreSQL из переменных среды. Откройте “Панель управления”, найдите раздел “Система” или “Система и безопасность” и выберите “Система”. В открывшемся окне выберите “Дополнительные параметры системы”. В открывшемся окне выберите вкладку “Дополнительно”. Нажмите на кнопку “Переменные среды”. В разделе “Системные переменные” найдите переменные с названиями, начинающимися с “PG” или “postgresql”. Выберите каждую переменную по очереди, нажмите кнопку “Удалить” и подтвердите удаление.
  5. Перезагрузите компьютер. После выполнения всех вышеуказанных действий рекомендуется перезагрузить компьютер, чтобы убедиться, что все изменения вступили в силу и PostgreSQL полностью удален из системы.

После выполнения всех шагов вы можете быть уверены, что PostgreSQL успешно удален с вашего компьютера. При необходимости вы всегда можете повторно установить PostgreSQL с чистого листа и начать использовать базу данных.

How to Install PostgreSQL on Ubuntu

PostgreSQL is an open-source, object-relational database system with a strong reputation for feature robustness, extensibility, and technical standards compliance. Combined with Ubuntu, it provides a dependable and performant platform for your database needs.

This tutorial will provide two different ways of installing the latest PostgreSQL version on Ubuntu.

How to Install PostgreSQL on Ubuntu.

  • A machine running Ubuntu.
  • Access to the terminal (Ctrl+Alt+T).
  • A user account with root privileges.

How to Install PostgreSQL On Ubuntu

There are two ways to install PostgreSQL on Ubuntu:

  • From the PostgreSQL repository.
  • From the default Ubuntu repository.

Installing PostgreSQL via the Ubuntu repository provides the PostgreSQL version that is officially packaged and maintained by the Ubuntu developers. On the other hand, installing from the PostgreSQL repository gives you the option to get the latest version directly from the PostgreSQL project, potentially providing newer features and bug fixes not yet available in the Ubuntu repositories.

The sections below provide the steps for each installation method.

Method 1: Install PostgreSQL from PostgreSQL Apt Repository

The PostgreSQL Apt Repository provides the latest PostgreSQL version, as well as all previous server packages, extensions, and modules. Having the latest version provides access to newer features, performance improvements, and bug fixes sooner than they are available in the Ubuntu repositories.

However, note that while installing from the PostgreSQL repository can provide access to the latest PostgreSQL releases, it may require more manual work and attention to security updates.

Follow the steps in the sections below to install PostgreSQL from the PostgreSQL repository.

Step 1: Add PostgreSQL Repository

Run the following command to add the PostgreSQL repository to your system:

sudo sh -c 'echo "deb https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'

The command adds the repository to the system’s apt package manager, instructing it to use the PostgreSQL repository for package management.

Step 2: Add the Repository Signing Key

The next step is to fetch the repository’s GPG key and add it to APT’s trusted keyring. This allows APT to verify the authenticity of packages downloaded from the PostgreSQL repository.

Run the command below:

wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -

Adding the PostgreSQL repository GPG key to apt.

Step 3: Update the Package List

After adding the official PostgreSQL repository, update the package list to ensure you install the latest PostgreSQL package.

sudo apt update

Step 4: Install PostgreSQL

To install PostgreSQL and the PostgreSQL contrib package (which provides additional features), run the following command:

sudo apt install postgresql postgresql-contrib

By default, the software creates a postgres user once you successfully install the database system. This user account has the default postgres role.

Method 2: Install PostgreSQL from Local Ubuntu Repository

The PostgreSQL packages provided by the Ubuntu repositories are maintained and supported by the Ubuntu developers. This ensures compatibility with the Ubuntu system and adherence to Ubuntu’s packaging standards.

However, the PostgreSQL versions available in the Ubuntu repositories may not always be the latest releases. The reasoning is that Ubuntu prioritizes stability and long-term support over providing the newest features.

Follow the steps below to install PostgreSQL from the default Ubuntu repository.

Step 1: Check Available PostgreSQL Version

Before you decide whether you want to set up PostgreSQL from the Ubuntu repository, verify which versions are available. Update the repository and then run the command:

apt show postgresql

The output provides all the necessary information about the package, including the release number and size.

Show PostgreSQL package version information.

Step 2: Install PostgreSQL Package

To install the PostgreSQL version accessible from the local repository, use the following command:

sudo apt install postgresql postgresql-contrib

Wait for the process to finish, and you have successfully installed PostgreSQL on Ubuntu.

Verify PostgreSQL Installation

Verify that PostgreSQL has been installed by checking the PostgreSQL service status. Run the command below:

sudo systemctl status postgresql

Verify PostgreSQL installation on Ubuntu.

If everything is installed correctly, the output shows the PostgreSQL service status as active.

Connect to PostgreSQL

To establish a connection with the database, log into the postgres account with:

sudo su - postgres

Next, open a postgres prompt using the command:

psql

Connecting to PostgreSQL in Ubuntu.

Create a New User on PostgreSQL

PostgreSQL includes the client utility, which allows you to create a new user from the terminal without connecting to the database. The syntax for creating a new user is:

sudo -u postgres createuser -e [username]

Replace [username] with the actual user name of the user you want to create. For example:

Creating a new PostgreSQL user in Ubuntu.

Note: For other ways of creating a user in PostgreSQL and securing access, refer to our in-depth tutorial for creating a PostgreSQL user.

Create a New Database on PostgreSQL

  • Using the CREATE DATABASE SQL statement. Creates a database from the PostgreSQL shell prompt and requires appropriate privileges.
  • Via the command line. Uses the createdb command, which can be directly run from the command line.
  • Using the GUI pgadmin program.

For this tutorial, we will focus on using the CREATE DATABASE statement.

Follow the steps below:

1. Log in to the postgres prompt as a user that has the appropriate privileges for creating a database. We will log in as postgres :

sudo su - postgres
psql

2. Use the following syntax to create a database:

CREATE DATABASE [dbname]; 

Replace [dbname] with the database name. For example:

Creating a new database in PostgreSQL.

Check Connection Information

If you are connected to PostgreSQL and want to see details of the connection, use the command:

\conninfo

The output displays information on the database name, the account you are logged in, the socket path, and the port number.

Checking the PostgreSQL connection information in Ubuntu.

This article should help you set up PostgreSQL. Whether you decide to install from the PostgreSQL repository or the local Ubuntu repository, both installations are simple and easy to do.

Was this article helpful?
Bosko Marijan

Having worked as an educator and content writer, combined with his lifelong passion for all things high-tech, Bosko strives to simplify intricate concepts and make them user-friendly. That has led him to technical writing at PhoenixNAP, where he continues his mission of spreading knowledge.

Next you should read
March 14, 2024

Workbench is a visual tool for managing MySQL databases. Its graphical interface allows administrators and.

November 18, 2019

This simple tutorial analyses the commands used to list all user accounts in MySQL. Learn about additional.

February 28, 2024

MariaDB is an open-source, fully compatible, relational database management system. It is commonly used as a.

February 22, 2024

PostgreSQL is an open-source relational database management system. In this tutorial learn how to connect.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *