Showing posts with label postgreSQL. Show all posts
Showing posts with label postgreSQL. Show all posts

Friday, May 22, 2026

pg_cron setup in PostgreSQL

pg_cron is a PostgreSQL extension that lets you run scheduled jobs (like Linux cron) directly inside PostgreSQL.


1.RHEL / CentOS / Rocky Linux install


sudo yum install pg_cron_15


2. Enable pg_cron in PostgreSQL


/var/lib/pgsql/15/data/postgresql.conf


Add:


shared_preload_libraries = 'pg_cron'


cron.database_name = 'postgres'


3. Restart PostgreSQL


pg_ctl


4. Create the Extension


psql -U postgres


Create extension:


CREATE EXTENSION pg_cron;


Verify:


SELECT * FROM pg_extension WHERE extname = 'pg_cron';


5. Schedule Jobs


CREATE EXTENSION pg_cron;


PostgreSQL creates a schema named cron inside the database where the extension was installed (commonly the postgres database).


objects like:


cron.job

cron.job_run_details

cron.schedule()

cron.unschedule()



select * from  cron.job;


select * from  cron.job_run_details;


select * from cron.schedule();


select * from cron.unschedule();


Important detail:


pg_cron is installed per database, not cluster-wide.


If you created the extension in postgres DB:


Check extension location:


SELECT extname, extnamespace::regnamespace

FROM pg_extension

WHERE extname='pg_cron';




postgres=# select version();

                                                 version

---------------------------------------------------------------------------------------------------------

 PostgreSQL 15.8 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 8.5.0 20210514 (Red Hat 8.5.0-22), 64-bit

(1 row)


postgres=# CREATE EXTENSION pg_cron;

CREATE EXTENSION

postgres=# SELECT * FROM pg_extension WHERE extname = 'pg_cron';

  oid  | extname | extowner | extnamespace | extrelocatable | extversion |         extconfig         | extcondition

-------+---------+----------+--------------+----------------+------------+---------------------------+---------------

 24853 | pg_cron |       10 |           11 | f              | 1.6        | {24856,24855,24875,24874} | {"","","",""}

(1 row)


postgres=# SELECT extname, extnamespace::regnamespace

postgres-# FROM pg_extension

postgres-# WHERE extname='pg_cron';

 extname | extnamespace

---------+--------------

 pg_cron | pg_catalog

(1 row)


postgres=# \dn

      List of schemas

  Name  |       Owner

--------+-------------------

 admin  | postgres

 cron   | postgres

 public | pg_database_owner

(3 rows)


postgres=#



SELECT * FROM pg_available_extensions

postgres-# WHERE name = 'pg_cron';

  name   | default_version | installed_version |           comment

---------+-----------------+-------------------+------------------------------

 pg_cron | 1.6             | 1.6               | Job scheduler for PostgreSQL

(1 row)




Find job ID & name:


SELECT jobid, jobname

FROM cron.job;


 SELECT jobid, jobname

postgres-# FROM cron.job;

 jobid |      jobname

-------+-------------------

     1 | db-size-collector

(1 row)



Remove:


SELECT cron.unschedule('db-size-collector');


Check Execution History

SELECT *

FROM cron.job_run_details

ORDER BY start_time DESC

LIMIT 10;


Verify Job Created

SELECT * FROM cron.job;


Tuesday, December 21, 2021

How to stop /start /status of PostgreSQL service on linux server

 How to stop /start /status of PostgreSQL service


<linux_server>>:/postgresql_SW> psql --version 

psql (PostgreSQL) 12.1pg_ctl status


<linux_server>>:/postgresql_SW>pg_ctl: server is running (PID: 16915)

/usr/pgsql-11/bin/postgres "-D" "/var/lib/pgsql/11/data"

<linux_server>>:/postgresql_SW>  pg_ctl stop

waiting for server to shut down.... done

server stopped



<linux_server>>:/postgresql_SW> pg_ctl status

pg_ctl: no server running



<linux_server>>:/postgresql_SW> pg_ctl start

