Relational Database Fundamentals

Level: Intermediate Module: Database Services 9 min read Lesson 40 of 66

Overview

  • What you’ll learn: The relational data model, core SQL operations (DDL/DML/DCL), ACID transaction properties, normalization forms, indexing fundamentals, and criteria for selecting an RDBMS on Ubuntu Server.
  • Prerequisites: Module 1 (Linux Fundamentals), basic command-line proficiency
  • Estimated reading time: 20 minutes

Introduction

Relational databases have been the backbone of enterprise data management for over four decades. From financial transactions and customer records to application session state and content management systems, relational database management systems (RDBMS) provide the structured, consistent, and durable storage that production workloads demand.

Before diving into the installation and administration of specific database servers such as MySQL and PostgreSQL, it is essential to understand the theoretical foundation upon which they are built. The relational model, first proposed by Edgar F. Codd in 1970, organizes data into tables (relations), enforces integrity through constraints, and provides a powerful query language — SQL — for manipulating that data.

In this lesson you will learn the core concepts of relational databases, understand how ACID properties guarantee data reliability, explore normalization to eliminate redundancy, and survey the RDBMS options available on Ubuntu Server so that you can make an informed choice for your workloads.

The Relational Model

At its core, the relational model represents data as a collection of relations (tables). Each relation consists of tuples (rows) and attributes (columns). Every attribute has a defined data type and an associated domain — the set of permissible values.

Tables, Rows, and Columns

A table is the fundamental storage unit. Each row represents a single record, and each column represents a specific piece of information about that record. For example, a users table might contain columns for id, username, email, and created_at.

-- Example: creating a simple users table
CREATE TABLE users (
    id         SERIAL PRIMARY KEY,
    username   VARCHAR(64) NOT NULL UNIQUE,
    email      VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Primary Keys and Foreign Keys

A primary key uniquely identifies each row in a table. It must be unique and not null. A foreign key is a column (or set of columns) in one table that references the primary key of another table, establishing a relationship between the two.

-- Foreign key example: orders references users
CREATE TABLE orders (
    id       SERIAL PRIMARY KEY,
    user_id  INTEGER NOT NULL REFERENCES users(id),
    total    DECIMAL(10,2) NOT NULL,
    status   VARCHAR(20) DEFAULT 'pending'
);

Foreign keys enforce referential integrity — you cannot insert an order for a user that does not exist, and you cannot delete a user who has outstanding orders (unless cascading rules are defined).

SQL Foundations

Structured Query Language (SQL) is the standard interface for interacting with relational databases. SQL statements are grouped into three categories:

  • DDL (Data Definition Language): CREATE, ALTER, DROP — define and modify schema objects.
  • DML (Data Manipulation Language): SELECT, INSERT, UPDATE, DELETE — read and write data.
  • DCL (Data Control Language): GRANT, REVOKE — manage access permissions.

Essential DML Operations

-- Insert a row
INSERT INTO users (username, email) VALUES ('alice', 'alice@example.com');

-- Query with a filter
SELECT id, username, email FROM users WHERE username = 'alice';

-- Update a row
UPDATE users SET email = 'alice@newdomain.com' WHERE username = 'alice';

-- Delete a row
DELETE FROM users WHERE username = 'alice';

Joins

Joins combine rows from two or more tables based on a related column. The most common types are:

  • INNER JOIN: Returns only rows that have matching values in both tables.
  • LEFT JOIN: Returns all rows from the left table plus matched rows from the right table (nulls where no match).
  • RIGHT JOIN: The reverse of LEFT JOIN.
  • FULL OUTER JOIN: Returns all rows from both tables, with nulls where there is no match.
-- Inner join: users with their orders
SELECT u.username, o.id AS order_id, o.total
FROM users u
INNER JOIN orders o ON u.id = o.user_id;

ACID Properties

Reliable databases guarantee four properties for every transaction, collectively known as ACID:

  • Atomicity: A transaction is all-or-nothing. If any statement within the transaction fails, the entire transaction is rolled back.
  • Consistency: A transaction moves the database from one valid state to another. All constraints, triggers, and rules are satisfied before and after the transaction.
  • Isolation: Concurrent transactions do not interfere with each other. The database provides isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) to balance consistency with performance.
  • Durability: Once a transaction is committed, the changes survive system crashes. This is typically achieved through write-ahead logging (WAL).
