DEV Community

Cover image for PostgreSQL Tutorial & Real World Guide
Md Nazmus Sakib
Md Nazmus Sakib

Posted on

PostgreSQL Tutorial & Real World Guide

Made by: Md. Nazmus Sakib

Profession: Full Stack Developer


Table of Contents


PostgreSQL Home

PostgreSQL is a powerful, open-source relational database system that’s trusted for robustness, scalability, and extensibility.

Used by companies like Apple, Instagram, and Reddit for storing millions of records and complex business logic.


PostgreSQL Intro

  • Relational Database: Stores data in tables with rows and columns.
  • Open Source: Free, community-driven, and highly extensible.
  • Real Life Example: Instagram uses PostgreSQL for user data, photos, likes, comments, and relationships.

PostgreSQL Install

Ubuntu:

sudo apt update sudo apt install postgresql postgresql-contrib 
Enter fullscreen mode Exit fullscreen mode

macOS (Homebrew):

brew install postgresql 
Enter fullscreen mode Exit fullscreen mode

Windows:

Download installer from PostgreSQL Official Site


PostgreSQL Get Started

Start the PostgreSQL service:

sudo service postgresql start 
Enter fullscreen mode Exit fullscreen mode

Access the CLI:

sudo -u postgres psql 
Enter fullscreen mode Exit fullscreen mode

Create a database:

CREATE DATABASE shop; 
Enter fullscreen mode Exit fullscreen mode

Create a user:

CREATE USER shopuser WITH PASSWORD 'strongpassword'; GRANT ALL PRIVILEGES ON DATABASE shop TO shopuser; 
Enter fullscreen mode Exit fullscreen mode

PostgreSQL pgAdmin 4

pgAdmin 4 is the official graphical user interface for PostgreSQL.

It allows you to manage databases, run queries, view statistics, and more — all via a web browser.


DBeaver: Universal DB Client

DBeaver is a powerful database management tool supporting PostgreSQL and many other databases.
DBeaver Screenshot

  • Use it for visual table design, ER diagrams, queries, and data analysis.
  • Real Life: Data analysts use DBeaver to explore customer purchase histories and sales trends from PostgreSQL.

Database Operations

PostgreSQL CREATE TABLE

CREATE TABLE customers ( id SERIAL PRIMARY KEY, name VARCHAR(100), email VARCHAR(100), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); 
Enter fullscreen mode Exit fullscreen mode

Real Life: E-commerce platforms store customer info.


PostgreSQL INSERT INTO

INSERT INTO customers (name, email) VALUES ('Sakib', 'sakib@gmail.com'); 
Enter fullscreen mode Exit fullscreen mode

Real Life: Registering new users on a website.


PostgreSQL Fetch Data

SELECT * FROM customers; 
Enter fullscreen mode Exit fullscreen mode

Real Life: Admin dashboard shows all customers.


PostgreSQL ADD COLUMN

ALTER TABLE customers ADD COLUMN phone VARCHAR(20); 
Enter fullscreen mode Exit fullscreen mode

Real Life: Adding mobile number support.


PostgreSQL UPDATE

UPDATE customers SET email = 'sakib@outlook.com' WHERE id = 1; 
Enter fullscreen mode Exit fullscreen mode

Real Life: User updates their email address.


PostgreSQL ALTER COLUMN

ALTER TABLE customers ALTER COLUMN phone TYPE VARCHAR(30); 
Enter fullscreen mode Exit fullscreen mode

Real Life: Allow longer phone numbers.


PostgreSQL DROP COLUMN

ALTER TABLE customers DROP COLUMN phone; 
Enter fullscreen mode Exit fullscreen mode

Real Life: Remove unnecessary data fields.


PostgreSQL DELETE

DELETE FROM customers WHERE id = 1; 
Enter fullscreen mode Exit fullscreen mode

Real Life: GDPR request to delete user data.


PostgreSQL DROP TABLE

DROP TABLE customers; 
Enter fullscreen mode Exit fullscreen mode

Real Life: Remove legacy tables after migration.


Create Demo Database

CREATE DATABASE demo; -- Connect to demo \c demo -- Create table CREATE TABLE products ( id SERIAL PRIMARY KEY, title VARCHAR(100), price NUMERIC ); INSERT INTO products (title, price) VALUES ('Laptop', 1200), ('Mouse', 25); 
Enter fullscreen mode Exit fullscreen mode

Real Life: Inventory management for an electronics shop.


PostgreSQL Syntax & Operators

Syntax

SELECT column1, column2 FROM table_name WHERE condition; 
Enter fullscreen mode Exit fullscreen mode

Operators

  • = (equal), <> (not equal), <, >, <=, >=
  • AND, OR, NOT
  • IN, BETWEEN, LIKE
SELECT * FROM products WHERE price > 100 AND title LIKE '%top%'; 
Enter fullscreen mode Exit fullscreen mode

PostgreSQL SELECT & Clauses

PostgreSQL SELECT

SELECT * FROM products; 
Enter fullscreen mode Exit fullscreen mode

SELECT DISTINCT

SELECT DISTINCT title FROM products; 
Enter fullscreen mode Exit fullscreen mode

WHERE

SELECT * FROM products WHERE price > 500; 
Enter fullscreen mode Exit fullscreen mode

ORDER BY

