| |

SQL 5 🛢️ Installing SQL Environment and Client Tools

The previous chapters covered what a relational database is, how the RDBMS implements the model, and how tables and keys are structured. This chapter covers the practical step that comes before you write your first SELECT: installing a database server and the client tools that connect to it.

There are three open-source RDBMSs that dominate the learning landscape: PostgreSQL, MySQL, and SQLite. Each has a different installation path, a different default client, and a different set of graphical tools. The choice depends on what you are building. PostgreSQL is the most feature-rich and standards-compliant. MySQL is the most widely deployed in web applications. SQLite is the simplest — a single file with no server process at all.

Key point: A database system has two halves. The server stores the data and processes queries. The client connects to the server and sends SQL. On Linux, the server installs as a system service and the client installs as a command-line tool. Graphical clients are optional — they connect to the same server through the same protocols.


Why the environment matters

You cannot learn SQL by reading about it. You need a database to run queries against. The setup step is not glamorous, but it determines whether your first experience with SQL is smooth or frustrating.

The server problem. A relational database is a server process. It listens for connections, manages memory, writes to disk, and enforces constraints. On a development machine, the server runs as a background service. On a production server, it runs on dedicated hardware. The installation step installs the server and configures it to start automatically.

The client problem. The server does not present a user interface. You connect to it with a client. The command-line client (psql for PostgreSQL, mysql for MySQL, sqlite3 for SQLite) is the primary tool. Graphical clients like pgAdmin, MySQL Workbench, and DBeaver provide a visual interface for the same operations.

The connection problem. The server and client communicate over a protocol. PostgreSQL uses its own protocol over TCP port 5432. MySQL uses its protocol over TCP port 3306. SQLite has no network protocol because it is not a server — the client and the data are in the same process.

The trade-off. Installing a server-based database is more complex than opening a file. It requires configuring authentication, managing users, and starting a service. The complexity is the cost of concurrency, durability, and the ACID properties. For a single-user learning environment, SQLite avoids all of it. For anything that multiple users will access, a server-based database is required.


a. Installing PostgreSQL on Ubuntu

PostgreSQL is available in Ubuntu’s default repositories, but the PostgreSQL Global Development Group maintains its own APT repository with the latest versions and extensions . The recommended installation uses the PGDG repository.

The quickstart is three commands:

sudo apt install -y postgresql-common ca-certificates
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh
sudo apt install postgresql

The postgresql-common package provides the utilities for managing PostgreSQL on Debian-based systems. The apt.postgresql.org.sh script adds the PGDG repository to the system’s sources. The postgresql package installs the server .

After installation, the service starts automatically. You can verify it with:

sudo systemctl status postgresql

The output shows active (exited) with an ExecStart=/bin/true line. This is normal for PostgreSQL on Debian and Ubuntu — the main service is a placeholder, and the actual server processes are managed by pg_ctlcluster .

PostgreSQL uses peer authentication by default. This means the postgres operating system user can connect as the postgres database user without a password. To connect:

sudo -u postgres psql

This opens the psql command-line client connected to the default postgres database .

The psql client is the primary interface for PostgreSQL. It supports SQL statements, meta-commands that begin with a backslash, and scripting. The \l command lists databases. The \dt command lists tables. The \d table_name command describes a table. The \q command quits .

To create a database and a user:

CREATE DATABASE mydb;
CREATE USER myuser WITH ENCRYPTED PASSWORD 'strong_password';
GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;

To enable password authentication for remote connections, the pg_hba.conf file must be modified. The default peer authentication method must be changed to scram-sha-256 for the local connection if you want password-based access .


b. Installing MySQL on Ubuntu

MySQL is available in Ubuntu’s default repositories, but Oracle maintains its own APT repository for the latest versions . The installation can use either path.

The simplest installation uses the default repository:

sudo apt update
sudo apt install mysql-server

For the latest version, the MySQL APT repository must be added first. The process involves downloading the repository configuration package from the MySQL Developer Zone, installing it with dpkg, and then running apt update .

After installation, the MySQL service starts automatically. The mysql_secure_installation script is typically run to set a root password, remove anonymous users, and disable remote root login.

The command-line client is mysql:

sudo mysql

This connects to the MySQL server as the root user using the Unix socket. The -u flag specifies a different user, and -p prompts for a password.

MySQL configuration files are under /etc/mysql. The data directory is /var/lib/mysql. The binaries are under /usr/bin and /usr/sbin .

