Ir al contenido
Londres, Reino Unido · Fundado en 1994
Español

Unit 4: Data and Databases

Why organisations store data in databases, how the relational model organises it into related tables, how SQL is used to query it, and how good design keeps data accurate and safe.

Unit 4 of 5 · about 54 minutes

4.1 Why databases and the relational model

Almost every organisation depends on stored data: customers, orders, stock, staff, payments, appointments. Small amounts can be managed in documents or spreadsheets, but as the volume of data, the number of users and the importance of accuracy grow, these tools start to struggle. A database is an organised collection of data, and a database management system (DBMS) is the software that stores it, controls access to it and lets people and programs query and update it safely.

Why not just use spreadsheets?

Spreadsheets are excellent for analysis and small lists, but they have well-known weaknesses when used as shared systems of record:

  • The same information is often copied into several places, so a change in one place leaves others out of date.
  • It is easy to type inconsistent values, such as "London", "london" and "Ldn", in the same column.
  • Several people editing at once can overwrite each other's work.
  • Access control is usually all or nothing for a whole file.
  • Performance falls as files grow very large.

A DBMS addresses these problems by enforcing structure, validating data, managing many simultaneous users, controlling who can see and change what, and providing backup and recovery features.

The relational model

The most widely used type of database is the relational database, based on ideas published by the computer scientist Edgar F. Codd in 1970. Data is organised into tables (formally called relations). Each table describes one kind of thing, such as customers or orders. Each row is one instance of that thing, such as one customer, and each column is one attribute, such as the customer's name or postcode. Every column has a defined data type, such as text, whole number, decimal or date.

Keys and relationships

Two ideas make relational databases powerful:

  • A primary key is a column, or combination of columns, whose value uniquely identifies each row. A customer number is a typical example. Names are poor keys because two people can share a name.
  • A foreign key is a column in one table that refers to the primary key of another. An orders table might include a customer number column, linking each order to exactly one customer.

Relationships between tables come in three common forms. In a one-to-many relationship, one customer can place many orders, but each order belongs to one customer. In a many-to-many relationship, such as students and courses, a third "linking" table records each pairing. One-to-one relationships are less common, for example separating sensitive details into their own table.

Tip: Sketch your tables and the lines between them on paper before building anything. A simple diagram showing each table, its key and its relationships is called an entity-relationship diagram, and it is the most useful planning tool in database design.

Other types of database

Relational databases are not the only option. The term NoSQL covers several alternatives designed for particular needs:

  • Document databases store flexible records, often in a format called JSON, suiting data whose structure varies.
  • Key-value stores act like very large, very fast dictionaries, often used for caching and session data.
  • Graph databases specialise in highly connected data, such as networks of people or fraud rings.
  • Column-oriented and analytical databases are optimised for summarising very large volumes of data.

Many organisations use more than one type. Relational databases remain the default choice for business records where accuracy and consistency matter most. The right choice depends on the shape of the data, how it will be queried, how much it will grow and the skills available to look after it. Choosing an unfamiliar technology simply because it is fashionable is a common and costly mistake.

In practice

If your team runs an important process from a shared spreadsheet that is growing, suffering from conflicting edits or full of inconsistent entries, these are signs that a database, or an application built on one, may be appropriate. Even if you stay with spreadsheets, relational thinking helps: keep one table per kind of thing, give each row a unique identifier, avoid copying the same data into several places and use drop-down lists to keep values consistent.

4.2 Asking questions with SQL

SQL (Structured Query Language, often pronounced "sequel" or spelled out) is the standard language for working with relational databases. It has been in use since the 1970s and remains one of the most valuable technical skills for analysts, developers and many business roles. Different database products add their own variations, but the core statements are very similar everywhere.

SQL is declarative: you describe the result you want, and the database works out how to obtain it efficiently. This makes simple queries readable even for beginners.

Retrieving data with SELECT

Imagine a table called customers with columns customer_id, name, city and joined_date. The query

SELECT name, city FROM customers WHERE city = 'Leeds' ORDER BY name;

