SQL · Module 1 · Lesson 11 min read

What is a Database?

Data, databases and DBMS

  • Data – raw facts: a name, a price, a date
  • Database – an organised collection of data that is stored so it can be found, updated and protected easily
  • DBMS (Database Management System) – the software that manages the database: PostgreSQL, MySQL, SQL Server, SQLite, Oracle

Why not just use a spreadsheet or files?

Spreadsheet / filesDatabase
Slow with millions of rowsHandles billions of rows
One person edits at a timeThousands of users at once
Easy to type invalid dataRules (constraints) block bad data
Hard to link dataRelationships between tables
Manual backupsBackups, recovery, security, permissions

Relational databases

Data is stored in tables (also called relations):

  • Table – one kind of thing: users, expenses
  • Row (record) – one item: one user
  • Column (field) – one property: name, email
  • Each row has a unique primary key (like id)
  • Tables are linked with foreign keys (expenses.user_id → users.id)
Terminal
users                              expenses
id | name        | city            id | user_id | title      | amount
1  | Asha Sharma | Kathmandu       1  | 1       | Groceries  | 2450.00
2  | Ravi Thapa  | Pokhara         2  | 1       | Taxi       | 450.00

Where databases are used

Banking, e-commerce, social media, hospitals, schools, games, and of course budgeting apps. Almost every backend you'll ever build has a database at its core.

Example

SQL
-- A table is like a smart spreadsheet with strict rules
CREATE TABLE friends (
  id    INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name  TEXT NOT NULL,
  phone TEXT UNIQUE
);

INSERT INTO friends (name, phone) VALUES
  ('Asha', '9801111111'),
  ('Ravi', '9802222222');

SELECT * FROM friends;
--  id | name |   phone
-- ----+------+------------
--   1 | Asha | 9801111111
--   2 | Ravi | 9802222222

-- The database protects your data: this fails (phone must be unique)
-- INSERT INTO friends (name, phone) VALUES ('Copycat', '9801111111');
-- ERROR: duplicate key value violates unique constraint "friends_phone_key"

DROP TABLE friends;