DEV Community

Cover image for PostgreSQL
Hashem Al-wadeai
Hashem Al-wadeai

Posted on • Edited on

PostgreSQL

Introduction:

PostgreSQL is a powerful open-source object-relational database management system (ORDBMS) known for its robustness, reliability, and scalability. It was first developed at the University of California, Berkeley in the 1980s and has since grown to become one of the most popular database systems in the world.

What is PostgreSQL

PostgreSQL is an advanced relational database management system that is designed to handle complex workloads and data processing tasks. It is a high-performance, scalable, and extensible database system that supports a wide range of data types, including JSON, XML, and Geospatial data. PostgreSQL is also known for its advanced transactional capabilities, concurrency control, and data integrity features.

Features of PostgreSQL

PostgreSQL comes with a rich set of features that make it a popular choice for developers and enterprises alike. Some of its key features include:

ACID compliance: PostgreSQL ensures transactional consistency and reliability through its adherence to ACID principles.
Extensibility: PostgreSQL provides support for creating custom functions, data types, and operators.
Robustness: PostgreSQL is designed to handle high-volume and complex data workloads with ease.
Scalability: PostgreSQL is highly scalable and can support large amounts of data and high user concurrency.
Security: PostgreSQL has robust security features such as encryption, authentication, and access control.
Geospatial data support: PostgreSQL supports advanced geospatial data processing and analysis.

Advantages of PostgreSQL over other databases

There are several advantages of using PostgreSQL over other database systems, including:

Open-source: PostgreSQL is an open-source database system, which means it is free to use and can be customized according to specific needs.
Reliability: PostgreSQL is known for its reliability and stability, with a track record of high uptime and minimal downtime.
High performance: PostgreSQL is a high-performance database system that can handle complex queries and large data sets efficiently.
Extensibility: PostgreSQL provides a wide range of extensions and plugins that can be used to enhance its
functionality and add new features.
Scalability: PostgreSQL is highly scalable and can handle large volumes of data and user traffic without compromising on performance.
Community support: PostgreSQL has a large and active community of developers and users who contribute to its development and provide support and guidance to new users.

Installation and Setup