waiting for server to start....2021-09-13 13:16:43.724 UTC [24156] LOG:  listening on IPv4 address "0.0.0.0", port 5432

2021-09-13 13:16:43.724 UTC [24156] LOG:  listening on IPv6 address "::", port 5432

2021-09-13 13:16:43.725 UTC [24156] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"

2021-09-13 13:16:43.731 UTC [24156] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"

2021-09-13 13:16:43.747 UTC [24156] LOG:  redirecting log output to logging collector process

2021-09-13 13:16:43.747 UTC [24156] HINT:  Future log output will appear in directory "log".

 done

server started



<linux_server>>:/postgresql_SW> pg_ctl -D /var/lib/pgsql/11/data stop

waiting for server to shut down.... done

server stopped



<linux_server>>:/postgresql_SW> pg_ctl -D /var/lib/pgsql/11/data status

pg_ctl: no server running



<linux_server>>:/postgresql_SW> pg_ctl -D /var/lib/pgsql/11/data start

waiting for server to start....2021-09-13 13:17:19.374 UTC [24204] LOG:  listening on IPv4 address "0.0.0.0", port 5432

2021-09-13 13:17:19.374 UTC [24204] LOG:  listening on IPv6 address "::", port 5432

2021-09-13 13:17:19.376 UTC [24204] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"

2021-09-13 13:17:19.381 UTC [24204] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"

2021-09-13 13:17:19.397 UTC [24204] LOG:  redirecting log output to logging collector process

2021-09-13 13:17:19.397 UTC [24204] HINT:  Future log output will appear in directory "log".

 done

server started

how to get DDL of table in postgreSQL using pg_dump

 how to get DDL of table in PostgreSQL

********************************************


<linux_server>:/var/opt/pgsql11/data/tablespace/app_tablespace> pg_dump -t 'public.phonebook' -d testdb

--

-- PostgreSQL database dump

--


-- Dumped from database version 11.6

-- Dumped by pg_dump version 12.1


SET statement_timeout = 0;

SET lock_timeout = 0;

SET idle_in_transaction_session_timeout = 0;

SET client_encoding = 'SQL_ASCII';

SET standard_conforming_strings = on;

SELECT pg_catalog.set_config('search_path', '', false);

SET check_function_bodies = false;

SET xmloption = content;

SET client_min_messages = warning;

SET row_security = off;


SET default_tablespace = '';


--

-- Name: phonebook; Type: TABLE; Schema: public; Owner: postgres

--


CREATE TABLE public.phonebook (

    phone character varying(32),

    firstname character varying(32),

    lastname character varying(32),

    address character varying(64)

);



ALTER TABLE public.phonebook OWNER TO postgres;


--

-- Data for Name: phonebook; Type: TABLE DATA; Schema: public; Owner: postgres

--


COPY public.phonebook (phone, firstname, lastname, address) FROM stdin;

+1 123 456 7890 John    Doe     North America

\.



--

-- PostgreSQL database dump complete

--


Monday, November 29, 2021

Step by step to create tablespace in PostgreSQL RDS instance

Step by step to create tablespace in PostgreSQL RDS instance


when you create tablespace in RDS postgreSQL instance ,you can  give the location  as any string.


Tablespace location  will be "PREFIXED " by /rdsdbdata/db/base/tablespace


CREATE TABLESPACE testTBSspace LOCATION '/test_data';



postgreSQL_dev=> \db+ testtbsspace

                                                   List of tablespaces

     Name     |  Owner   |                Location                 | Access privileges | Options |  Size   | Description

--------------+----------+-----------------------------------------+-------------------+---------+---------+-------------

 testtbsspace | db_admin | /rdsdbdata/db/base/tablespace/test_data |                   |         | 0 bytes |

(1 row)



drop  TABLESPACE testTBSspace;



postgreSQL_dev=> drop  TABLESPACE testTBSspace;

DROP TABLESPACE

postgreSQL_dev=> \db+ testtbsspace

                            List of tablespaces

 Name | Owner | Location | Access privileges | Options | Size | Description

------+-------+----------+-------------------+---------+------+-------------

(0 rows)

Friday, November 26, 2021

