PostgreSQL, often referred to as Postgres, is a powerful, open-source, object-relational database management system (ORDBMS). Known for its robustness, extensibility, and compliance with SQL standards, it supports both relational and non-relational data structures.
Connect to a PostgreSQL server using the PostgreSQL command-line client (psql) and a username. It will prompt you for the password
To connect to a specific database on a PostgreSQL server with a username
To exit the client
For a full list of commands
For a list of psql commands
To export data using the pg_dump tool
To create a table
To increment the ID automatically with each new record, use the SERIAL data type
To create a table with a foreign key
To change a table name
To add a column to the table
To change a column name
To change a column data type
To delete a column
To delete a table
An example of a single-table query
An example of a multiple-table query
To concatenate two strings, use the || operator or the CONCAT() function
Note that with ||, the result is NULL if any of the strings is NULL
In contrast, CONCAT() ignores NULL
To get the count of characters in a string
To convert all letters to lowercase
To convert all letters to uppercase
To capitalize the first letter of each word in a string, use INITCAP()
To get a part of a string
To replace a part of a string
To get the number of seconds in a week
In PostgreSQL, the division operator / performs an integer division on integer arguments
Avoid integer division by including at least one non-integer argument
To get the remainder of a division
To round a number to its nearest integer
To round a number to three decimal places (NUMERIC arguments only)
To get the absolute value of a number
To get the square root of a number:
a date with a resolution of one day; stores the year, month, and day in the YYYY-MM-DD format.
a time of day with a resolution of one microsecond; stores the hours, minutes, seconds, and fractional seconds in the HH:MM:SS.SSSSSS format.
a timestamp with the time zone; stores the date and the time along with the corresponding time zone information. The range is from '4713-11-24 00:00:00' BC to '294276-12-31 23:59:59' AD.
a timestamp without the time zone; stores the date and the time. PostgreSQL handles TIMESTAMP values automatically with time zone conversion.
a duration of time, such as 3 days, 4 hours, and 30 minutes.
To create a date, time, or datetime value, write it as a string and cast it to the desired type.
You may skip casting in simple conditions. The database knows what you mean.
To add or subtract an INTERVAL from a date, time, or timestamp
To find the difference between two dates in days
DATE_TRUNC() in PostgreSQL truncates date or timestamp values to the specified time units.