العلائقية مقابل غير العلائقية
في هذا الدرس 11 موضوعات
هذا الدرس متاح حاليًا باللغة الإنجليزية فقط، ولم تُنشر نسخته العربية بعد.
Lesson Overview
There is more than one way to organise data in a database. The two big families are relational databases, which keep data in tables linked by keys, and nonrelational databases (often called NoSQL), which use other shapes such as documents, key-value pairs, or graphs. This lesson compares them at a high level. You will not learn a query language yet. The goal is to understand the difference well enough to explain it and to avoid a very common myth: "NoSQL is faster".
You will use the previous lesson's shapes: structured data fits tables naturally, and semi-structured data fits documents naturally. You will also see how two tables linked by a key keep a fact in one place, and how a document keeps related data together.
Why this matters for a backend: this course continues with a relational database (PostgreSQL, introduced later), so you need to know what "relational" means and what the alternatives are. Teams also choose between the families for real projects, and a good choice starts from the data and the work, not from a trend.
Learning Objectives
By the end of this lesson you will be able to:
- Describe a relational database as tables of rows and columns linked by keys.
- Explain what a primary key and a foreign key do, in plain words.
- Name the main nonrelational styles: document, key-value, and graph.
- Compare the same contact stored as table rows and as a document.
- Explain that "NoSQL is faster" is not true in general.
- Give a reason to choose each family that does not rely on the word "faster".
Written Explanation
Relational: tables linked by keys
In a relational database, data is stored in tables. PostgreSQL's manual describes it this way: a table is a named collection of rows, every row in a table has the same set of named columns, and each column has a specific data type. The word "relation" is the mathematical term for a table.
A primary key is a column (or set of columns) whose value identifies one row uniquely, such as a contact's id. A foreign key is a column in one table that refers to the primary key of another, which is how tables are linked. If the phones table has a contact_id column holding a contact's id, you can find all phones of that contact by following the key.
Relational databases are queried with SQL, a standard language you will start learning in a later module. They check rules on write (types, required values, uniqueness, links between tables), and they are strong at keeping data consistent when many changes happen together.
The key design habit: keep each fact in one place and refer to it by key. A contact's name is stored once, in contacts. Orders refer to the contact by id. If the name changes, there is one row to change.
Nonrelational: other shapes
"Nonrelational" or NoSQL is a loose label for many databases that do not use the table-and-key model. Four styles are common:
| Style | Idea | Example use |
|---|---|---|
| Document | Stores self-contained documents (often JSON-like), grouped in collections | A product catalogue where products have different attributes |
| Key-value | Stores a value under a key, like a giant dictionary | Caching a session by its id |
| Wide-column | Rows with flexible sets of columns, grouped for huge scale | Very large event data (not covered further here) |
| Graph | Stores things and the relationships between them | Friends-of-friends in a social network |
You already know a key-value structure from the collections module: a Map. A document store is like a map of maps and lists, kept safely on disk and searchable.
MongoDB, a well-known document database, describes its data model as flexible: documents in one collection do not have to share the same fields or data types, and you can add new fields without rewriting old documents. If you need a fixed structure, it offers optional validation rules. The idea carries over: flexibility on write, with the application (or optional rules) deciding what must be present.
The same contact in both worlds
In a relational design, Sara and her two phones become rows in two tables:
contacts: (1, Sara), (2, Omar)
phones: (1, 0100), (1, 0111), (2, 0122) -- first value is the contact idIn a document design, Sara and her phones are one document:
{"name": "Sara", "phones": ["0100", "0111"]}Reading one contact with all its phones is a single step in the document version, because everything sits together. In the relational version it takes following a key between tables. On the other hand, if the same phone number or company must be shared by many contacts, the relational version stores it once, while a document version might copy it into many documents, and then every copy has to be updated.
"NoSQL is faster": why it is not true
Speed depends on the work and not on the family. A document database can be quick to read a whole document that was stored together. A relational database can be quick to answer a question that crosses many tables, because it was built for that. A key-value store can be very quick at "get this one key", and poor at "find all values containing X". The same database can be fast or slow depending on how data is organised, whether suitable indexes exist, how much data there is, and how many users are active.
So the honest statement is: some systems are faster for some workloads. The honest method is to measure on your own data and your own questions. Reasons that are better than "faster":
- Data shape: nested, varying documents suggest a document store; regular, linked records suggest relational.
- Consistency needs: money and stock counts need strong, enforced rules, which relational databases are well known for. (Many NoSQL systems also offer strong guarantees now, so check each product.)
- Scale pattern: huge volumes of simple key lookups may suit a key-value design.
- Team skill and tools: a database your team knows well is usually worth a lot.
A final note: the boundary is not sharp. PostgreSQL can store JSON values, and several NoSQL systems now support SQL-like queries. Treat "relational" and "nonrelational" as families with overlap.
Examples
Example 1: two tables and a key (simple)
The program below mimics the relational idea with two lists. The contacts rows hold an id and a name. The phones rows hold a contact id and a number. Following the key finds each contact's phones. It also builds the document version.
import java.util.*;
public class L03a {
public static void main(String[] args) {
List<String[]> contacts = List.of(new String[]{"1", "Sara"}, new String[]{"2", "Omar"});
List<String[]> phones = List.of(new String[]{"1", "0100"}, new String[]{"1", "0111"}, new String[]{"2", "0122"});
for (String[] c : contacts) {
System.out.print(c[1] + ":");
for (String[] p : phones) {
if (p[0].equals(c[0])) System.out.print(" " + p[1]); // follow the key
}
System.out.println();
}
Map<String, Object> doc = new LinkedHashMap<>();
doc.put("name", "Sara");
doc.put("phones", List.of("0100", "0111"));
System.out.println(doc);
}
}Output with JDK 21:
Sara: 0100 0111
Omar: 0122
{name=Sara, phones=[0100, 0111]}The loops are only a picture of the idea. A real DBMS does this with its own tools, quickly, and keeps data on disk. The Map at the end is the document shape: the phones live inside Sara's value.
Example 2: choosing for a product catalogue (practical)
An online shop sells laptops (RAM, screen size, battery), shirts (size, colour, fabric), and books (author, pages). A relational design has two reasonable ways: a wide products table with many empty columns, or a general table plus extra tables per product type. A document store lets each product hold only its own attributes:
{"name": "Laptop X", "ram_gb": 16, "screen_in": 14}
{"name": "Shirt Y", "size": "M", "colour": "blue"}The flexible attributes favour the document style. But the same shop also has orders, payments, and stock. These are regular, linked, and money-related, so rules and consistency matter. A realistic outcome is that the shop uses a relational database for orders and stock and may use a document or JSON-valued field for the catalogue. Choosing one family does not force the whole system into it.
Example 3: a measured comparison, not a slogan (realistic)
A team argues about which database to use for a service that stores user profiles and reads one profile by id millions of times a day. Instead of voting, they write down the work.
- Typical operations: "get profile by id" (very common), "update email" (rare), "list profiles created last week" (a few times a day).
- Data shape: a profile has the same ten fields for everyone.
- Rules: the email must be unique.
- Plan: load a realistic number of profiles into both candidates, run the three operations, and record times and effort.
The result depends on the product, hardware, and settings, so this lesson does not quote any number. What matters is the method: they compare on their operations. A relational database with an index on id is a strong baseline for this exact work, and the unique-email rule is native to it. If the measurements showed a key-value store was clearly better at the first operation, they would weigh that against losing the other two conveniences.
Backend Insight
Most backend teams start with a relational database because it fits most business data (users, orders, payments, bookings), enforces rules, and has a long track record. Later they may add a second store for a particular job, such as a key-value cache for sessions or a search engine. Using several stores in one system is common and is not a sign of confusion. It is a sign that different data has different needs.
When a design review says "let us use NoSQL because it scales", ask three questions: What data? What operations, in what numbers? What did we measure? If nobody can answer, the choice is a guess.
Common Mistakes
Mistake 1: "NoSQL is always faster"
- Incorrect: "We will use NoSQL because it is faster."
- Correct: "Our work is mostly reading whole documents by key, and in a test it was faster for that."
Mistake 2: "Relational databases cannot scale or cannot hold JSON"
Both claims are too simple. Relational systems run very large workloads, and PostgreSQL has JSON support. The honest limits depend on the product and the design.
Mistake 3: "NoSQL means no schema, no rules"
A flexible schema means the database demands less. Your program still needs to know what a valid document is. MongoDB itself offers optional validation for this.
Mistake 4: Treating the choice as all-or-nothing
Many systems use a relational database for core records and another store for caching or search.
Exercises
Level A: Foundation
A1. Describe a relational database in two sentences. Use the words table, row, column, and key.
أظهر الحل A1
A1. A relational database stores data in tables. Each table has columns (named and typed) and rows (records), and tables are linked by keys: a primary key identifies a row, and a foreign key refers to a row in another table.
A2. Match each to a style: (a) a social network of friends, (b) a cache that maps a session id to user data, (c) a catalogue of products with different attributes. Styles: document, key-value, graph.
أظهر الحل A2
A2. (a) Graph. (b) Key-value. (c) Document.
A3. What is the difference between a primary key and a foreign key?
أظهر الحل A3
A3. A primary key uniquely identifies a row in its own table. A foreign key is a column that holds another table's primary key value, linking rows across tables.
Level B: Application
B1. A school has students and courses, and each student can take many courses. Sketch the contact-style idea with tables and keys: which tables would you make, and which column would be a foreign key?
أظهر الحل B1
B1. Tables: students, courses, and a linking table enrolments with student_id and course_id, both foreign keys. (A linking table is needed because each student has many courses and each course many students.)
B2. Write one person who has two email addresses as a single JSON document, and then as rows in two tables (a people table and an emails table with a key).
أظهر الحل B2
B2. Document: {"name": "Hala", "emails": ["h@example.com", "hala@example.org"]}. Tables: people: (1, Hala) and emails: (1, h@example.com), (1, hala@example.org) where the first value is the person id.
B3. A teammate says NoSQL is faster, so you should switch. List three questions you would ask before deciding.
أظهر الحل B3
B3. For example: What data and operations do we have? What did we measure, with how much data? Do we need rules such as uniqueness and strong consistency? Can the team support it? Any three good questions work.
Level C: Challenge
C1. Name one situation where a document database would be a good choice and one where a relational database would be, and give the data-shape or rule reason for each (not speed).
أظهر الحل C1
C1. Document: varied product attributes, because each document holds only its own fields. Relational: bank transfers or orders, because the rules, links, and consistency between records matter. Other well-reasoned answers are fine.
C2. In a document design, a company name is copied into 5,000 contact documents. The company renames itself. What problem appears, and how does the relational "one fact, one place" habit avoid it?
أظهر الحل C2
C2. All 5,000 documents must be updated, and any that are missed show the old name. In the relational design the name is stored once in a companies table and contacts refer to it by key, so one update fixes everything.
Mini Challenge
Take a library app with books, members, and loans. Draw the relational design as three tables with columns and mark the primary and foreign keys. Then write one book as a JSON document with its loans embedded. Finish with two sentences: one question that is easy in each design, and one that is harder.
Check your work: keys are marked, the document and the tables hold the same facts, and your sentences talk about structure rather than "faster".
Summary & Next Lesson
Key takeaways
- Relational databases store data in tables of rows and columns, linked by primary and foreign keys, and queried with SQL.
- Nonrelational (NoSQL) databases use other shapes: document, key-value, wide-column, graph.
- The relational habit is one fact in one place; the document habit is to keep related data together.
- "NoSQL is faster" is not true in general: speed depends on the workload, so measure.
- The families overlap and are often combined in one system.
Next lesson
The next lesson, "DBMS and schemas", names the parts of a database system precisely: what a DBMS is, what a database is, and what a schema describes.
Self-check
- What is a foreign key for?
- Name two nonrelational styles.
- Is NoSQL always faster than relational? Why or why not?
- Give one reason for choosing a document database that is not speed.
- What does "one fact in one place" mean?
أظهر الإجابات
- It links a row to a row in another table by holding that row's primary key.
- For example document and key-value (or graph, wide-column).
- No. Speed depends on the data, the operations, the indexes, and the load, so it must be measured.
- For example: varying, nested records that fit a flexible document.
- Store each piece of information once and refer to it by key, so one update changes it everywhere.
References
- PostgreSQL documentation, Concepts (tutorial). Supports the description of a relational database as data stored in relations (tables) of rows, where each row in a table has the same named columns and each column has a data type.
- MongoDB documentation, Data Modeling Introduction. Supports the statement that documents in a collection need not share the same fields or types, that fields can be added without a schema migration, and that validation is optional.
- The statements about speed depending on workload, the four NoSQL styles, and the PostgreSQL JSON support are common knowledge not checked against a fetched page in this lesson; the speed claim is deliberately stated as "depends, so measure". The Java code was compiled and run with JDK 21.
التطبيق
طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.
تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.