The mysql client supports standard SQL statements. Meta-commands begin with a backslash. The \l equivalent is SHOW DATABASES;. The \dt equivalent is SHOW TABLES;. The DESCRIBE table_name; statement describes a table.


c. Installing SQLite on Ubuntu

SQLite is not a server. It is a library that stores an entire database in a single file. The sqlite3 command-line tool is the client .

The installation is a single command:

sudo apt update
sudo apt install sqlite3

The sqlite3 binary is installed at /usr/bin/sqlite3. To verify:

sqlite3 --version

To start an interactive session with a new database file:

sqlite3 mydb.db

SQLite creates the file if it does not exist. The .databases command lists open databases. The .tables command lists tables. The .schema command shows the schema. The .quit command exits .

SQLite supports most of the SQL standard. The differences are in features that require a server: user management, network protocols, and concurrent writes. SQLite is the right choice for embedded applications, mobile apps, and single-user local development.


d. Graphical Client Tools

Command-line clients are sufficient for learning SQL, but graphical clients provide a visual interface for browsing schemas, editing data, and writing queries. The choice depends on the database and the platform.

pgAdmin 4 is the official PostgreSQL administration GUI. It is open source, free, and maintained by the PostgreSQL community. It provides an object browser, a query tool, explain plan visualization, and backup/restore workflows. It can run as a desktop app or as a web application .

MySQL Workbench is the official MySQL GUI. It provides database modeling with ER diagrams, a SQL editor with syntax highlighting, and migration tools. It is available for Windows, macOS, and Linux .

DBeaver is a universal database client that supports PostgreSQL, MySQL, SQLite, and dozens of other databases. It is open source with a proprietary enterprise edition. It provides a consistent interface across databases, a powerful SQL editor, and data export tools .

HeidiSQL is a lightweight Windows-only client for MySQL, MariaDB, and PostgreSQL. It is free and open source. It provides a simple interface for browsing data, editing tables, and running queries .

TablePlus is a modern, visually polished client for macOS and Windows. It supports multiple databases and provides a native-feeling interface. The free tier has connection limits; advanced features require a license .

For learning SQL, the command-line client is the best starting point. It forces you to write the SQL and understand the results. Graphical clients are useful once you are comfortable with the syntax and want to browse schemas or export data more efficiently.


Complete Example Session

This session installs PostgreSQL, creates a database and table, inserts data, and queries it from the psql client.

# ============================================
# PART 1: INSTALL POSTGRESQL
# ============================================

sudo apt update
sudo apt install -y postgresql-common ca-certificates
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh
sudo apt install postgresql

# Verify the service is running
sudo systemctl status postgresql

# ============================================
# PART 2: CONNECT WITH psql
# ============================================

sudo -u postgres psql

# Output:
# psql (17.4)
# Type "help" for help.
# postgres=#

# ============================================
# PART 3: CREATE A DATABASE AND USER
# ============================================

CREATE DATABASE bookstore;
CREATE USER librarian WITH ENCRYPTED PASSWORD 'shelf_password';
GRANT ALL PRIVILEGES ON DATABASE bookstore TO librarian;

# Exit and reconnect as the new user
\q

# Connect to the new database
psql -U librarian -d bookstore -h localhost

# Enter the password when prompted.

# ============================================
# PART 4: CREATE A TABLE
# ============================================

CREATE TABLE books (
    book_id     SERIAL PRIMARY KEY,
    title       VARCHAR(200) NOT NULL,
    author      VARCHAR(100) NOT NULL,
    price       DECIMAL(8, 2) NOT NULL CHECK (price >= 0),
    published   DATE
);

# ============================================
# PART 5: INSERT DATA
# ============================================

INSERT INTO books (title, author, price, published)
VALUES
    ('The Great Gatsby', 'F. Scott Fitzgerald', 12.99, '1925-04-10'),
    ('1984', 'George Orwell', 14.99, '1949-06-08'),
    ('To Kill a Mockingbird', 'Harper Lee', 11.99, '1960-07-11');

# ============================================
# PART 6: QUERY THE DATA
# ============================================

SELECT * FROM books;

# Output:
#  book_id |         title          |        author        | price |  published
# ---------+------------------------+----------------------+-------+------------
#        1 | The Great Gatsby       | F. Scott Fitzgerald  | 12.99 | 1925-04-10
#        2 | 1984                   | George Orwell        | 14.99 | 1949-06-08
#        3 | To Kill a Mockingbird  | Harper Lee           | 11.99 | 1960-07-11
# (3 rows)

