Postgresql Command Line Cheat Sheet



Introduction to the PostgreSQL cheat sheet

If you’re using PostgreSQL to store and query your data, you might find yourself needing to look up the syntax of some common statements and queries. There’s no need to go searching for this information– we’ve rounded up some of the most common SQL statements and queries and created a PostgreSQL cheat sheet for you. This handy reference guide will help you perform many common PostgreSQL tasks using the psql command-line interface.

Note that SQL statements in psql must terminate with a semicolon. This syntax lets Postgres knows where a statement ends; otherwise, PostgreSQL will interpret the next line as an extension of that same command.

You can do some of them through a visual user interface, but that's not covered here. Knowing how to perform these operations on the command line means you can script them, and scripting means you can automate tests, check errors, and do data entry on the command line. This section isn't a full cheat sheet for psql. It covers the most common operations and shows them roughly in sequence, as you'd use. Connect to a specific database. For example, the following command connects to the 'employees'. PostgreSQL Cheat Sheet The PostgreSQL cheat sheet provides you with the common PostgreSQL commands and statements that enable you to work with PostgreSQL quickly and effectively. Download PostgreSQL cheat sheet We provide you with a 3-page PostgreSQL cheat sheet in PDF format. Command Line The Terminal Filesystem Navigation File Manipulation Command Line Lab. PostgreSQL Cheat Sheet Database Administration. PostgreSQL: Configuration Cheat Sheet. Service management commands: sudo service postgresql stop sudo service postgresql start sudo service postgresql restart. Changing verbosity & querying Postgres log: 1) First edit the config file, set a decent verbosity, save and restart postgres.

Another thing to keep in mind when constructing SQL statements is that PostgreSQL strings must always be enclosed using single quotation marks (e.g. 'string here'). Using double quotes will result in a syntax error.

Office 365 outlook uwm. You can press CTRL+C if you’d like to escape a command or exit from the results of a command.

Prerequisites to using PostgreSQL SQL commands in psql

Before we proceed with our PostgreSQL cheat sheet, let’s review a few prerequisites that are necessary to get the most out of this article. You should have PostgreSQL installed, and you’ll need to have a PostgreSQL role with access to a database in order to execute the SQL statement examples found in this article. You’ll also need to use psql, the command-line interface for PostgreSQL. Use the psql -V command to find out which version of the interface is installed on your machine.

Accessing PostgreSQL using the ‘psql’ command line interface

We can use the following syntax to access a PostgreSQL database on a localhost server. The command should be executed using the psql command-line interface:

psql postgres

The command shown above will try to connect to the PostgreSQL database named postgres.

You can also use the alternative syntax shown below to connect to PostgreSQL using a username, host and database name:

psql -U some_username -h 127.0.0.1 -d some_database

NOTE: Notice that a few different flags are used in this command syntax. The -U flag represents the Postgres username, and the -h flag indicates the host domain or IP address. The -d flag is used to provide the database name. Adobe 360 video. If only one parameter is supplied, psql will assume it is the database name.

PostgreSQL cheat sheet of useful SQL queries and commands

Line

The following section provides an overview of some of the most common SQL commands used to manage and alter Postgres roles, indexes and tables.

PostgreSQL cheat sheet to manage the roles and users

In Postgres, a role is the entity that is granted privileges to access and modify database and table data. A role can be either a user or a group. You can create a new role using the following syntax:

To add a username and password to the new role, simply use the command:

CREATEROLE new_role NOINHERIT
LOGIN PASSWORD 'mYpAsSwOrDyO!';

We can assign a new role to our current psql session:

The last command we’ll review in this section is used to create a user with an encrypted password:

CREATEUSER new_user
WITH ENCRYPTED PASSWORD 'mYpAsSwOrDyO!';

Grant privileges to a Postgres user or role

Now that we know how to create a user or role, let’s discuss how to grant a user privileges. The following command uses the GRANT CONNECT keyword to grant a Postgres user access to a specific database:

Postgresql command line cheat sheet free

Here’s how we can grant all privileges for public tables to the same user:

GRANTALL PRIVILEGES ONALLTABLES
IN SCHEMA public TO new_user;

Revoke all privileges for a PostgreSQL user or role

Not only can you grant privileges to a user, but you can also take them away. The following command will reverse the one shown above and REVOKEall of a role’s privileges for all tables:

REVOKEALL PRIVILEGES ONALLTABLES
IN SCHEMA public FROM new_user;

The same can be done for database privileges:

REVOKEALL PRIVILEGES ONDATABASE
some_db FROM new_user;

Last but not least, let’s look at an example of how to revoke database ownership for the user:

PostgreSQL cheat sheet commands for table views

Postgresql

In this section, we’ll look at some commands related to views. A PostgreSQL VIEW is a way of logically organizing data that’s meant to represent the column data of tables.

The following example uses the CREATE VIEW SQL keywords. It also uses the AS keyword to give the view database object a name:

CREATEVIEW some_view AS col_data;

Download sierra installer. The next example creates a view object that consists of the column names col1 and col2:

CREATEVIEW some_view(col1, col2)
ASSELECT col1, col2 FROM some_table;

If you need to DROP, or delete, a view from your database, here’s how to do it:

PostgreSQL cheat sheet commands for indices

In this section, we’ll look at some common commands used to manage indexes. To create an index, we use the following command:

CREATEINDEX some_index ON some_table(col_name, second_col);

The DROP INDEX command is used to remove a specified index from a table:

PostgreSQL cheat sheet commands for Triggers

In SQL, a TRIGGER is a callback or function that will automatically execute a SQL statement when a certain event occurs. The basic structure of a PostgreSQL trigger is shown below:

CREATETRIGGER some_trigger
[WHEN EVENT]ON some_table
[TRIGGERTYPE]EXECUTE stored_procedure;
Postgresql Command Line Cheat SheetPostgresql

NOTE: The WHEN EVENT and TRIGGER TYPE keywords are optional.

PostgreSQL cheat sheet commands for tables

The syntax for the SQL command used to create a new table looks like the following:

CREATETABLE some_table
(some_column +DATATYPE+ CONSTRAINTS [OPTIONAL]);

Let’s look at an example of how you can use the CREATE TABLE keyword to create a Postgres table comprised of a string column and an integer column:

CREATETABLE some_table (
id INTPRIMARYKEY,
some_str VARCHAR(30),
some_int INT
);

NOTE: Our example contains the PRIMARY KEY constraint, which tells Postgres to make the value of that particular column the main identifying information for the record.

If you need to rename a Postgres table, you can use the ALTER TABLE and RENAME commands:

To drop a table and all of its dependent objects:

DROPTABLE[IFEXISTS] some_table CASCADE;

To add a new column to an existing table, use the following command:

ALTERTABLE some_table ADDCOLUMN some_column DATATYPE;

To rename a specific column in an existing table, use the command shown below:

Postgresql Command Line Cheat Sheet Example

ALTERTABLE some_table RENAME some_column TO some_column;

To drop a column from a table, use the following command:

To remove the SQL primary key constraint from a table, we use the ALTER TABLE and DROP CONSTRAINT commands:

Postgresql Command Line Cheat Sheet Free

ALTERTABLE some_table
DROPCONSTRAINT primary_key_constraint_name;

Postgres Psql Command

NOTE: Some common examples of a PRIMARY KEY constraint would be NOT NULL or UNIQUE.

Conclusion to the PostgreSQL cheat sheet

If you’re just getting started with PostgreSQL, it may seem like there’s a lot to learn; however, having a PostgreSQL cheat sheet handy can make it easier to perform everyday database tasks. In this article, we covered many of the common commands and queries used in PostgreSQL. In the next installment of this two-part series, we’ll pick up where we left off and look at some more examples of PostgreSQL syntax.

Postgres Cli Commands

In first steps young DBA can greedily soak up all kinds of database knowledges: as RDBMS as NoSQL. We’re realising things like how table index works, how to optimize memory caching, write triggers and procedurs etc. But we still can forget a simple command to create user or show tables list. Also we can get stuck when switching from MySQL to PostgreSQL or whatever else, cause command syntax is different.

For this issue I lead a special cheatsheet table of DBMS commands. This table is splitted on few parts for each system I faced. I’ll try to update it as soon as I’ll start to explore other DBMS solutions.

MySQLPostgreSQLOracle Database
Shell command to ask MySQL command linemysql u admin -ppsql U admin passwordsqlplus admin/password
Create new user adminCREATE USER ‘admin’@‘localhost’ IDENTIFIED BY ‘password’;CREATE USER admin WITH PASSWORD ‘password’; CREATE USER admin IDENTIFIED BY

password

List all available databasesSHOW DATABASESlcat /etc/oratab #from shell
List all available tables in current databaseSHOW TABLESdtSELECT table_name FROM all_tables
List all users in RDBMSSELECT User FROM mysql.userduselect*from dba_users
Check database grants for any userSHOW GRANTSdpSELECT GRANTEE, OWNER, GRANTOR,

PRIVILEGE,GRANTABLE

FROM DBA_TAB_PRIVS;

Switch to another databaseUSE database2connect database2sqlplus

admin/password@localhost/database2

Read help about command syntaxHELP select’h SELECTHELP SELECT
Execute shell command! pwd! pwdHard-to-explain Oracle scheduler
Execute SQL script from filesource mydir/test.sqli mydir/test.sqlecho @mydir/test.sql | sqlplus username/password@connect

(only from command line, sorry)

Get database sizeSELECT data_length + index_length as“size” FROM information_schema.TABLES WHERE table_schema =“mydb”SELECT pg_database_size(mydb);Still hard to explain
Check data storage directorySHOW VARIABLES WHERE Variable_Name LIKE “%dir”;SHOW data_directory;SELECT value FROM v$parameter

WHERE name =‘db_create_file_dest’

List all indexesSELECT *

FROM information_schema.STATISTICS

WHERE TABLE_SCHEMA = DATABASE();

diSELECT user_tables.table_name, user_indexes.index_name

FROM user_tables JOIN user_indexes on user_indexes.table_name = user_tables.table_name

ORDER by user_tables.table_name,user_indexes.index_name;

Grant SELECT on all DB tablesGRANT SELECT ON mydb.* TO ‘user’@‘localhost’;GRANT SELECT ON ALL TABLES IN SCHEMA public TO user;So much hard to explain
Set config parameterSET parameter=value;ALTER SYSTEM SET parameter = value;ALTER SYSTEM SET parameter = value;
Make a logical backupmysql dump -h host -u user -pPassword dbpg_dump -h host -d db -U user -WNO WAY!
Return info about dead tuples at the table (PostgreSQL only)SELECT relname, n_dead_tup, last_vacuum, last_autovacuum FROM pg_catalog.pg_stat_all_tables WHERE n_dead_tup >0 AND relname NOT LIKE ‘pg%’;
Terminate all connections to databaseSELECT CONCAT(‘KILL ‘,id,’;’) FROM information_schema.processlist WHERE user=’root’ INTO OUTFILE ‘/tmp/a.txt’;

SOURCE /tmp/a.txt;

SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname=’ticktest’;startup forse;(as sys)