In this chapter, we will learn how to design and structure the data in PostgreSQL using tables. Understanding how to model the data properly is crucial for building efficient, maintainable, and scalable databases.
Understanding Tables, Rows, and Columns
Tables
- A table is like a spreadsheet: it holds data in rows and columns.
- Each table represents one entity, such as
users
,products
, ororders
.
Columns
- Define attributes or fields for the table.
- Each column has a data type (e.g.,
text
,integer
,data
).
Rows
- Each row is a record in the table, storing a set of values under the defined columns.
Data Types in PostgreSQL
PostgreSQL has a rich set of built-in data types:
Category | Common Types | Example |
---|---|---|
Text | VARCHAR(n) , TEXT , CHAR(n) | 'John Doe' |
Numbers | INTEGER , BIGINT , DECIMAL , NUMERIC , SERIAL | 42 , 3.14 |
Date/Time | DATE , TIME , TIMESTAMP , INTERVAL | '2023-12-31' |
Boolean | BOOLEAN | TRUE , FALSE |
UUID | UUID | 'a1b2c3...' |
JSON | JSON , JSONB | {"key": "value"} |
Array | Any type with [] | {1, 2, 3} |
Tip: Use
SERIAL
orBIGSERIAL
for auto-incrementing primary keys.
Creating and Modifying Tables
Basic CREATE TABLE
example
CREATE TABLE employees {
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email TEXT UNIQUE,
position TEXT DEFAULT 'Staff',
hire_date DATE
};
SERIAL
: Auto-incrementing integerPRIMARY KEY
: Uniquely identifies each rowNOT NULL
: Field must have a valueUNIQUE
: Not two rows can have the same valueDEFAULT
: Automatically assigns a value if none provided
Modifying Tables
-- Add a new column
ALTER TABLE employees ADD COLUMN salary NUMERIC(10, 2);
-- RENAME a column
ALTER TABLE employees RENAME COLUMN position TO job_title;
-- DELETE a column
ALTER TABLE employees DROP COLUMN salary;
Be cautious when altering tables in production databases.
Keys and Relationships
Primary Keys
- A primary key ensures each row is uniquely identifiable.
- Usually applied to column like `id
Leave a comment
Your email address will not be published. Required fields are marked *