PostgreSQL Installation on Mac OS

  1. Go to the PostgreSQL download page (https://www.postgresql.org/download/macosx/) and select the version that matches your operating system.
  2. Download the PostgreSQL installer package for your version of Mac OS.
  3. Double-click on the downloaded file to start the installation process.
  4. Follow the installation wizard to complete the installation process. You may need to enter your system password to allow the installation to proceed.
  5. Once the installation is complete, PostgreSQL will be ready to use on your Mac OS.

PostgreSQL Installation on Windows

  1. Go to the PostgreSQL download page (https://www.postgresql.org/download/windows/) and select the version that matches your operating system.
  2. Download the PostgreSQL installer package for your version of Windows.
  3. Double-click on the downloaded file to start the installation process.
  4. Follow the installation wizard to complete the installation process. You may need to enter your system password to allow the installation to proceed.
  5. Once the installation is complete, PostgreSQL will be ready to use on your Windows system.

GUI Clients vs Terminal/CMD Clients

When working with PostgreSQL, you have the option of using either a graphical user interface (GUI) client or a terminal/CMD client. A GUI client provides a visual interface that allows you to interact with PostgreSQL using buttons, menus, and other graphical elements, while a terminal/CMD client uses command-line input to interact with PostgreSQL.
Both types of clients have their own advantages and disadvantages. A GUI client is generally easier to use for beginners and provides a more intuitive way of interacting with PostgreSQL. On the other hand, a terminal/CMD client is more flexible and powerful, allowing for more advanced operations and automation.

Setting up PSQL on Mac OS

PSQL is the command-line interface for interacting with PostgreSQL. Here's how to set it up on Mac OS:

  1. Open Terminal on your Mac.
  2. Type the command "psql" and hit Enter. If PostgreSQL is installed correctly, you should see the version number and a prompt that looks like this: postgres=#.
  3. To exit PSQL, type "\q" and hit Enter.

Setting up PSQL on Windows

To set up PSQL on windows, you will Open the Command Prompt and follow the same steps as Mac.

How to Create a Database

To create a new database in PostgreSQL, you can use the 'CREATE DATABASE' command followed by the name of the database you want to create:
CREATE DATABASE dbname;

For example, to create a database named test, you can use the following command:

CREATE DATABASE test;

This command will create a new database with default settings.
Note: In PostgreSQL, you need to be a superuser or have the CREATEDB privilege to create a new database.

How to Connect to a Database

Once you have created a database, you can connect to it using the 'psql' command-line tool. To connect to a database, use the following command:
psql -U username -d dbname -h host

Where:
'username' is the username you use to connect to the database
'dbname' is the name of the database you want to connect to
'host' is the host name or IP address of the machine where the database is running (optional)

For example, to connect to the 'test' database as the 'postgres' user on the local machine, you can use the following command:
psql -U postgres -d test

Creating Tables Without Constraints

To create a table without constraints in PostgreSQL, you can use the 'CREATE TABLE' command followed by the table name and the column names and data types.

For example, to create a table named 'products' with three columns 'id', 'name', and 'price', you can use the following command:
CREATE TABLE products (
id INTEGER,
name VARCHAR(50),
price NUMERIC(10,2)
);

Creating Tables with Constraints

To create a table with constraints in PostgreSQL, you can use the 'CREATE TABLE' command followed by the table name, the column names and data types, and the constraints.

For example, to create a table named users with two columns id and name, and a primary key constraint on the id column, you can use the following command:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(50) NOT NULL
);

Note: In PostgreSQL, you can use the 'SERIAL' data type to create an auto-incrementing column.

Inserting Data into Tables

To insert data into a table in PostgreSQL, you can use the 'INSERT INTO' command followed by the table name and the values you want to insert.

For example, to insert a row into the users table with the values '1' and ''Adam'', you can use the following command:
INSERT INTO users (id, name) VALUES (1, 'Adam');

Note: In PostgreSQL, you need to specify the column names in the INSERT INTO command when inserting data.

Retrieving Data with SELECT

To retrieve data from a table in PostgreSQL, you can use the 'SELECT' command followed by the column names you want to retrieve and the table name.

For example, to retrieve all the data from the users table, you can use the following command:
SELECT * FROM users;

Filtering Data with WHERE:

The 'WHERE' clause is used to filter data retrieved from a table based on certain conditions. It allows you to specify a condition and retrieve only the rows that meet that condition. The syntax for the WHERE clause is:
SELECT column1, column2, ...
FROM table_name
WHERE condition;

For example, to retrieve all the customers with a specific last name from a table called "customers", you could use the following query:

SELECT * FROM customers
WHERE last_name = 'Smith';

Sorting Data with ORDER BY:

The 'ORDER BY' clause is used to sort the result set in either ascending or descending order based on one or more columns. The syntax for the ORDER BY clause is:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;

For example, to sort the customers in the "customers" table by their last name in ascending order, you could use the following query:
SELECT * FROM customers
ORDER BY last_name ASC;

Limiting Data with LIMIT, OFFSET, and FETCH:

The LIMIT clause is used to limit the number of rows returned in a query result set. The OFFSET clause is used to skip a certain number of rows in the result set before returning the remaining rows. The FETCH clause combines the functionality of the LIMIT and OFFSET clauses in a single statement.

The syntax for the LIMIT and OFFSET clauses is:
SELECT column1, column2, ...
FROM table_name
LIMIT [number_of_rows_to_return]
OFFSET [number_of_rows_to_skip];

The syntax for the FETCH clause is:
SELECT column1, column2, ...
FROM table_name
OFFSET [number_of_rows_to_skip] ROWS
FETCH FIRST [number_of_rows_to_return] ROWS ONLY;

Examples for limiting data with LIMIT, OFFSET, and FETCH in PostgreSQL:

  1. Using LIMIT:
    SELECT * FROM customers LIMIT 10;

    This query retrieves the first 10 rows from the 'customers' table.

  2. Using OFFSET:
    SELECT * FROM customers OFFSET 10;

    This query retrieves all rows from the 'customers' table starting from the 11th row (since we are skipping the first 10 rows using OFFSET).

  3. Using LIMIT and OFFSET:
    SELECT * FROM customers LIMIT 10 OFFSET 20;

    This query retrieves 10 rows from the 'customers' table starting from the 21st row (since we are skipping the first 20 rows using OFFSET).

  4. Using FETCH:
    `SELECT first_name, last_name
    FROM customer
    ORDER BY last_name
    OFFSET 2 ROWS
    FETCH FIRST 5 ROWS ONLY;

`
This query will skip the first two rows of the result set (the first two customers in alphabetical order by last name) and then retrieve the next 5 rows.

Aggregating Data with GROUP BY and HAVING:

The 'GROUP BY' clause is used to group rows that have the same values in one or more columns. The 'HAVING' clause is used to filter groups based on a specified condition. These clauses are often used with aggregate functions such as SUM, AVG, MAX, and MIN to perform calculations on groups of data.

The syntax for the GROUP BY clause is:
SELECT column1, column2, ...
FROM table_name
GROUP BY column1, column2, ...;

The syntax for the HAVING clause is:
SELECT column1, column2, ...
FROM table_name
GROUP BY column1, column2, ...
HAVING condition;

For example, to calculate the total sales for each salesperson in the "sales" table and only return those with total sales greater than $10,000, you could use the following query:
SELECT salesperson, SUM(sales_amount) AS total_sales
FROM sales
GROUP BY salesperson
HAVING SUM(sales_amount) > 10000;

Top comments (0)