Step by step Table migration from AWS RDS postgreSQL to other PostgreSQL DB instance

 Step by step Table migration from AWS RDS postgreSQL to other PostgreSQL DB instance:

steps:

1.use the pg_dump to take the backup to plain file

2.restore on target using psql import.


pg_dump --username=db_admin --host=<host_name_aws endpoint> --port=5700 --format=plain --file=backup.sql  --dbname=postgrsql_db_dev  --table=test_table1




-rw-r--r-- 1 postgres postgres  2294 Nov 26 08:30 backup.sql

<server_name>:~/aws> cat backup.sql

--

-- PostgreSQL database dump

--


-- Dumped from database version 11.5

-- Dumped by pg_dump version 12.1


SET statement_timeout = 0;

SET lock_timeout = 0;

SET idle_in_transaction_session_timeout = 0;

SET client_encoding = 'UTF8';

SET standard_conforming_strings = on;

SELECT pg_catalog.set_config('search_path', '', false);

SET check_function_bodies = false;

SET xmloption = content;

SET client_min_messages = warning;

SET row_security = off;


SET default_tablespace = '';


--

-- Name: test_table1; Type: TABLE; Schema: public; Owner: app456_admin

--


CREATE TABLE public.test_table1 (

    id integer NOT NULL,

    app_id integer NOT NULL,

    variant_id integer NOT NULL,

    principal_id integer NOT NULL,

    include boolean NOT NULL

);



ALTER TABLE public.test_table1 OWNER TO app456_admin;


--

-- Name: test_table1_id_seq; Type: SEQUENCE; Schema: public; Owner: app456_admin

--


CREATE SEQUENCE public.test_table1_id_seq

    AS integer

    START WITH 1

    INCREMENT BY 1

    NO MINVALUE

    NO MAXVALUE

    CACHE 1;



ALTER TABLE public.test_table1_id_seq OWNER TO app456_admin;


--

-- Name: test_table1_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: app456_admin

--


ALTER SEQUENCE public.test_table1_id_seq OWNED BY public.test_table1.id;



--

-- Name: test_table1 id; Type: DEFAULT; Schema: public; Owner: app456_admin

--


ALTER TABLE ONLY public.test_table1 ALTER COLUMN id SET DEFAULT nextval('public.test_table1_id_seq'::regclass);



--

-- Data for Name: test_table1; Type: TABLE DATA; Schema: public; Owner: app456_admin

--


COPY public.test_table1 (id, app_id, variant_id, principal_id, include) FROM stdin;

4       80      43      51      t

5       89      52      51      t

\.



--

-- Name: test_table1_id_seq; Type: SEQUENCE SET; Schema: public; Owner: app456_admin

--


SELECT pg_catalog.setval('public.test_table1_id_seq', 5, true);



--

-- Name: test_table1 test_table1_pkey; Type: CONSTRAINT; Schema: public; Owner: app456_admin

--


ALTER TABLE ONLY public.test_table1

    ADD CONSTRAINT test_table1_pkey PRIMARY KEY (id);



--

-- Name: test_table1_by_app_id_variant_id; Type: INDEX; Schema: public; Owner: app456_admin

--


CREATE INDEX test_table1_by_app_id_variant_id ON public.test_table1 USING btree (app_id, variant_id);



--

-- PostgreSQL database dump complete

--

***************************restore using import**************************************


psql --username=testuser --host=<host_name> --port=5432  --file=backup.sql  --dbname=testdb  --table=test_table1

<server_name>:~/aws> psql --username=testuser --host=<host_name> --port=5432  --file=backup.sql  --dbname=testdb  --table=test_table1

SET

SET

SET

SET

SET

 set_config

------------


(1 row)


SET

SET

SET

SET

SET

CREATE TABLE

ALTER TABLE

CREATE SEQUENCE

ALTER TABLE

ALTER SEQUENCE

ALTER TABLE

COPY 2

 setval

--------

      5

(1 row)


ALTER TABLE

CREATE INDEX




<server_name>:~/aws> psql

psql (12.1, server 11.6)

Type "help" for help.


postgres=# \c testdb