SELECT * FROM products ORDER BY price DESC; 
Enter fullscreen mode Exit fullscreen mode

LIMIT

SELECT * FROM products LIMIT 5; 
Enter fullscreen mode Exit fullscreen mode

MIN and MAX

SELECT MIN(price), MAX(price) FROM products; 
Enter fullscreen mode Exit fullscreen mode

COUNT

SELECT COUNT(*) FROM products WHERE price > 500; 
Enter fullscreen mode Exit fullscreen mode

SUM

SELECT SUM(price) FROM products; 
Enter fullscreen mode Exit fullscreen mode

AVG

SELECT AVG(price) FROM products; 
Enter fullscreen mode Exit fullscreen mode

LIKE

SELECT * FROM products WHERE title LIKE 'Lap%'; 
Enter fullscreen mode Exit fullscreen mode

IN

SELECT * FROM products WHERE price IN (25, 1200); 
Enter fullscreen mode Exit fullscreen mode

BETWEEN

SELECT * FROM products WHERE price BETWEEN 100 AND 1300; 
Enter fullscreen mode Exit fullscreen mode

AS (Alias)

SELECT title AS "Product Name", price AS "Cost" FROM products; 
Enter fullscreen mode Exit fullscreen mode

PostgreSQL Joins

Suppose you have tables orders and customers.

INNER JOIN

SELECT orders.id, customers.name FROM orders INNER JOIN customers ON orders.customer_id = customers.id; 
Enter fullscreen mode Exit fullscreen mode

LEFT JOIN

SELECT orders.id, customers.name FROM orders LEFT JOIN customers ON orders.customer_id = customers.id; 
Enter fullscreen mode Exit fullscreen mode

RIGHT JOIN

SELECT orders.id, customers.name FROM orders RIGHT JOIN customers ON orders.customer_id = customers.id; 
Enter fullscreen mode Exit fullscreen mode

FULL JOIN

SELECT orders.id, customers.name FROM orders FULL JOIN customers ON orders.customer_id = customers.id; 
Enter fullscreen mode Exit fullscreen mode

CROSS JOIN

SELECT customers.name, products.title FROM customers CROSS JOIN products; 
Enter fullscreen mode Exit fullscreen mode

UNION

SELECT name FROM customers UNION SELECT title FROM products; 
Enter fullscreen mode Exit fullscreen mode

GROUP BY

SELECT customer_id, COUNT(*) AS order_count FROM orders GROUP BY customer_id; 
Enter fullscreen mode Exit fullscreen mode

HAVING

SELECT customer_id, COUNT(*) AS order_count FROM orders GROUP BY customer_id HAVING COUNT(*) > 5; 
Enter fullscreen mode Exit fullscreen mode

EXISTS

SELECT name FROM customers WHERE EXISTS ( SELECT 1 FROM orders WHERE orders.customer_id = customers.id ); 
Enter fullscreen mode Exit fullscreen mode

ANY

SELECT * FROM products WHERE price = ANY (SELECT price FROM products WHERE price < 100); 
Enter fullscreen mode Exit fullscreen mode

ALL

SELECT * FROM products WHERE price > ALL (SELECT price FROM products WHERE price < 1000); 
Enter fullscreen mode Exit fullscreen mode

CASE

SELECT title, price, CASE WHEN price > 1000 THEN 'Expensive' ELSE 'Affordable' END AS category FROM products; 
Enter fullscreen mode Exit fullscreen mode

Prisma Integration with PostgreSQL

Prisma is a next-generation Node.js/TypeScript ORM for PostgreSQL (and more).

It makes database access safe, fast, and easy.

How Prisma Works

  • Define your DB schema in schema.prisma
  • Generate type-safe client code
  • Write database queries in JavaScript/TypeScript

Install & Set Up

npm install @prisma/client npx prisma init 
Enter fullscreen mode Exit fullscreen mode

Add your PostgreSQL URL in .env:

DATABASE_URL="postgresql://shopuser:strongpassword@localhost:5432/shop" 
Enter fullscreen mode Exit fullscreen mode

Example Prisma Schema

model Customer { id Int @id @default(autoincrement()) name String email String @unique orders Order[] } model Order { id Int @id @default(autoincrement()) product String customerId Int customer Customer @relation(fields: [customerId], references: [id]) } 
Enter fullscreen mode Exit fullscreen mode

Migration

npx prisma migrate dev --name init 
Enter fullscreen mode Exit fullscreen mode

Query Examples

import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() // Create a customer await prisma.customer.create({ data: { name: 'Sakib', email: 'sakib@gmail.com' } }) // Find all customers const customers = await prisma.customer.findMany() // Create an order for a customer await prisma.order.create({ data: { product: 'Laptop', customerId: 1 } }) 
Enter fullscreen mode Exit fullscreen mode

Real World Use Cases

  • E-commerce: Customers, Orders, Products — with relations and constraints.
  • Blog/CMS: Users, Posts, Comments — with easy querying and filtering.
  • Analytics: Store logs/events as JSONB, aggregate with SQL and Prisma.
  • Healthcare: Patients, Doctors, Appointments, secure medical records.
  • Education: Students, Courses, Enrollments, track progress.

Resources


PostgreSQL and Prisma together empower you to build scalable, high-performance, and secure applications for any real world need!

Top comments (0)