# ============================================
# PART 7: USE META-COMMANDS
# ============================================

# List tables
\dt

# Describe the books table
\d books

# List databases
\l

# ============================================
# PART 8: QUERY WITH A FILTER
# ============================================

SELECT title, author FROM books WHERE price < 13.00;

# Output:
#         title          |        author
# -----------------------+----------------------
#  The Great Gatsby      | F. Scott Fitzgerald
#  To Kill a Mockingbird | Harper Lee
# (2 rows)

# ============================================
# PART 9: EXIT AND RECONNECT
# ============================================

\q

# Reconnect
psql -U librarian -d bookstore -h localhost

# ============================================
# PART 10: THE WORKFLOW SUMMARY
# ============================================

# 1. Install the server (apt install postgresql)
# 2. Connect as the default postgres user (sudo -u postgres psql)
# 3. Create a database and user
# 4. Connect as the new user
# 5. Create tables
# 6. Insert data
# 7. Query data
# 8. Use meta-commands for inspection
# 9. Exit with \q

The ten parts cover installing PostgreSQL, connecting with psql, creating a database and user, creating a table, inserting data, querying the data, using meta-commands, querying with a filter, exiting and reconnecting, and the workflow summary.


Quick Reference

The Installation Commands

DatabaseInstallationService Check
PostgreSQLsudo apt install postgresqlsudo systemctl status postgresql
MySQLsudo apt install mysql-serversudo systemctl status mysql
SQLitesudo apt install sqlite3No service (file-based)

The Command-Line Clients

DatabaseClientConnect Command
PostgreSQLpsqlsudo -u postgres psql
MySQLmysqlsudo mysql
SQLitesqlite3sqlite3 mydb.db

The psql Meta-Commands

CommandPurpose
\lList databases
\dtList tables
\d table_nameDescribe a table
\dList all objects
\qQuit
\i file.sqlExecute a SQL file

The Graphical Clients

ToolDatabasesPlatform
pgAdmin 4PostgreSQLWindows, macOS, Linux, Web
MySQL WorkbenchMySQLWindows, macOS, Linux
DBeaverMultipleWindows, macOS, Linux
HeidiSQLMySQL, MariaDB, PostgreSQLWindows
TablePlusMultipleWindows, macOS

The Default Ports

DatabaseDefault Port
PostgreSQL5432
MySQL3306
SQLiteNo port (file-based)

Best Practices

✅ Do This:

# Use the official repository for the latest version
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh    # ✅
# Verify the service is running after installation
sudo systemctl status postgresql                                 # ✅
# Use peer authentication for local admin access
sudo -u postgres psql                                            # ✅
# Create a dedicated user for applications
CREATE USER myapp WITH ENCRYPTED PASSWORD 'strong';              # ✅

❌ Don’t Do This:

# Don't run the database as the root user
sudo psql  # root is not a database user                         # ❌
# Don't use weak passwords for database users
CREATE USER myapp WITH PASSWORD '12345';                         # ❌
# Don't skip the service check after installation
# A failed install leaves the server down.                      # ❌
# Don't rely on peer authentication for remote connections
# Peer auth only works on the local socket.                     # ❌

Common Pitfalls

PitfallWhy It HappensFix
psql: command not foundClient package not installedInstall postgresql-client
psql: FATAL: role "root" does not existRunning as root without a database userUse sudo -u postgres psql
mysql: Access deniedWrong user or passwordUse sudo mysql for socket auth
sqlite3: command not foundSQLite not installedsudo apt install sqlite3
Service not startingConfiguration errorCheck journalctl -u postgresql
\dt shows no tablesConnected to the wrong databaseUse \c database_name

Real-World Examples

1. Install PostgreSQL

sudo apt install postgresql

2. Connect with psql

sudo -u postgres psql

3. Create a Database

CREATE DATABASE myapp;

4. Create a User

CREATE USER app_user WITH ENCRYPTED PASSWORD 'secret';

5. Connect as a User

psql -U app_user -d myapp -h localhost

6. List Tables

\dt

7. Describe a Table

\d books

8. Execute a SQL File

\i schema.sql

9. Quit psql

\q

10. Install SQLite

sudo apt install sqlite3

Visual

The Database Architecture