psql (12.1, server 11.6)

You are now connected to database "testdb" as user "postgres".


after Data migration to  new PostgreSQL instance

testdb=# select * from test_table1;

 id1 | app_id | variant_id | principal_id | include

----+--------+------------+--------------+---------

  14 |     480 |         543 |          751 | t

  45 |     489 |         552 |          751 | t

(2 rows)

Thursday, November 25, 2021

script to get the tablespace location and owner of the tablespace in PostgreSQL

 script to get the tablespace location in PostgreSQL


Use pg_tablespace_location(tablespace_oid)(PostgreSQL 9.2+) to get the path in the file system where the tablespace is located.


You'll get oid of tablespace from pg_tablespace, so the query should be


select spcname

      ,pg_tablespace_location(oid) 

from   pg_tablespace;



  spcname    |                         pg_tablespace_location

--------------+-------------------------------------------------------------------------

 pg_default   |

 pg_global    |

 testdb2_data | /rdsdbdata/db/base/tablespace/rdsdbdata/db/base/tablespace/testdb2_data

(3 rows)


******************create DB to specific tablespace in postgres SQL****************


postgres=# create database TEST tablespace TBSspace;

CREATE DATABASE


*****************************

testdb2_connect_prod=> select version();

                                                 version

---------------------------------------------------------------------------------------------------------

 PostgreSQL 11.5 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-11), 64-bit

(1 row)



postgres_db_dev=> \du db_admin

                        List of roles

 Role name |          Attributes           |    Member of

-----------+-------------------------------+-----------------

 db_admin  | Create role, Create DB       +| {rds_superuser}

           | Password valid until infinity |



postgres_db_dev=>  SELECT spcname,spcowner FROM pg_tablespace;

   spcname    | spcowner

--------------+----------

 pg_default   |       10

 pg_global    |       10

 testdb2_data |    16410

(3 rows)


postgres_db_dev=> select usename from pg_user where usesysid='16410';

    usename

---------------

 testdb2_admin

(1 row)



testdb2_workbench_dev=> select current_database();

   current_database

-----------------------

 testdb2_workbench_dev

(1 row)


postgres_db_dev=> SELECT current_user;

 current_user

---------------

 testdb2_admin

(1 row)


Error while creating database in PostgreSQL

 issue:

when I tried to create new DB in postgreSQL got the below error and analyzed the issue and found the solution.

postgres_DEV=> create database postgres_db_dev1;

ERROR:  source database "template1" is being accessed by other users

DETAIL:  There is 1 other session using the database.


check which user/process holding the template DB

postgres_DEV=> select datname,pid,usename,application_name,client_hostname,client_port from pg_stat_activity where datname='template1';

  datname  | pid  | usename  |     application_name     | client_hostname | client_port

-----------+------+----------+--------------------------+-----------------+-------------

 template1 | 1871 | DB_admin | pgAdmin 4 - DB:template1 |                 |       51681

(1 row)


Solution:

Kill a  template1 session on PostgreSQL database:

select pg_terminate_backend(pid) 

from pg_stat_activity

where pid = '1871';



postgres_DEV=> select pg_terminate_backend(pid)

postgres_DEV-> from pg_stat_activity

postgres_DEV-> where pid = '1871';

 pg_terminate_backend

----------------------

 t

(1 row)


postgres_DEV=> CREATE DATABASE test2 TEMPLATE template1;


CREATE DATABASE


Sunday, November 14, 2021

script to find postgres db size:

 script to find postgres db size:


SELECT

    pg_database.datname,

    pg_size_pretty(pg_database_size(pg_database.datname)) AS size

    FROM pg_database;


postgres=# \l+ postgres

                                                               List of databases

   Name   |  Owner   | Encoding  | Collate | Ctype |   Access privileges    |  Size   | Tablespace |                Description

----------+----------+-----------+---------+-------+------------------------+---------+------------+--------------------------------------------

 postgres | postgres | SQL_ASCII | C       | C     | =Tc/postgres          +| 7941 kB | pg_default | default administrative connection database

          |          |           |         |       | postgres=CTc/postgres +|         |            |

          |          |           |         |       | kmonitor00=c/postgres +|         |            |

          |          |           |         |       | testmonitor=c/postgres |         |            |

