PostgreSQL is an advanced, open-source, object-relational database management system. It is renowned for its scalability, reliability, and compliance with the SQL standard. PostgreSQL supports both SQL (relational) and JSON (non-relational) querying, making it highly versatile.
**psql** is a terminal-based front end to PostgreSQL. It allows users to interact with PostgreSQL databases by executing SQL queries, managing database objects, and performing administrative tasks.
To start psql, open your terminal or command prompt and type:
```bash
psql
```
### Connecting to a Database
You can specify the database name, user, host, and port when launching psql:
```bash
psql -d database_name -U username -h hostname -p port
```
Alternatively, you can use environment variables:
```bash
export PGDATABASE=mydb
export PGUSER=myuser
export PGPASSWORD=mypassword
export PGHOST=localhost
export PGPORT=5432
psql
```
### Listing Databases and Tables
- **List Databases:**
```sql
\l
```
- **List Tables in the Current Database:**
```sql
\dt
```
- **List All Schemas:**
```sql
\dn
```
### Creating and Dropping Databases/Tables
- **Create a Database:**
```sql
CREATE DATABASE mydb;
```
- **Drop a Database:**
```sql
DROP DATABASE mydb;
```
- **Create a Table:**
```sql
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL
);
```
- **Drop a Table:**
```sql
DROP TABLE users;
```
### Running SQL Queries
Execute standard SQL commands to interact with your data.
**Example: Inserting Data**
```sql
INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com');
```
**Example: Querying Data**
```sql
SELECT * FROM users;
```
**Example: Updating Data**
```sql
UPDATE users SET email = 'john.doe@example.com' WHERE username = 'john_doe';
```
**Example: Deleting Data**
```sql
DELETE FROM users WHERE username = 'john_doe';
```
## Meta-Commands
psql provides a set of meta-commands (prefixed with `\`) that facilitate various tasks.
### Common Meta-Commands
- **Help on Meta-Commands:**
```sql
\?
```
- **Help on SQL Commands:**
```sql
\h
```
- **Describe a Table:**
```sql
\d table_name
```
- **List All Tables, Views, and Sequences:**
```sql
\dt
```
- **List All Indexes:**
```sql
\di
```
- **Exit psql:**
```sql
\q
```
## Data Types
### 1. **Numeric Types**
- **Small Integer Types**
-`SMALLINT` (2 bytes): Range from -32,768 to +32,767
- **Integer Types**
-`INTEGER` or `INT` (4 bytes): Range from -2,147,483,648 to +2,147,483,647
- **Big Integer Types**
-`BIGINT` (8 bytes): Range from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
- **Decimal/Exact Types**
-`DECIMAL` or `NUMERIC` (variable size): User-defined precision and scale
- **Floating-Point Types**
-`REAL` (4 bytes): Single precision floating-point number
-`DOUBLE PRECISION` (8 bytes): Double precision floating-point number