PostgreSQL - Cheat Sheet : Basic to Advanced
Last Updated :
21 Oct, 2024
PostgreSQL is a powerful, open-source object-relational database management system (ORDBMS). It is designed to help developers build robust applications and allow administrators to maintain data integrity while creating fault-tolerant environments. Like other enterprise databases such as Microsoft SQL Server and Oracle, PostgreSQL supports advanced features like data types, indexing techniques, and performance optimizations.
In this PostgreSQL Cheat Sheet, we've compiled the most essential commands, tips, and tricks for navigating PostgreSQL efficiently. From basic queries to advanced configurations, this article will be our go-to resource for effectively managing databases. Let's dive in and simplify our PostgreSQL experience.
What is PostgreSQL
PostgreSQL is an advanced, open-source relational database management system (RDBMS). It uses SQL (Structured Query Language) to interact with and manage data. It supports a wide variety of data types, complexqueries, transactions, foreign keys, and triggers, making it an ideal choice for large-scale applications.
Key Features of PostgreSQL:
- Open Source DBMS: Free and highly customizable.
- Supports ACID properties: Atomicity, Consistency, Isolation, and Durability for reliable transactions.
- Advanced indexing techniques: B-tree, Hash, GIN, GiST, SP-GiST.
- Replication: Both log-based and trigger-based replication.
- JSON support: Native support for JSON and JSONB data types.
- Geospatial Data: Support for geographic objects using PostGIS.
- Object-Oriented: Support for custom types and inheritance.
PostgreSQL Data Types
PostgreSQL supports a wide range of data types. Here's a table of the most commonly used types:
Category | Data Types |
---|
Numeric | smallint, integer, bigint, decimal, numeric, serial |
Character | varchar(n), text, char(n) |
Date/Time | timestamp, date, time, interval |
Monetary | money |
Binary | bytea |
Boolean | boolean |
Geometric | point, line, box, path, polygon, circle, lseg |
JSON | json, jsonb |
UUID | uuid |
Network Address | cidr, inet, macaddr |
BitString | bit(n), bit varying(n) |
Range | int4range, int8range, numrange, tsrange (timestamp range) |
Operators in PostgreSQL:
An operator manipulates individual data items and returns a result. These are the reserved words used in WHERE clause to perform operations.
Operators |
---|
Arithmetic Operators | +, -, *, /, %, ^, ! |
Comparison Operators | =, !=, <>, >, <, >=, <= |
Logical Operators | AND, NOT, OR |
Bitwise Operators | &, | |
PostgreSQL Installation
- To install PostgreSQL, run the following command:
sudo apt install postgresql
- To add some additional utilities and functionalities.
sudo apt install postgresql postgresql-contrib
- Once installed, switch to the Postgres user and access the PostgreSQL prompt:
sudo -i -u postgres
- Now, we can access the Postgres prompt using psqlcommand.
Working With Databases in PostgreSQL
Creating a Database
TheCREATE DATABASE command is used to create the database.
syntax:
CREATE DATABASE database_name;
Example:
create databaseExplanation:
This command creates a database named my_database
where we can store our data. Once the database is created, we can switch to it using the\c
command in psql to start working with tables and other objects.
Creating a Table
Now, to store the data, we need the table. The CREATE TABLEstatement is used to create the table.
Syntax:
CREATE TABLE table_name
(column_1 data_type,
column_2 data_type,
...
column_n data_type);
Example:
create tableExplanation:
This command creates an Student
table with three columns: roll, student_name and course . The roll
column is a serial primary key, meaning it will auto-increment with each new row added.TheINSERTcommand is used to insert the new record (row) into the table.
Inserting Data into a Table
To insert a new record (row) into a table, use the INSERT INTO
command.
Syntax:
INSERT INTO table_name (column_1, column_2 ,...)
VALUES(value_1, value_2, ...);
Example:
insert into tableExplanation:
This query inserts a new row into the Student table with the student name ANDREW, roll number 1, and course MCA.
Selecting Data from a Table
The SELECTstatement is used to fetch the data from a database table, which returns the data in the form of a result table.
Syntax:
SELECT
column_1, column_2, .. column_n
FROM
table_name;
Example:
Select commandExplanation:
This query retrieves the roll number and student name
columns from the Student
table. If we want to select all columns, we can use an asterisk *
.
Filtering Data with the WHERE Clause
TheWHEREclause is used to filter results returned by the SELECT statement.
Syntax:
SELECT column_name
FROM
table_name
WHERE condition;
Example:
Where clauseExplanation:
This query selects all the records from the student table where course name is MCA.
Using the LIMIT Clause
TheLIMITclause is used to get a subset of rows generated by a query. This clause is optional and helps control the number of rows retrieved. OFFSETnskips 'n' rows before beginning to return rows.
Syntax:
SELECT *
FROM table_name
LIMIT n;
Example:
Limit & OffsetExplanation:
LIMIT n
: Specifies the maximum number of rows to return.
OFFSET m
: Skips the first m
rows and starts returning rows from the next one.
This query returns 3 rows from the Student
table, but skips the first 1 row.
Modifying Table Structure with ALTER TABLE
The structure of an existing table can be modified using the ALTER TABLE statement. PostgreSQL supports the various actions to perform with ALTER TABLE as listed below:
- Add a column to an existing table
ALTER TABLE table_name ADD COLUMN new_column_name TYPE;
- Drop a column from an existing table
ALTER TABLE table_name DROP COLUMN column_name;
- Rename a column from an existing table
ALTER TABLE table_name RENAME COLUMN column_name TO new_column_name;
- Rename a column from an existing table
ALTER TABLE table_name ALTER COLUMN column_name [SET DEFAULT value | DROP DEFAULT];
- Change NOT NULL constraint
ALTER TABLE table_name ALTER COLUMN column_name [SET NOT NULL| DROP NOT NULL];
- Add CHECK constraints to a column
ALTER TABLE table_name ADD CHECK expression;
ALTER TABLE table_name ADD CONSTRAINT constraint_name constraint_definition;
ALTER TABLE table_name RENAME TO new_table_name;
Updating Data in PostgreSQL
The UPDATE
statement is used to modify existing data in a table. We can update one or multiple columns by specifying the column values and a condition for the rows we want to update.
Syntax:
UPDATE table_name
SET column_1 = value_1,
column_2 = value_2, ...
WHERE
condition_1 AND condition_2;
Example:
UpdateExplanation:
This query updates the course of the Student to MCA where roll number is 4.
Deleting Data in PostgreSQL
The DELETE
statement is used to remove rows from a table. We can delete all rows or specific rows based on a condition.
Syntax:
DELETE FROM table_name
WHERE condition;
Example:
DeleteExplanation:
This query deletes all student whose roll number is 3.
Conclusion
PostgreSQL is a highly flexible and powerful database system that offers robust features for managing databases effectively. By using this PostgreSQL Cheat Sheet, we will be able to navigate through basic to advanced PostgreSQL tasks with ease. From creating databases to optimizing queries, this guide ensures you have the right tools and commands at our fingertips.
Similar Reads
MongoDB Cheat Sheet (Basic to Advanced)
MongoDB is a powerful NoSQL database known for its flexible, document-oriented storage that is ideal for handling large-scale, complex data. MongoDB Atlas (a cloud-based solution), MongoDB Compass (a GUI for data visualization) and the MongoDB Shell for command-line operations, users can efficiently
11 min read
SQL Cheat Sheet ( Basic to Advanced)
Creating and managing databases in SQL involves various commands and concepts that handle the structuring, querying, and manipulation of data. In this guide, we will see a comprehensive cheat sheet for essential SQL operations, offering a practical reference for tasks ranging from database creation
15 min read
How to Migrate a PostgreSQL Database to MySQL
Moving a database from one platform to another can be tough, but with careful planning and execution, it can be done smoothly. In this article, we'll go over how to migrate a PostgreSQL database to MySQL, which are both popular RDBMS. We'll cover preparation, schema conversion, data migration, and t
5 min read
PostgreSQL - CREATE TABLE AS
The CREATE TABLE AS statement in PostgreSQL is a powerful tool used to create a new table and populate it with data returned by a query. This functionality allows you to generate tables on the fly based on query results, which can be very useful for reporting, analysis, and other tasks.Let us better
3 min read
How to List all Schemas in PostgreSQL?
In PostgreSQL, schemas are used to organize database objects such as tables, views, functions, and indexes into logical groups. Understanding how to list schemas within a PostgreSQL database is essential for effective database management, especially as databases grow in size and complexity.In this a
3 min read
PostgreSQL - CREATE SCHEMA
PostgreSQL provides the CREATE SCHEMA statement to create a new schema in a database. By creating schemas, users can effectively separate data into logical groups, making it easier to manage and access information. Schemas also enhance security by controlling object visibility and permissions, allow
5 min read
SQL for Data Analysis Cheat Sheet
SQL (Structured Query Language) is essential for data analysis as it enables efficient data retrieval, manipulation, and transformation. It allows analysts to filter, sort, group, and aggregate large datasets, making data-driven decision-making easier. SQL integrates seamlessly with business intelli
4 min read
Create a CRUD API With PostgREST
In today's fast-paced world, businesses rely heavily on efficient data management systems to streamline operations and deliver optimal services. One such tool that has gained popularity for its simplicity and effectiveness is PostgREST. In this article, we'll explore how you can harness the power of
5 min read
PostgreSQL - TEXT Data Type
PostgreSQL provides a highly flexible character data type known as TEXT, designed to store character strings of virtually unlimited length. Unlike the VARCHAR data type, which can be limited to a specified length, the TEXT data type offers the same efficiency and performance without the length const
3 min read
Rust and PostgreSQL
In today's world of software development, choosing the right programming language and database can significantly impact the performance and reliability of your applications. Rust is a modern programming language that prioritizes safety and performance, while PostgreSQL is a powerful and flexible rel
8 min read