-- Transaction example
BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT;

-- If anything fails, roll back
ROLLBACK;

Normalization

Normalization is the process of organizing tables to reduce data redundancy and improve integrity. The most commonly referenced forms are:

  • First Normal Form (1NF): Every column contains atomic (indivisible) values; no repeating groups.
  • Second Normal Form (2NF): 1NF plus every non-key column is fully dependent on the entire primary key (eliminates partial dependencies).
  • Third Normal Form (3NF): 2NF plus no non-key column depends on another non-key column (eliminates transitive dependencies).

In practice, most production schemas aim for 3NF. Denormalization — intentionally introducing redundancy — is sometimes used for read-heavy workloads where join performance becomes a bottleneck.

Indexing Fundamentals

An index is a data structure (typically a B-tree or hash) that allows the database to locate rows without scanning the entire table. Indexes dramatically speed up SELECT queries but add overhead to INSERT, UPDATE, and DELETE operations because the index must be maintained.

-- Create an index on the email column
CREATE INDEX idx_users_email ON users (email);

-- Composite index on two columns
CREATE INDEX idx_orders_user_status ON orders (user_id, status);

-- Examine query execution plan
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'alice@example.com';

As a general rule, index columns that appear frequently in WHERE clauses, JOIN conditions, and ORDER BY clauses. Avoid over-indexing — each additional index consumes disk space and slows down write operations.

Choosing an RDBMS on Ubuntu Server

Ubuntu Server provides official packages for several relational databases. The two most popular open-source options are:

  • MySQL / MariaDB: Widely used in web applications (LAMP/LEMP stacks). MySQL is developed by Oracle; MariaDB is a community-maintained fork. Both use the apt packages mysql-server or mariadb-server.
  • PostgreSQL: Known for standards compliance, advanced features (JSONB, CTEs, window functions, full-text search), and extensibility. Available via the postgresql package.
# Check available MySQL packages
$ apt-cache search mysql-server

# Check available PostgreSQL packages
$ apt-cache search postgresql | head -20

When selecting a database, consider factors such as: the application framework’s default support, required SQL feature set, replication and clustering needs, community and commercial support, and your team’s existing expertise.

Key Takeaways

  • The relational model organizes data into tables with rows and columns, enforcing integrity through primary keys, foreign keys, and constraints.
  • SQL is divided into DDL (schema), DML (data), and DCL (permissions) categories.
  • ACID properties (Atomicity, Consistency, Isolation, Durability) guarantee reliable transactions.
  • Normalization (1NF through 3NF) reduces redundancy; denormalization is a deliberate trade-off for read performance.
  • Indexes accelerate reads at the cost of additional write overhead — index strategically.
  • Ubuntu Server offers MySQL/MariaDB and PostgreSQL as the primary open-source RDBMS options; choose based on feature needs, ecosystem, and team expertise.

What’s Next

In Lesson 41, you will install and configure MySQL Server on Ubuntu, set up secure authentication, create databases and users, and learn essential administration commands for day-to-day operations.

繁體中文

概覽

  • 您將學到:關聯式資料模型、核心 SQL 操作(DDL/DML/DCL)、ACID 交易屬性、正規化形式、索引基礎,以及在 Ubuntu Server 上選擇 RDBMS 的標準。
  • 先決條件:模組 1(Linux 基礎)、基本命令列操作能力
  • 預估閱讀時間:20 分鐘

簡介

關聯式資料庫四十多年來一直是企業資料管理的基石。從金融交易和客戶記錄到應用程式會話狀態和內容管理系統,關聯式資料庫管理系統(RDBMS)提供了生產工作負載所需的結構化、一致性和持久性儲存。

在深入安裝和管理 MySQL 和 PostgreSQL 等特定資料庫伺服器之前,了解它們所依據的理論基礎至關重要。關聯模型由 Edgar F. Codd 於 1970 年首次提出,將資料組織到表(關聯)中,通過約束強制完整性,並提供強大的查詢語言——SQL——來操作資料。