┌──────────────────────────────────────────────┐
│  CLIENT                                      │
│    psql, mysql, sqlite3                      │
│    pgAdmin, Workbench, DBeaver               │
│       │                                      │
│       │  Protocol (TCP or socket)            │
│       ▼                                      │
│  SERVER                                      │
│    postgresql, mysql, sqlite (embedded)      │
│    ├─ Query parser                           │
│    ├─ Query optimizer                        │
│    ├─ Transaction manager                    │
│    └─ Storage engine                         │
│       │                                      │
│       ▼                                      │
│  DATA FILES                                  │
│    /var/lib/postgresql/                      │
│    /var/lib/mysql/                           │
│    mydb.db (SQLite)                          │
│                                              │
└──────────────────────────────────────────────┘

The psql Workflow

┌──────────────────────────────────────────────┐
│  psql WORKFLOW                               │
│                                              │
│  sudo -u postgres psql                       │
│       │                                      │
│       ▼                                      │
│  postgres=# CREATE DATABASE mydb;            │
│  postgres=# \q                               │
│       │                                      │
│       ▼                                      │
│  psql -U myuser -d mydb -h localhost         │
│       │                                      │
│       ▼                                      │
│  mydb=> CREATE TABLE ...;                    │
│  mydb=> INSERT INTO ...;                     │
│  mydb=> SELECT * FROM ...;                   │
│  mydb=> \q                                   │
│                                              │
└──────────────────────────────────────────────┘

The Client Tools

┌──────────────────────────────────────────────┐
│  COMMAND LINE                                │
│    psql, mysql, sqlite3                       │
│    Fast, scriptable, minimal                  │
│                                              │
│  GRAPHICAL                                   │
│    pgAdmin, Workbench, DBeaver, HeidiSQL      │
│    Visual, browse schemas, edit data          │
│                                              │
│  For learning: use the command line first.    │
│  For production: use the tool that fits.      │
│                                              │
└──────────────────────────────────────────────┘

The SQLite Difference

┌──────────────────────────────────────────────┐
│  SERVER-BASED (PostgreSQL, MySQL)            │
│    Separate server process                    │
│    Network protocol                           │
│    User authentication                        │
│    Concurrent connections                     │
│                                              │
│  EMBEDDED (SQLite)                            │
│    No server process                          │
│    No network protocol                        │
│    No user authentication                     │
│    Single file                                │
│                                              │
│  SQLite is a library, not a server.           │
│                                              │
└──────────────────────────────────────────────┘

Summary

ItemValue
PostgreSQL installsudo apt install postgresql
PostgreSQL clientpsql
PostgreSQL default port5432
MySQL installsudo apt install mysql-server
MySQL clientmysql
MySQL default port3306
SQLite installsudo apt install sqlite3
SQLite clientsqlite3
SQLite storageSingle file
pgAdmin 4Official PostgreSQL GUI
MySQL WorkbenchOfficial MySQL GUI
DBeaverMulti-database GUI

Key takeaways:

  • PostgreSQL, MySQL, and SQLite are the three open-source RDBMSs most commonly used for learning and development. PostgreSQL and MySQL are server-based. SQLite is embedded .
  • PostgreSQL is installed from the PGDG repository for the latest version. The quickstart is apt install postgresql-common, run the apt.postgresql.org.sh script, and apt install postgresql .
  • MySQL is installed from Ubuntu’s default repository or Oracle’s APT repository. The default repository has a simpler setup; the Oracle repository has the latest version .
  • SQLite is installed with a single command and requires no server. The sqlite3 tool creates the database file on first use .
  • The command-line client is the primary interface. psql, mysql, and sqlite3 support SQL statements and meta-commands for inspection and administration .
  • Graphical clients provide a visual interface for the same operations. pgAdmin 4 for PostgreSQL, MySQL Workbench for MySQL, and DBeaver for multiple databases .
  • The server and client communicate over a protocol. PostgreSQL uses port 5432. MySQL uses port 3306. SQLite has no network protocol because it is not a server.

Remember: Before you can write SQL, you need a database to run it against. Install a server. Connect with a client. Create a database. Create a table. Insert data. Query it. The command-line client is the fastest path to understanding the syntax. Graphical clients are useful once you are comfortable. PostgreSQL is the most standards-compliant. MySQL is the most widely deployed. SQLite is the simplest. Choose the one that matches your project, and start with the command line.


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!