(1 row)



select t1.datname AS db_name,  

       pg_size_pretty(pg_database_size(t1.datname)) as db_size

from pg_database t1

order by pg_database_size(t1.datname) desc;


       datname        |  size

----------------------+---------

 testdbTest          | 7941 kB

 template1            | 7941 kB

 template0            | 7801 kB

 testdba              | 7941 kB

script to check what are the tables available on specific tablespace:

 script to check what are the tables available on specific tablespace:

\db+ ts_primary

postgres=# \db+ test_data

                                                   List of tablespaces

   Name    |   Owner    |               Location                | Access privileges | Options |    Size    | Description

-----------+------------+---------------------------------------+-------------------+---------+------------+-------------

 test_data | test_admin | /var/opt/pgsql12/tablespace/test_data |                   |         | 4096 bytes |

(1 row)

query/script to list tablespace in PostgreSQL:

 query to list tablespace in PostgreSQL:


SELECT spcname FROM pg_tablespace;



to  list all Tablespace in 


postgres=# \db

      

                                               List of tablespaces

    Name    |   Owner    |             Location              | Access privileges | Options |  Size  | Description

------------+------------+-----------------------------------+-------------------+---------+--------+-------------

 test_data  | test_admin | /opt/pgsql12/tablespace/test_data |                   |         | 59 GB  |

 pg_default | postgres   |                                   |                   |         | 35 MB  |

 pg_global  | postgres   |                                   |                   |         | 399 kB |


query to find out memory values of postgresql memory:

 query the list of parameter

select name,setting from pg_settings;


query the list of parameter requires restart

select name,setting from pg_settings where context='postmaster';


show command used to display the vaule of parameter


query to find out memory values of postgresql memory:


select name,setting from pg_settings where name LIKE '%shared_buffer%';

      name      | setting

----------------+---------

 shared_buffers | 16384




postgres=# show shared_buffers;

 shared_buffers

----------------

 128MB

(1 row)

How to backup database object definitions in PostgreSQL database?

 Sometimes, you want to backup only database object definitions, not the data This is helpful in the testing phase, which you do not want to move test data to the live system.


To back up objects in all databases, including roles, tablespaces, databases, schemas, tables, indexes, triggers, functions, constraints, views, ownerships, and privileges, you use the following command:


pg_dumpall --schema-only > c:\pgdump\definitiononly.sql

Code language: CSS (css)

If you want to back up role definition only, use the following command:


pg_dumpall --roles-only > c:\pgdump\allroles.sql

Code language: CSS (css)

If you want to backup tablespaces definition, use the following command:


pg_dumpall --tablespaces-only > c:\pgdump\allroles.sql

Code language: CSS (css)

Further Reading

script to find PostgreSQL configuration file location

 command/script to find postgreSQL configuration file location

*****************************************************



postgres=# SHOW config_file;

              config_file

---------------------------------------

 /var/opt/pgsql12/data/postgresql.conf

script check the all active connections to the db database by using the following query:

script check the all active connections to the db database by using the following query: 


select usename,datname FROM pg_stat_activity;


SELECT  *

FROM pg_stat_activity

WHERE datname = 'db';



terminate all the connections to the db database by using the following statement:


SELECT

    pg_terminate_backend (pid)

FROM

    pg_stat_activity

WHERE

    datname = 'db';

Thursday, August 12, 2021

what is the query to list tablespace in PostgreSQL?

 


query to list tablespace in PostgreSQL:


SELECT spcname FROM pg_tablespace;


\db+

                                            List of tablespaces

    Name    |   Owner    |             Location              | Access privileges | Options |  Size  | Description

------------+------------+-----------------------------------+-------------------+---------+--------+-------------

 DB_data  | DB_admin | /opt/pgsql12/tablespace/DBdata |                   |         | 59 GB  |

 pg_default | postgres   |                                   |                   |         | 35 MB  |

 pg_global  | postgres   |                                   |                   |         | 399 kB |


