15个高级的PostgreSQL命令的例子

15个高级的PostgreSQL命令的例子,第1张

概述15 Advanced PostgreSQL Commands with Examples Some of the open source application comes with postgreSQL database. To maintain those application, companies may not hire a fulltime postgreSQL DBA. Inste 15 Advanced Postgresql Commands with Examples

Some of the open source application comes with postgresql database. To maintain those application,companIEs may not hire a fulltime postgresql DBA. Instead they may request the existing Oracle DBA,or linux system administrator,or programmers to maintain the potgresql. In this article let discuss about the 15 practical postgresql database commands which will be useful to both DBA and expert psql users.

1. How to find the largest table in the postgresql database?

$ /usr/local/pgsql/bin/psql testWelcome 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 quittest=# SELECT relname,relpages FROM pg_class ORDER BY relpages DESC;              relname              | relpages-----------------------------------+---------- pg_proc                           |       50 pg_proc_proname_args_nsp_index    |       40 pg_depend                         |       37 pg_attribute                      |       30


If you want only the first biggest table in the postgres database then append the above query with limit as:

# SELECT relname,relpages FROM pg_class ORDER BY relpages DESC limit 1; relname | relpages---------+---------- pg_proc |       50(1 row)

relname– name of the relation/table. relpages– relation pages ( number of pages,by default a page is 8kb ) pg_class– system table,which maintains the details of relations limit 1– limits the output to display only one row. 2. How to calculate postgresql database size in disk ?

pg_database_size is the function which gives the size of mentioned database. It shows the size in bytes.

# SELECT pg_database_size('geekdb');pg_database_size------------------         63287944(1 row)


If you want it to be shown pretty,then use pg_size_pretty function which converts the size in bytes to human understandable format.

# SELECT pg_size_pretty(pg_database_size('geekdb')); pg_size_pretty---------------- 60 MB(1 row)
3. How to calculate postgresql table size in disk ?

This is the total disk space size used by the mentioned table including index and toasted data. You may be interested in kNowing only the size of the table excluding the index then use the following command.

# SELECT pg_size_pretty(pg_total_relation_size('big_table')); pg_size_pretty---------------- 55 MB(1 row)
How to find size of the postgresql table ( not including index ) ?

Use pg_relation_size instead of pg_total_relation_size as shown below.

# SELECT pg_size_pretty(pg_relation_size('big_table')); pg_size_pretty---------------- 38 MB(1 row)
4. How to vIEw the indexes of an existing postgresql table ?
Syntax: # \d table_name

As shown in the example below,at the end of the output you will have a section Titled as indexes,if you have index in that table. In the example below,table pg_attribute has two btree indexes. By default postgres uses btree index as it good for most common situations.

test=# \d pg_attribute   table "pg_catalog.pg_attribute"    Column     |   Type   | ModifIErs---------------+----------+----------- attrelID      | oID      | not null attname       | name     | not null atttypID      | oID      | not null attstattarget | integer  | not null attlen        | smallint | not null attnum        | smallint | not null attndims      | integer  | not null attcacheoff   | integer  | not null atttypmod     | integer  | not null attbyval      | boolean  | not null attstorage    | "char"   | not null attalign      | "char"   | not null attnotnull    | boolean  | not null atthasdef     | boolean  | not null attisdropped  | boolean  | not null attislocal    | boolean  | not null attinhcount   | integer  | not nullIndexes:    "pg_attribute_relID_attnam_index" UNIQUE,btree (attrelID,attname)    "pg_attribute_relID_attnum_index" UNIQUE,attnum)
5. How to specify postgresql index type while creating a new index on a table ?

By default the indexes are created as btree. You can also specify the type of index during the create index statement as shown below.

Syntax: CREATE INDEX name ON table USING index_type (column);# CREATE INDEX test_index ON numbers using hash (num);
6. How to work with postgresql transactions ? How to start a transaction ?
# BEGIN -- start the transaction.
How to rollback or commit a postgresql transaction ?

All the operations performed after the BEGIN command will be committed to the postgresql database only you execute the commit command. Use rollback command to undo all the transactions before it is committed.

# RolLBACK -- rollbacks the transaction.# COMMIT -- commits the transaction.
7. How to vIEw execution plan used by the postgresql for a sql query ?
# EXPLAIN query;
8. How to display the plan by executing the query on the server sIDe ?

This executes the query in the server sIDe,thus does not shows the output to the user. But shows the plan in which it got executed.

# EXPLAIN ANALYZE query;
9. How to generate a serIEs of numbers and insert it into a table ?

This inserts 1,2,3 to 1000 as thousand rows in the table numbers.

# INSERT INTO numbers (num) VALUES ( generate_serIEs(1,1000));
10. How to count total number of rows in a postgresql table ?

This shows the total number of rows in the table.

# select count(*) from table;


Following example gives the total number of rows with a specific column value is not null.

# select count(col_name) from table;


Following example displays the distinct number of rows for the specifIEd column value.

# select count(distinct col_name) from table;
11. How can I get the second maximum value of a column in the table ? First maximum value of a column
# select max(col_name) from table;

Second maximum value of a column
# SELECT MAX(num) from number_table where num  < ( select MAX(num) from number_table );
12. How can I get the second minimum value of a column in the table ? First minimum value of a column
# select min(col_name) from table;

Second minimum value of a column

# SELECT MIN(num) from number_table where num > ( select MIN(num) from number_table );
13. How to vIEw the basic available datatypes in postgresql ?

Below is the partial output that displays available basic datatypes and it’s size.

test=# SELECT typname,typlen from pg_type where typtype='b';    typname     | typlen----------------+-------- bool           |      1 bytea          |     -1 char           |      1 name           |     64 int8           |      8 int2           |      2 int2vector     |     -1
typname – name of the datatype typlen – length of the datatype 14. How to redirect the output of postgresql query to a file?
# \o output_file# SELECT * FROM pg_class;

The output of the query will be redirected to the “output_file”. After the redirection is enabled,the select command will not display the output in the stdout. To enable the output to the stdout again,execute the \o without any argument as mentioned below.

# \o


As explained in our earlIEr article,you can alsobackup and restore postgreSQL database using pg_dump and psql.

15. Storing the password after encryption.

Postgresql database can encrypt the data using the crypt command as shown below. This can be used to store your custom application username and password in a custom table.

# SELECT crypt ( 'sathiya',gen_salt('md5') );
Postgresql crypt function Issue:

The postgresql crypt command may not work on your environment and display the following error message.

ERROR:  function gen_salt("unkNown") does not existHINT:  No function matches the given name and argument types.         You may need to add explicit type casts.
Postgresql crypt function Solution:

To solve this problem,installl the postgresql-contrib-your-version package and execute the following command in the postgresql prompt.

# \i /usr/share/postgresql/8.1/contrib/pgcrypto.sql
总结

以上是内存溢出为你收集整理的15个高级的PostgreSQL命令例子全部内容,希望文章能够帮你解决15个高级的PostgreSQL命令的例子所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/1172423.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-02
下一篇 2022-06-02

发表评论

登录后才能评论

评论列表(0条)

保存