在本課中,您將學習關聯式資料庫的核心概念,了解 ACID 屬性如何保證資料可靠性,探索正規化以消除冗餘,並概覽 Ubuntu Server 上可用的 RDBMS 選項,以便為您的工作負載做出明智的選擇。

關聯模型

關聯模型的核心是將資料表示為關聯(表)的集合。每個關聯由元組(列)和屬性(欄)組成。每個屬性都有定義的資料類型和相關的域——可允許值的集合。

表、列和欄

表是基本的儲存單位。每一列代表一筆記錄,每一欄代表該記錄的一項特定資訊。例如,users 表可能包含 idusernameemailcreated_at 欄位。

-- 範例:建立簡單的使用者表
CREATE TABLE users (
    id         SERIAL PRIMARY KEY,
    username   VARCHAR(64) NOT NULL UNIQUE,
    email      VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

主鍵和外鍵

主鍵唯一識別表中的每一列。它必須是唯一且非空的。外鍵是一個表中的欄(或一組欄),引用另一個表的主鍵,建立兩者之間的關係。

-- 外鍵範例:orders 引用 users
CREATE TABLE orders (
    id       SERIAL PRIMARY KEY,
    user_id  INTEGER NOT NULL REFERENCES users(id),
    total    DECIMAL(10,2) NOT NULL,
    status   VARCHAR(20) DEFAULT 'pending'
);

SQL 基礎

結構化查詢語言(SQL)是與關聯式資料庫互動的標準介面。SQL 語句分為三類:

  • DDL(資料定義語言):CREATEALTERDROP——定義和修改結構物件。
  • DML(資料操作語言):SELECTINSERTUPDATEDELETE——讀寫資料。
  • DCL(資料控制語言):GRANTREVOKE——管理存取權限。

基本 DML 操作

-- 插入一列
INSERT INTO users (username, email) VALUES ('alice', 'alice@example.com');

-- 帶篩選條件的查詢
SELECT id, username, email FROM users WHERE username = 'alice';

-- 更新一列
UPDATE users SET email = 'alice@newdomain.com' WHERE username = 'alice';

-- 刪除一列
DELETE FROM users WHERE username = 'alice';

聯結

聯結根據相關欄位合併兩個或多個表的列。最常見的類型包括:

  • INNER JOIN:僅返回兩個表中都有匹配值的列。
  • LEFT JOIN:返回左表的所有列加上右表中匹配的列(無匹配處為 null)。
  • RIGHT JOIN:LEFT JOIN 的反向操作。
  • FULL OUTER JOIN:返回兩個表的所有列,無匹配處為 null。

ACID 屬性

可靠的資料庫為每個交易保證四個屬性,統稱為 ACID

  • 原子性(Atomicity):交易是全有或全無的。如果交易中的任何語句失敗,整個交易將回滾。
  • 一致性(Consistency):交易將資料庫從一個有效狀態移至另一個。所有約束、觸發器和規則在交易前後都得到滿足。
  • 隔離性(Isolation):並行交易不會互相干擾。資料庫提供隔離級別以平衡一致性和效能。
  • 持久性(Durability):一旦交易提交,變更在系統崩潰後仍然存在。通常透過預寫日誌(WAL)實現。

正規化

正規化是組織表以減少資料冗餘和提高完整性的過程。最常引用的形式包括:

  • 第一正規形式(1NF):每個欄位包含原子(不可分割)值;沒有重複群組。
  • 第二正規形式(2NF):1NF 加上每個非鍵欄完全依賴於整個主鍵。
  • 第三正規形式(3NF):2NF 加上沒有非鍵欄依賴於另一個非鍵欄。

索引基礎

索引是一種資料結構(通常是 B-tree 或雜湊),允許資料庫在不掃描整個表的情況下定位列。索引大幅加速 SELECT 查詢,但會增加 INSERTUPDATEDELETE 操作的開銷。

-- 在 email 欄位上建立索引
CREATE INDEX idx_users_email ON users (email);

-- 檢查查詢執行計畫
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'alice@example.com';

在 Ubuntu Server 上選擇 RDBMS

Ubuntu Server 為多個關聯式資料庫提供官方套件。兩個最受歡迎的開源選項是:

  • MySQL / MariaDB:廣泛用於 Web 應用程式(LAMP/LEMP 堆疊)。
  • PostgreSQL:以標準合規性、進階功能和可擴展性著稱。
# 檢查可用的 MySQL 套件
$ apt-cache search mysql-server

# 檢查可用的 PostgreSQL 套件
$ apt-cache search postgresql | head -20

重點回顧

  • 關聯模型將資料組織到具有列和欄的表中,透過主鍵、外鍵和約束強制完整性。
  • SQL 分為 DDL(結構)、DML(資料)和 DCL(權限)類別。
  • ACID 屬性(原子性、一致性、隔離性、持久性)保證可靠的交易。
  • 正規化(1NF 到 3NF)減少冗餘;反正規化是為了讀取效能的刻意取捨。
  • 索引加速讀取但增加寫入開銷——應策略性地建立索引。
  • Ubuntu Server 提供 MySQL/MariaDB 和 PostgreSQL 作為主要的開源 RDBMS 選項。

下一步

在第 41 課中,您將在 Ubuntu 上安裝和配置 MySQL Server,設定安全認證,建立資料庫和使用者,並學習日常操作的基本管理命令。

日本語

概要

  • 学習内容:リレーショナルデータモデル、コア SQL 操作(DDL/DML/DCL)、ACID トランザクション特性、正規化形式、インデックスの基礎、Ubuntu Server での RDBMS 選定基準。
  • 前提条件:モジュール 1(Linux 基礎)、基本的なコマンドライン操作能力
  • 推定読了時間:20 分

はじめに

リレーショナルデータベースは、40 年以上にわたってエンタープライズデータ管理の基盤となっています。金融取引や顧客記録からアプリケーションセッション状態やコンテンツ管理システムまで、リレーショナルデータベース管理システム(RDBMS)は、本番ワークロードが必要とする構造化された一貫性のある永続的なストレージを提供します。

MySQL や PostgreSQL などの特定のデータベースサーバーのインストールと管理に入る前に、それらが構築されている理論的基盤を理解することが不可欠です。1970 年に Edgar F. Codd が最初に提案したリレーショナルモデルは、データをテーブル(リレーション)に整理し、制約によって整合性を強制し、データを操作するための強力なクエリ言語——SQL——を提供します。

このレッスンでは、リレーショナルデータベースのコアコンセプトを学び、ACID 特性がデータの信頼性をどのように保証するかを理解し、冗長性を排除するための正規化を探り、Ubuntu Server で利用可能な RDBMS オプションを概観して、ワークロードに適した選択ができるようにします。

リレーショナルモデル

リレーショナルモデルの核心は、データをリレーション(テーブル)のコレクションとして表現することです。各リレーションはタプル(行)と属性(列)で構成されます。各属性には定義されたデータ型と関連するドメイン——許容値の集合——があります。

テーブル、行、列

テーブルは基本的なストレージ単位です。各行は1つのレコードを表し、各列はそのレコードの特定の情報を表します。

-- 例:シンプルなユーザーテーブルの作成
CREATE TABLE users (
    id         SERIAL PRIMARY KEY,
    username   VARCHAR(64) NOT NULL UNIQUE,
    email      VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

主キーと外部キー

主キーはテーブル内の各行を一意に識別します。一意かつ非 NULL でなければなりません。外部キーは、あるテーブルの列が別のテーブルの主キーを参照し、2つのテーブル間の関係を確立します。

-- 外部キーの例:orders が users を参照
CREATE TABLE orders (
    id       SERIAL PRIMARY KEY,
    user_id  INTEGER NOT NULL REFERENCES users(id),
    total    DECIMAL(10,2) NOT NULL,
    status   VARCHAR(20) DEFAULT 'pending'
);

SQL の基礎

構造化問合せ言語(SQL)はリレーショナルデータベースと対話するための標準インターフェースです。SQL 文は3つのカテゴリに分類されます:

  • DDL(データ定義言語):CREATEALTERDROP——スキーマオブジェクトの定義と変更。
  • DML(データ操作言語):SELECTINSERTUPDATEDELETE——データの読み書き。
  • DCL(データ制御言語):GRANTREVOKE——アクセス権限の管理。

基本的な DML 操作

-- 行の挿入
INSERT INTO users (username, email) VALUES ('alice', 'alice@example.com');

-- フィルタ付きクエリ
SELECT id, username, email FROM users WHERE username = 'alice';

-- 行の更新
UPDATE users SET email = 'alice@newdomain.com' WHERE username = 'alice';

-- 行の削除
DELETE FROM users WHERE username = 'alice';

結合

結合は、関連する列に基づいて2つ以上のテーブルの行を組み合わせます。最も一般的な種類は:

  • INNER JOIN:両方のテーブルに一致する値がある行のみを返す。
  • LEFT JOIN:左テーブルのすべての行と右テーブルの一致する行を返す(一致がない場合は null)。
  • RIGHT JOIN:LEFT JOIN の逆。
  • FULL OUTER JOIN:両方のテーブルのすべての行を返し、一致がない場合は null。

ACID 特性

信頼性の高いデータベースは、すべてのトランザクションに対して ACID と総称される4つの特性を保証します:

  • 原子性(Atomicity):トランザクションは全か無かです。トランザクション内のいずれかの文が失敗すると、トランザクション全体がロールバックされます。
  • 一貫性(Consistency):トランザクションはデータベースをある有効な状態から別の有効な状態に移行します。
  • 分離性(Isolation):同時実行トランザクションは互いに干渉しません。
  • 永続性(Durability):トランザクションがコミットされると、変更はシステムクラッシュ後も存続します。通常、先行書き込みログ(WAL)で実現されます。

正規化

正規化は、データの冗長性を減らし整合性を向上させるためにテーブルを整理するプロセスです:

  • 第一正規形(1NF):各列がアトミック(不可分)な値を含み、繰り返しグループがない。
  • 第二正規形(2NF):1NF に加え、すべての非キー列が主キー全体に完全に依存する。
  • 第三正規形(3NF):2NF に加え、非キー列が他の非キー列に依存しない。

インデックスの基礎

インデックスは、テーブル全体をスキャンせずに行を特定できるデータ構造(通常は B-tree またはハッシュ)です。インデックスは SELECT クエリを大幅に高速化しますが、INSERTUPDATEDELETE 操作にオーバーヘッドを追加します。

-- email 列にインデックスを作成
CREATE INDEX idx_users_email ON users (email);

-- クエリ実行計画の確認
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'alice@example.com';

Ubuntu Server での RDBMS 選定

Ubuntu Server は複数のリレーショナルデータベースの公式パッケージを提供しています。最も人気のある2つのオープンソースオプションは:

  • MySQL / MariaDB:Web アプリケーション(LAMP/LEMP スタック)で広く使用されています。
  • PostgreSQL:標準準拠、高度な機能、拡張性で知られています。
# 利用可能な MySQL パッケージを確認
$ apt-cache search mysql-server

# 利用可能な PostgreSQL パッケージを確認
$ apt-cache search postgresql | head -20

重要ポイント

  • リレーショナルモデルはデータを行と列を持つテーブルに整理し、主キー、外部キー、制約で整合性を強制する。
  • SQL は DDL(スキーマ)、DML(データ)、DCL(権限)のカテゴリに分けられる。
  • ACID 特性(原子性、一貫性、分離性、永続性)が信頼性の高いトランザクションを保証する。
  • 正規化(1NF ~ 3NF)は冗長性を削減し、非正規化は読み取りパフォーマンスのための意図的なトレードオフ。
  • インデックスは読み取りを高速化するが書き込みオーバーヘッドが増加する——戦略的にインデックスを作成すること。
  • Ubuntu Server は MySQL/MariaDB と PostgreSQL を主要なオープンソース RDBMS オプションとして提供している。

次のステップ

レッスン 41 では、Ubuntu に MySQL Server をインストールして設定し、セキュアな認証を設定し、データベースとユーザーを作成し、日常運用に必要な基本的な管理コマンドを学びます。

You Missed