PostgreSQL Database Design and implementation Standard

PostgreSQL Database Design & implementation Standard:

its been a while  that I am working on PostgreSQL and would like to create standard for DB cluster installation.


 Installation:

install the postgres software under the below directory and user postgres:


Postgres Binary tablespace----> /postgres/<App_name>/<postgres/version>


pre-work 


1.we  need to create separate OS user to install & run the PostgrSQL cluster ,e,g postgres OS User.


2.create separate File system for Data,Temp,Postgres Binary and WAL(write Ahead Log),Backup


3.folder sturcture should be like below


Data tablespace----> /postgres/<App_name>/Data/--->used for Data

Temp tablespace---->/postgres/<App_name>/Temp/---->used for sorting, Temp

Postgres Binary tablespace----> /postgres/<App_name>/<postgres/version>

WAL tablespace---->/postgres/<App_name>/WAL/--->To store WAL files

Backup tablespace----> /postgres/<App_name>/Backup/--->to store backup files


3.we can have profile  for Postgres OS user.

we can Have :PG_HOME,PG_DATA,PG_DATABASE,PG_BACKUP,PG_HOSTNAME

4.Port Number ---configure Non-Default port number  5432


Memory configuration 

As per the Industry standard ,Please allocate the Memory for Each Layer in Postgres like below


shared_buffers - Non Prod==>20-30% of total, Non Prod==>RAM 20% of total RAM---->Key Memory component for PostgreSQL cluster


temp_buffers - Non Prod==>10-15% of total RAM,Non Prod==> 10% of total RAM----> Memory component for Temp Buffer


work_mem - Non Prod==>5-10% of total RAM ,5% of total RAM-


maintenance_work_mem - 10-15% of total RAM  10% of total RAM-


DB creation

1.create separate tablespace for each DB and park the DB data on that tablespace,it will be easy to recover during server crash.

2.Add the DB parameter accoridng to  below for Prod & Non Prod systems

max_connections - For Dev systems, 100-200. For Production, 500-1000 (Depending on application requirements)


Authentication/Security

Do not leave the defult setting and change all connection thru encrypted and password session on hba file

pg_hba.conf entries (Allow specific IP)

host     all             all            172.17.0.0/32           md5


Monitoring Tools:

I believe Community version needs to buy separate license for the below PostgreSQL monitoring tools,But Enterprise DB license must include PEM monitoring license.

PEM(Postgres Enterprise Manager) just we need to install the agent on the DB server and GUI based tool to monitor Postgres service.


ZABBIX

NAGIOS

PEM


Backup Policy:

Prod we can enable the WAL  to have get the Point in time recovery ,for Non Prod ,No need  to enable the WAL


backup types :

we use the pg_dump backup utility for Community version and Enterprise DB we can use BART tools.

we can schedule the backup backup jobs under cron

1.pg_dump

2.BART tool(EDB)


Maintenance Jobs needed:

1.Vacuum job 

2.Backup Job

3.stats gathering


Thursday, September 1, 2016

PostgreSQL database basic administration commands

1. How to change PostgreSQL root user password?

$ /usr/local/pgsql/bin/psql postgres postgres
Password: (oldpassword)
# ALTER USER postgres WITH PASSWORD 'tmppassword';

$ /usr/local/pgsql/bin/psql postgres postgres
Password: (tmppassword)

Changing the password for a normal postgres user is similar as changing the password of the root user. Root user can change the password of any user, and the normal users can only change their passwords as Unix way of doing.

# ALTER USER username WITH PASSWORD 'tmppassword';

2. How to setup PostgreSQL SysV startup script?

$ su - root

# tar xvfz postgresql-8.3.7.tar.gz

# cd postgresql-8.3.7

# cp contrib/start-scripts/linux /etc/rc.d/init.d/postgresql

# chmod a+x /etc/rc.d/init.d/postgresql

3. How to check whether PostgreSQL server is up and running?

$ /etc/init.d/postgresql status
Password:
pg_ctl: server is running (PID: 6171)
/usr/local/pgsql/bin/postgres "-D" "/usr/local/pgsql/data"
[Note: The status above indicates the server is up and running]

