Основные команды PostgreSQL
Войти в консоль
sudo -u postgres psql
Войти под определенный пользователем
psql -U username -h 127.0.0.1 dbname
Показать БД
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+---------+---------+-----------------------
postgres | postgres | UTF8 | C.UTF-8 | C.UTF-8 |
template0 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
(3 rows)
Добавить БД
postgres=# CREATE DATABASE test;
CREATE DATABASE
Добавить пользователя
postgres=# CREATE USER test;
CREATE ROLE
Добавления прав для пользователя
ALTER USER box CREATEDB CREATEROLE LOGIN SUPERUSER;
Добавить права пользователю на работу внутри схемы public
\с test_db
grant usage, create on schema public to test_db;
Добавить все привилегии на определенную базу для определённого пользователя.
postgres=# GRANT ALL PRIVILEGES ON DATABASE "namedb" to username;
GRANT
Установка или сброс пароля пользователя
postgres=# ALTER USER username WITH PASSWORD 'password';
ALTER ROLE
Подключиться к нужной БД
postgres-# \connect pepper
You are now connected to database "test" as user "postgres".
Показать размер текущей БД
SELECT pg_size_pretty(pg_database_size(current_database()));
pg_size_pretty
----------------
8457 kB
(1 row)
Пример создания таблицы
CREATE TABLE article (
article_id bigserial primary key,
article_name varchar(20) NOT NULL,
article_desc text NOT NULL,
date_added timestamp default NULL
);
Показать размер Таблицы
SELECT pg_size_pretty(pg_relation_size('electronics'));
pg_size_pretty
----------------
104 kB
(1 row)
Колличество строк в таблице
SELECT count(*) FROM electronics;
count
-------
301
(1 row)
Удалить все из таблицы
DELETE FROM electronics;
DELETE 326
Посмотреть Атрибуты на Роли
postgres=# \du
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------------------+-----------
go | Superuser, No inheritance, Create DB | {}
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
Показать таблицы в текущей БД
\dt
List of relations
Schema | Name | Type | Owner
--------+----------+-------+----------
public | products | table | postgres
(1 row)
Удалить все таблицы в бд, команда только выведет команды на удаление
SELECT 'drop table if exists "' || tablename || '" cascade;' as pg_tbl_drop
FROM pg_tables
WHERE schemaname='public';
SQL Запрос для вывода таблиц из определенной схемы
SELECT *
FROM pg_catalog.pg_tables
WHERE schemaname != 'pg_catalog' AND
schemaname != 'information_schema';
Показать колличество сессий
SELECT * FROM pg_settings WHERE name = 'max_connections';