PostgreSQL Basics: Understanding Databases, Tables, and SQL Commands
After installing PostgreSQL, the next step is to understand the basic concepts required to work with it confidently.
In this article, you will learn:
- What a database is
- What tables, rows, and columns are
- Basic PostgreSQL SQL commands
- How data is stored and accessed
This post is written for absolute beginners.
What Is a Database?
A database is an organized collection of data stored electronically.
Examples of data stored in databases:
- User information
- Orders
- Products
- Payments
- Logs
PostgreSQL stores data in databases, and each database contains tables.
What Is a Table?
A table is where the actual data is stored.
A table:
- Has a name
- Contains rows and columns
- Stores records
Example:
A users table may store information about users.
Rows and Columns Explained
Columns
- Define the type of data
- Have names and data types
Example columns:
idnameemailcreated_at
Rows
- Each row is a record
- Represents one entry
Example:
- One row = one user
What Is SQL?
SQL (Structured Query Language) is used to interact with PostgreSQL.
Using SQL, you can:
- Create tables
- Insert data
- Retrieve data
- Update data
- Delete data
PostgreSQL uses standard SQL with additional advanced features.
Connecting to PostgreSQL
To connect to PostgreSQL using the command line:
psql -U postgres
Creating a Database
Create a new database:
CREATE DATABASE mydb;
Creating a Table
Example table creation:
Explanation:
SERIALautomatically generates numbersPRIMARY KEYuniquely identifies each rowTEXTstores text dataTIMESTAMPstores date and time
Inserting Data into a Table
Retrieving Data (SELECT)
View all records:
SELECT * FROM users;
SELECT name, email FROM users;
Updating Data
Update existing data:
The WHERE clause is important to avoid updating all rows.
Deleting Data
Delete a row:
Always use WHERE with DELETE.
Common PostgreSQL Concepts
Primary Key
- Uniquely identifies each row
- Cannot be duplicated or NULL
Data Types
Common PostgreSQL data types:
INTEGERTEXTBOOLEANDATETIMESTAMP
Constraints
NOT NULLUNIQUEPRIMARY KEYFOREIGN KEY
Viewing Tables in a Database
View table structure:
\d users
Summary
- Databases store structured data
- Tables contain rows and columns
- SQL is used to interact with PostgreSQL
- Basic commands include CREATE, INSERT, SELECT, UPDATE, DELETE
You now understand the foundation of PostgreSQL.
What’s Next?
Next, we will explore PostgreSQL Data Types in detail.
Next article:
PostgreSQL Data Types Explained with Examples
No comments:
Post a Comment