returns the name and city of every customer in Leeds, sorted alphabetically by name. Each part has a clear job:

  • SELECT lists the columns you want. SELECT * returns all columns, which is convenient but often wasteful.
  • FROM names the table.
  • WHERE filters the rows. Conditions can be combined with AND and OR, and patterns can be matched with LIKE.
  • ORDER BY sorts the results, ascending by default or descending with DESC.

Summarising data

SQL can summarise as well as list. Aggregate functions include COUNT, SUM, AVG, MIN and MAX. Combined with GROUP BY, they produce summaries for each group:

SELECT city, COUNT(*) FROM customers GROUP BY city;

returns each city with its number of customers. A HAVING clause filters the groups afterwards, for example keeping only cities with more than 50 customers. Remember the difference: WHERE filters individual rows before grouping; HAVING filters groups after.

Combining tables with JOIN

Because data is split across tables, many questions require combining them. Suppose an orders table has order_id, customer_id, order_date and amount. To list each order with the customer's name:

SELECT customers.name, orders.order_date, orders.amount FROM orders JOIN customers ON orders.customer_id = customers.customer_id;

The JOIN matches rows using the foreign key. An ordinary (inner) join returns only rows that match in both tables. A LEFT JOIN keeps every row from the first table even if there is no match, which is useful for questions such as "which customers have never ordered?".

Remember: When totals from a joined query look too high, check whether the join has created duplicate rows. Joining to a table with several matching rows repeats the data from the other side.

Changing data

SQL also changes data:

  • INSERT adds new rows.
  • UPDATE changes existing rows, for example correcting a customer's city.
  • DELETE removes rows.

These statements are powerful and can affect thousands of rows at once. An UPDATE or DELETE without a WHERE clause applies to every row in the table, a mistake that has caused many real incidents. Careful practitioners first run a SELECT with the same WHERE clause to see exactly which rows will be affected, and make changes in a test environment or inside a transaction that can be undone.

Missing values

Databases represent unknown or missing values as NULL. NULL is not zero and not an empty piece of text; it means "no value". It behaves in surprising ways: a condition such as "city = NULL" does not find missing cities, so SQL uses the special test IS NULL instead. Averages and counts of a particular column ignore NULLs, which can change results noticeably.

Common beginner mistakes

  • Forgetting that text comparisons may be case-sensitive in some databases, so 'leeds' does not match 'Leeds'.
  • Writing a long query in one go instead of building and checking it a clause at a time.
  • Trusting results without comparing them against a figure you already know.

In practice

Even a little SQL lets you answer questions directly rather than waiting for a report: how many orders each region placed last month, which products have not sold, which customers have lapsed. If you are given read-only access to a reporting database, start by exploring each table with simple SELECT queries, check row counts against known figures and build up more complex queries one step at a time, checking the results at each stage.

4.3 Good data design, integrity and security

A database is only as useful as the quality of the data it holds. Poor design leads to duplicated, inconsistent and contradictory information, while good design makes errors difficult to introduce in the first place. This lesson covers the principles that keep data accurate, consistent and safe.

Normalisation

Normalisation is the process of organising tables to reduce duplication and the problems it causes. Consider a single table of orders in which every row repeats the customer's name, address and phone number. If the customer moves, every one of their order rows must be updated; miss one and the database now contradicts itself. If their only order is deleted, their details vanish altogether.

Normalisation solves this by storing each fact once. Customer details go in a customers table, orders in an orders table, and the two are linked by a customer number. The formal theory describes several "normal forms", but the practical principle can be summarised simply:

  1. Each table should describe one kind of thing.
  2. Each column should hold a single value, not a list.
  3. Every non-key column should describe the thing identified by the key, and nothing else.

Designers sometimes deliberately denormalise, duplicating some data, for example in reporting databases where speed of reading matters more than ease of updating. This should be a conscious decision, not an accident.

Integrity constraints

A DBMS can enforce rules, called constraints, that reject bad data automatically:

  • Primary key constraints prevent duplicate identifiers.
  • Foreign key constraints prevent an order from referring to a customer who does not exist, a property called referential integrity.
  • NOT NULL constraints require a value to be present.
  • Unique constraints prevent, for example, two accounts sharing an email address.
  • Check constraints enforce rules such as "quantity must be greater than zero".

Rules enforced by the database apply to every application and user, which is more reliable than hoping each program checks correctly.

Transactions