$ /etc/init.d/postgresql status
Password:
pg_ctl: no server running
[Note: The status above indicates the server is down]

4. How to start, stop and restart PostgreSQL database?

# service postgresql stop
Stopping PostgreSQL: server stopped
ok

# service postgresql start
Starting PostgreSQL: ok

# service postgresql restart
Restarting PostgreSQL: server stopped
ok

5. How do I find out what version of PostgreSQL I am running?

$ /usr/local/pgsql/bin/psql test
Welcome to psql 8.3.7, the PostgreSQL interactive terminal.

Type:  \copyright for distribution terms
\h for help with SQL commands
\? for help with psql commands
\g or terminate with semicolon to execute query
\q to quit

test=# select version();
version
----------------------------------------------------------------------------------------------------
PostgreSQL 8.3.7 on i686-pc-linux-gnu, compiled by GCC gcc (GCC) 4.1.2 20071124 (Red Hat 4.1.2-42)
(1 row)

test=#

6. How to create a PostgreSQL user?

There are two methods in which you can create user.

Method 1: Creating the user in the PSQL prompt, with CREATE USER command.

# CREATE USER ramesh WITH password 'tmppassword';
CREATE ROLE

Method 2: Creating the user in the shell prompt, with createuser command.

$ /usr/local/pgsql/bin/createuser sathiya
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) n
Shall the new role be allowed to create more new roles? (y/n) n
CREATE ROLE

7. How to create a PostgreSQL Database?

There are two metods in which you can create two databases.

Method 1: Creating the database in the PSQL prompt, with createuser command.

# CREATE DATABASE mydb WITH OWNER ramesh;
CREATE DATABASE
Method 2: Creating the database in the shell prompt, with createdb command.

$ /usr/local/pgsql/bin/createdb mydb -O ramesh
CREATE DATABASE
* -O owner name is the option in the command line.

8. How do I get a list of databases in a Postgresql database?

# \l  [Note: This is backslash followed by lower-case L]
List of databases
Name | Owner | Encoding
----------+----------+----------
backup | postgres | UTF8
mydb | ramesh | UTF8
postgres | postgres | UTF8
template0 | postgres | UTF8
template1 | postgres | UTF8

9. How to Delete/Drop an existing PostgreSQL database?

# \l
List of databases
Name | Owner | Encoding
----------+----------+----------
backup | postgres | UTF8
mydb | ramesh | UTF8
postgres | postgres | UTF8
template0 | postgres | UTF8
template1 | postgres | UTF8

# DROP DATABASE mydb;
DROP DATABASE

10. Getting help on postgreSQL commands

\? will show PSQL command prompt help. \h CREATE will shows help about all the commands that starts with CREATE, when you want something specific such as help for creating index, then you need to give CREATE INDEX.

# \?

# \h CREATE

# \h CREATE INDEX

11. How do I get a list of all the tables in a Postgresql database?

# \d
On an empty database, you’ll get “No relations found.” message for the above command.

12. How to turn on timing, and checking how much time a query takes to execute?

# \timing — After this if you execute a query it will show how much time it took for doing it.

# \timing
Timing is on.

# SELECT * from pg_catalog.pg_attribute ;
Time: 9.583 ms

13. How To Backup and Restore PostgreSQL Database and Table?

We discussed earlier how to backup and restore postgres database and tables using pg_dump and psql utility.

14. How to see the list of available functions in PostgreSQL?

To get to know more about the functions, say \df+

# \df

# \df+

15. How to edit PostgreSQL queries in your favorite editor?

# \e
\e will open the editor, where you can edit the queries and save it. By doing so the query will get executed.

16. Where can I find the PostgreSQL history file?

Similar to the Linux ~/.bash_history file, postgreSQL stores all the sql command that was executed in a history filed called ~/.psql_history as shown below.

$ cat ~/.psql_history
alter user postgres with password 'tmppassword';
\h alter user
select version();
create user ramesh with password 'tmppassword';
\timing
select * from pg_catalog.pg_attribute;