Many operations involve several related changes. Transferring money between two accounts means reducing one balance and increasing the other. If the system fails halfway, money must not disappear. Databases handle this with transactions: groups of changes treated as a single unit. Reliable transactions are often described by the acronym ACID:

  • Atomicity: all the changes happen, or none do.
  • Consistency: the database moves from one valid state to another, respecting all rules.
  • Isolation: simultaneous transactions do not interfere with each other.
  • Durability: once confirmed, changes survive crashes and power failures.

Indexes and performance

An index is a separate structure, usually a kind of tree, that lets the database find rows by a particular column without scanning the whole table, much like the index at the back of a book. Indexes speed up searches dramatically but take up space and slow down inserts and updates slightly, because the index must also be maintained. Columns that are frequently searched or used in joins are good candidates.

Tip: Validate data at the point of entry. Drop-down lists, date pickers and format checks prevent far more problems than cleaning up inconsistent data later.

Security and privacy

Databases often hold personal and commercially sensitive information, so protecting them is essential. Key practices include granting each user and application only the access they need, encrypting data in storage and in transit, keeping regular tested backups, logging access to sensitive tables, and keeping only the personal data that is genuinely needed. Many countries have data protection laws, such as the GDPR in the European Union and the United Kingdom, that require such safeguards. A well-known attack called SQL injection tricks an application into running malicious SQL by entering it into a form; developers prevent it by using parameterised queries rather than building SQL from user input.

In practice

When asked to review or request a new system, ask how it prevents duplicate and inconsistent records, which fields are mandatory, how often it is backed up and when a restore was last tested, and who can see sensitive data. These questions require no technical expertise but address the most common causes of data problems.

Case study: Fixing duplicate patient bookings at a physiotherapy group

Brookside Physio, a fictional group of three physiotherapy clinics, kept bookings in a shared spreadsheet. Each row held the appointment time, therapist and the patient's full contact details. Over time, patients appeared under slightly different names, phone numbers became out of date in some rows but not others, and two receptionists occasionally booked the same slot at once.

The practice manager worked with a local developer to move bookings into a small relational database behind a simple web form. Patients, therapists, clinics and appointments became separate tables, each with its own identifier. Appointments referred to patients and therapists by foreign keys, so contact details were stored once and updated in one place.

The developer added a unique constraint on therapist and time slot, so double bookings were rejected automatically, and made phone number and date of birth mandatory. Booking changes ran inside transactions. Reception staff were given access to booking data only, while clinical notes stayed in a separate, more restricted system. Weekly reports, previously assembled by hand, were replaced by a few SQL queries.

Activity

Choose a spreadsheet or list you use at work or at home that holds information about more than one kind of thing, such as customers and orders or members and events. Redesign it as two or three related tables, naming each table's primary key and any foreign keys. Then write one SQL query, in plain form, that would answer a useful question from your design.

Compare with a model answer

A good answer identifies the separate things being tracked, for example a volunteer rota that mixes volunteer details with shift information. It proposes a volunteers table (volunteer_id as primary key, name, email, phone), a shifts table (shift_id, date, location, start_time) and a linking assignments table (volunteer_id and shift_id as foreign keys) because volunteers work many shifts and shifts have many volunteers.

It explains that contact details are now stored once. The query is relevant and correctly structured, for example: SELECT volunteers.name, COUNT(*) FROM assignments JOIN volunteers ON assignments.volunteer_id = volunteers.volunteer_id GROUP BY volunteers.name; to count shifts per volunteer. The best answers suggest a constraint, such as preventing the same volunteer being assigned twice to one shift.

Key takeaways

  • Databases provide structure, validation, multi-user access, security and recovery that shared spreadsheets lack.
  • Relational databases organise data into tables linked by primary and foreign keys.
  • SQL lets you retrieve, filter, sort, summarise and join data; UPDATE and DELETE need particular care with WHERE clauses.
  • Normalisation stores each fact once, and constraints and transactions keep data accurate and consistent.
  • Good database practice includes least-privilege access, encryption, tested backups and protection against SQL injection.

Unit check

Create a free account to answer the check, save your progress and receive your free certificate.

Create a free account Log in
← Unit 3 Unit 5 →
WhatsApp