Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Certified PostgreSQL Expert ยท Lesson 4 of 7

Intermediate SQL and Data Modeling

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
4
Module 3: Certified PostgreSQL Expert โ€“ Intermediate SQL and Data Modeling

๐Ÿ“˜ Module 3: Certified PostgreSQL Expert โ€” Intermediate SQL and Data Modeling

๐Ÿ”Ž Module Introduction

Welcome back, young data explorer! In Module 1, you learned what a database is. In Module 2, you learned how to install PostgreSQL, create databases, create tables, and run simple queries. You learned how to use INSERT, SELECT, UPDATE, and DELETE.

In this module, we are going to go deeper. We will learn intermediate SQL. This means we will learn how to do more powerful things with our data. We will learn about joins. Joins let us combine data from multiple tables. We will learn about subqueries. Subqueries are queries inside queries. We will learn about views. Views are saved queries. We will learn about functions. Functions are reusable pieces of code. We will learn about indexes. Indexes make queries faster. And we will learn about normalization. Normalization is a way to organise data efficiently.

Do not worry if some words sound big. We will explain everything in simple language. We will use stories, examples from Nigeria, examples from school, and examples from home. We will use pictures made from keyboard characters (ASCII art) to help you see what we mean. By the end of this module, you will know:

  • How to combine data from multiple tables using joins.
  • How to write subqueries.
  • How to create and use views.
  • How to create and use functions.
  • How to create indexes to speed up queries.
  • How to organise data using normalization.
  • How to design efficient database schemas.

This module is long because it is a complete chapter, not just short notes. Take your time. Read one lesson at a time. Do the exercises. Ask questions. Practice on your computer. Are you ready? Let us begin!

๐ŸŽฏ Learning Objectives

After finishing this module, you should be able to:

  1. Explain what a join is in your own simple words.
  2. Use INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN.
  3. Explain what a subquery is.
  4. Write subqueries in WHERE and FROM clauses.
  5. Create and use views.
  6. Create and use functions.
  7. Explain what an index is.
  8. Create indexes to make queries faster.
  9. Explain what normalization is.
  10. Apply the first three normal forms.
  11. Design a simple database schema.
  12. Understand primary keys and foreign keys.

๐Ÿ“– Warm-up Story: Ngozi and the Two Registers

Ngozi was a 13-year-old girl who lived in Ibadan, Nigeria. She helped her mother run a small shop. The shop sold provisions: rice, beans, oil, and soap.

Ngozi's mother kept two registers. The first register had a list of customers and their phone numbers. The second register had a list of sales: what was sold, how much it cost, and who bought it.

One day, Ngozi's mother asked, "Which customer bought the most rice last month?"

Ngozi looked at the two registers. She needed information from both. The sales register had the item. The customer register had the name and phone number. But she could not find the answer quickly. She had to flip back and forth between the two registers.

Ngozi remembered her PostgreSQL lessons. "Mummy," she said, "if we used a database, we could join the two tables. We could ask the database one question and get the answer in seconds."

Her mother was amazed. "Can you teach me?" she asked.

Ngozi smiled. "Yes! Let me show you how joins work."

Moral of the story: Joins let you combine data from multiple tables. They help you find answers quickly. Anyone can learn to use joins.

๐Ÿ“š Lesson 1: What Is a Join?

Definition

A join is an SQL command that combines data from two or more tables. It matches rows from one table with rows from another table.

Why It Is Important

Data is often stored in different tables. To get the full picture, you need to join the tables. Joins help you answer questions that use data from multiple tables.

Simple Explanation

Imagine you have two lists. One list has names and phone numbers. The other list has names and favourite foods. If you want to know Chika's phone number and favourite food, you need to join the two lists. A join is like putting the two lists side by side.

Real-Life Example

A bank has a customers table and an accounts table. A join can show you which customer owns which account.

School Example

A school has a students table and a scores table. A join can show you each student's name and their score.

Home Example

At home, you have a recipes table and an ingredients table. A join can show you each recipe and its ingredients.

Nigerian Example

In a Nigerian market, a trader has a customers table and a sales table. A join can show which customer bought which item.

Illustration (ASCII)

   TABLE 1: CUSTOMERS
   +----+----------+
   | ID | NAME     |
   +----+----------+
   | 1  | CHIKA    |
   | 2  | EMEKA    |
   +----+----------+

   TABLE 2: SALES
   +----+----------+----------+
   | ID | ITEM     | CUST_ID  |
   +----+----------+----------+
   | 1  | RICE     | 1        |
   | 2  | BEANS    | 2        |
   +----+----------+----------+

   JOIN:
   +----+----------+----------+
   | ID | NAME     | ITEM     |
   +----+----------+----------+
   | 1  | CHIKA    | RICE     |
   | 2  | EMEKA    | BEANS    |
   +----+----------+----------+
  

Mini Summary

A join combines data from two or more tables. It matches rows from one table with rows from another table.

Summary of Lesson 1

You learned what a join is. You saw examples from home, school, and Nigeria. Now you know that joins help you combine data.

๐Ÿ“š Lesson 2: INNER JOIN

Definition

An INNER JOIN returns only the rows that match in both tables. If a row in one table has no match in the other table, it is not included.

Why It Is Important

INNER JOIN is the most common type of join. It helps you find data that exists in both tables.

Simple Explanation

Imagine you have two lists. One list has students who play football. The other list has students who play music. An INNER JOIN shows only students who play both football and music.

Real-Life Example

A bank uses INNER JOIN to find customers who have both a savings account and a current account.

School Example

A school uses INNER JOIN to find students who are in both the science club and the math club.

Home Example

At home, you use INNER JOIN to find recipes that use both rice and beans.

Nigerian Example

In a Nigerian market, a trader uses INNER JOIN to find customers who bought both rice and beans.

SQL Command for INNER JOIN

   SELECT customers.name, sales.item
   FROM customers
   INNER JOIN sales ON customers.id = sales.cust_id;
  

Illustration (ASCII)

   INNER JOIN:
   TABLE 1 (CUSTOMERS)    TABLE 2 (SALES)
   +----+----------+      +----+----------+----------+
   | ID | NAME     |      | ID | ITEM     | CUST_ID  |
   +----+----------+      +----+----------+----------+
   | 1  | CHIKA    |      | 1  | RICE     | 1        |
   | 2  | EMEKA    |      | 2  | BEANS    | 2        |
   | 3  | NGOZI    |      | 3  | OIL      | 2        |
   +----+----------+      +----+----------+----------+

   INNER JOIN RESULT:
   +----------+----------+
   | NAME     | ITEM     |
   +----------+----------+
   | CHIKA    | RICE     |
   | EMEKA    | BEANS    |
   | EMEKA    | OIL      |
   +----------+----------+
   (NGOZI is not included because she has no sales)
  

Mini Summary

INNER JOIN returns only the rows that match in both tables. It is the most common type of join.

Summary of Lesson 2

You learned about INNER JOIN. You saw examples from home, school, and Nigeria. Now you can use INNER JOIN to find matching data.

๐Ÿ“š Lesson 3: LEFT JOIN and RIGHT JOIN

Definition

A LEFT JOIN returns all rows from the left table and matching rows from the right table. If there is no match, the right side shows NULL. A RIGHT JOIN returns all rows from the right table and matching rows from the left table.

Why It Is Important

LEFT JOIN and RIGHT JOIN help you find rows that do not have matches. They show you missing data.

Simple Explanation

Imagine you have a list of all students and a list of students who play football. A LEFT JOIN shows all students and their football status. Students who do not play football show NULL for football.

Real-Life Example

A bank uses LEFT JOIN to find customers who have no accounts.

School Example

A school uses LEFT JOIN to find students who have not taken any exams.

Home Example

At home, you use LEFT JOIN to find recipes that have no ingredients listed.

Nigerian Example

In a Nigerian market, a trader uses LEFT JOIN to find customers who have never bought anything.

SQL Command for LEFT JOIN

   SELECT customers.name, sales.item
   FROM customers
   LEFT JOIN sales ON customers.id = sales.cust_id;
  

Illustration (ASCII)

   LEFT JOIN:
   TABLE 1 (CUSTOMERS)    TABLE 2 (SALES)
   +----+----------+      +----+----------+----------+
   | ID | NAME     |      | ID | ITEM     | CUST_ID  |
   +----+----------+      +----+----------+----------+
   | 1  | CHIKA    |      | 1  | RICE     | 1        |
   | 2  | EMEKA    |      | 2  | BEANS    | 2        |
   | 3  | NGOZI    |      | 3  | OIL      | 2        |
   +----+----------+      +----+----------+----------+

   LEFT JOIN RESULT:
   +----------+----------+
   | NAME     | ITEM     |
   +----------+----------+
   | CHIKA    | RICE     |
   | EMEKA    | BEANS    |
   | EMEKA    | OIL      |
   | NGOZI    | NULL     |
   +----------+----------+
   (NGOZI is included with NULL because she has no sales)
  

Mini Summary

LEFT JOIN returns all rows from the left table and matching rows from the right table. RIGHT JOIN does the opposite.

Summary of Lesson 3

You learned about LEFT JOIN and RIGHT JOIN. You saw examples from home, school, and Nigeria. Now you can find rows that do not have matches.

๐Ÿ“š Lesson 4: FULL JOIN

Definition

A FULL JOIN returns all rows from both tables. If there is no match, NULL is shown for the missing side.

Why It Is Important

FULL JOIN helps you see everything. It shows you all data from both tables, even if there are no matches.

Simple Explanation

Imagine you have a list of all students and a list of all football players. A FULL JOIN shows all students and all football players. If a student is not a football player, the football column shows NULL. If a football player is not a student, the student column shows NULL.

Real-Life Example

A bank uses FULL JOIN to see all customers and all accounts, even if some customers have no accounts.

School Example

A school uses FULL JOIN to see all students and all exam scores, even if some students have no scores.

Home Example

At home, you use FULL JOIN to see all recipes and all ingredients, even if some recipes have no ingredients.

Nigerian Example

In a Nigerian market, a trader uses FULL JOIN to see all customers and all sales, even if some customers have no sales.

SQL Command for FULL JOIN

   SELECT customers.name, sales.item
   FROM customers
   FULL JOIN sales ON customers.id = sales.cust_id;
  

Illustration (ASCII)

   FULL JOIN:
   TABLE 1 (CUSTOMERS)    TABLE 2 (SALES)
   +----+----------+      +----+----------+----------+
   | ID | NAME     |      | ID | ITEM     | CUST_ID  |
   +----+----------+      +----+----------+----------+
   | 1  | CHIKA    |      | 1  | RICE     | 1        |
   | 2  | EMEKA    |      | 2  | BEANS    | 2        |
   | 3  | NGOZI    |      | 3  | OIL      | 2        |
   +----+----------+      +----+----------+----------+

   FULL JOIN RESULT:
   +----------+----------+
   | NAME     | ITEM     |
   +----------+----------+
   | CHIKA    | RICE     |
   | EMEKA    | BEANS    |
   | EMEKA    | OIL      |
   | NGOZI    | NULL     |
   +----------+----------+
   (all rows from both tables are included)
  

Mini Summary

FULL JOIN returns all rows from both tables. It shows NULL for missing matches.

Summary of Lesson 4

You learned about FULL JOIN. You saw examples from home, school, and Nigeria. Now you can see all data from both tables.

๐Ÿ“š Lesson 5: What Is a Subquery?

Definition

A subquery is a query inside another query. The inner query runs first. Its result is used by the outer query.

Why It Is Important

Subqueries help you solve complex problems. They let you use the result of one query in another query.

Simple Explanation

Imagine you want to find the student with the highest score. First, you find the highest score. Then, you find the student with that score. A subquery is like doing two steps in one command.

Real-Life Example

A bank uses a subquery to find customers who have more money than the average balance.

School Example

A school uses a subquery to find students who scored higher than the class average.

Home Example

At home, you use a subquery to find recipes that take longer than the average cooking time.

Nigerian Example

In a Nigerian market, a trader uses a subquery to find goods that are more expensive than the average price.

SQL Command for Subquery

   SELECT name, score
   FROM students
   WHERE score > (SELECT AVG(score) FROM students);
  

Illustration (ASCII)

   SUBQUERY:
   OUTER QUERY: SELECT name, score FROM students WHERE score > ?
         |
         V
   INNER QUERY: SELECT AVG(score) FROM students
         |
         V
   RESULT: 82.5
         |
         V
   OUTER QUERY RUNS WITH RESULT: SELECT name, score FROM students WHERE score > 82.5
         |
         V
   FINAL RESULT: STUDENTS WITH SCORE > 82.5
  

Mini Summary

A subquery is a query inside another query. The inner query runs first, and its result is used by the outer query.

Summary of Lesson 5

You learned what a subquery is. You saw examples from home, school, and Nigeria. Now you can use subqueries to solve complex problems.

๐Ÿ“š Lesson 6: Subqueries in WHERE and FROM

Definition

You can use subqueries in different parts of a query. You can use them in the WHERE clause. You can use them in the FROM clause.

Why It Is Important

Subqueries in WHERE help you filter data. Subqueries in FROM help you create temporary tables.

Simple Explanation

Imagine you want to find students who scored higher than the class average. You use a subquery in the WHERE clause. Imagine you want to create a temporary table of high scorers. You use a subquery in the FROM clause.

Real-Life Example

A bank uses a subquery in WHERE to find customers with above-average balances.

School Example

A school uses a subquery in FROM to create a list of top students.

Home Example

At home, you use a subquery in WHERE to find recipes with above-average ratings.

Nigerian Example

In a Nigerian market, a trader uses a subquery in FROM to create a list of best-selling goods.

SQL Commands for Subqueries

   -- Subquery in WHERE
   SELECT name, score
   FROM students
   WHERE score > (SELECT AVG(score) FROM students);

   -- Subquery in FROM
   SELECT *
   FROM (SELECT name, score FROM students WHERE score > 80) AS top_students;
  

Illustration (ASCII)

   SUBQUERY IN WHERE:
   SELECT name, score FROM students WHERE score > (SELECT AVG(score) FROM students);

   SUBQUERY IN FROM:
   SELECT * FROM (SELECT name, score FROM students WHERE score > 80) AS top_students;
  

Mini Summary

Subqueries can be used in WHERE and FROM clauses. They help you filter data and create temporary tables.

Summary of Lesson 6

You learned how to use subqueries in WHERE and FROM. You saw examples from home, school, and Nigeria. Now you can use subqueries in different parts of your query.

๐Ÿ“š Lesson 7: What Is a View?

Definition

A view is a saved query. It looks like a table, but it does not store data. It runs the query every time you use it.

Why It Is Important

Views make complex queries easy to reuse. You can save a query as a view and use it again and again.

Simple Explanation

Imagine you have a long recipe. You write it down once. Then you can use it many times. A view is like that. You write a query once. You save it as a view. You can use the view many times.

Real-Life Example

A bank creates a view of all customers with high balances. The bank can use the view every day.

School Example

A school creates a view of all students with high scores. The school can use the view every term.

Home Example

At home, you create a view of all quick recipes. You can use the view when you are in a hurry.

Nigerian Example

In a Nigerian market, a trader creates a view of all best-selling goods. The trader can use the view every week.

SQL Command for View

   CREATE VIEW top_students AS
   SELECT name, score
   FROM students
   WHERE score > 80;

   -- Use the view
   SELECT * FROM top_students;
  

Illustration (ASCII)

   VIEW:
   [ QUERY: SELECT name, score FROM students WHERE score > 80 ]
         |
         V
   [ SAVE AS VIEW: top_students ]
         |
         V
   [ USE VIEW: SELECT * FROM top_students ]
         |
         V
   [ RESULTS SHOWN ]
  

Mini Summary

A view is a saved query. It looks like a table but does not store data. You can use it many times.

Summary of Lesson 7

You learned what a view is. You saw examples from home, school, and Nigeria. Now you can create and use views.

๐Ÿ“š Lesson 8: What Is a Function?

Definition

A function is a reusable piece of code. You write it once. You can use it many times. Functions can take inputs and return outputs.

Why It Is Important

Functions save time. They make code cleaner. They help you avoid writing the same code again and again.

Simple Explanation

Imagine you have a recipe for jollof rice. You write it down once. You can use it many times. A function is like that recipe. You write it once. You use it many times.

Real-Life Example

A bank creates a function to calculate interest. The bank uses the function for all accounts.

School Example

A school creates a function to calculate grades. The school uses the function for all students.

Home Example

At home, you create a function to convert measurements. You use the function for all your recipes.

Nigerian Example

In a Nigerian market, a trader creates a function to calculate discounts. The trader uses the function for all customers.

SQL Command for Function

   CREATE FUNCTION add_numbers(a INTEGER, b INTEGER)
   RETURNS INTEGER AS $$
   BEGIN
       RETURN a + b;
   END;
   $$ LANGUAGE plpgsql;

   -- Use the function
   SELECT add_numbers(5, 3);
  

Illustration (ASCII)

   FUNCTION:
   [ CREATE FUNCTION add_numbers(a, b) ]
         |
         V
   [ SAVE THE FUNCTION ]
         |
         V
   [ USE FUNCTION: SELECT add_numbers(5, 3) ]
         |
         V
   [ RESULT: 8 ]
  

Mini Summary

A function is a reusable piece of code. You write it once and use it many times.

Summary of Lesson 8

You learned what a function is. You saw examples from home, school, and Nigeria. Now you can create and use functions.

๐Ÿ“š Lesson 9: What Is an Index?

Definition

An index is a special data structure that makes queries faster. It works like the index at the back of a book. Instead of searching every page, you look at the index to find the page number.

Why It Is Important

Without an index, PostgreSQL must search every row in a table. With an index, PostgreSQL can find data much faster.

Simple Explanation

Imagine you have a big book. You want to find a topic. Without an index, you must read every page. With an index, you find the page number quickly. An index in a database is like the index in a book.

Real-Life Example

A bank creates an index on customer account numbers. The bank can find any account in seconds.

School Example

A school creates an index on student names. The school can find any student quickly.

Home Example

At home, you create an index on recipe names. You can find any recipe quickly.

Nigerian Example

In a Nigerian market, a trader creates an index on item names. The trader can find any item quickly.

SQL Command for Index

   CREATE INDEX idx_customer_name ON customers (name);

   -- Now queries on customer name are faster
   SELECT * FROM customers WHERE name = 'Chika';
  

Illustration (ASCII)

   WITHOUT INDEX:
   [ SEARCH EVERY ROW ] --> [ SLOW ]

   WITH INDEX:
   [ LOOK UP IN INDEX ] --> [ FIND ROW ] --> [ FAST ]
  

Mini Summary

An index makes queries faster. It works like the index at the back of a book.

Summary of Lesson 9

You learned what an index is. You saw examples from home, school, and Nigeria. Now you can create indexes to speed up your queries.

๐Ÿ“š Lesson 10: What Is Normalization?

Definition

Normalization is a way to organise data in a database. It reduces duplication. It makes data easier to maintain. It follows a set of rules called normal forms.

Why It Is Important

Without normalization, data can be duplicated. This wastes space and causes errors. Normalization keeps data clean and accurate.

Simple Explanation

Imagine you have a list of students and their classes. If a student takes three classes, their name appears three times. If you need to change the student's name, you must change it in three places. Normalization separates the data into two tables: students and classes. This avoids duplication.

Real-Life Example

A bank normalizes its data. Customers are in one table. Accounts are in another table.

School Example

A school normalizes its data. Students are in one table. Scores are in another table.

Home Example

At home, you normalize your recipes. Recipes are in one table. Ingredients are in another table.

Nigerian Example

In a Nigerian market, a trader normalizes data. Customers are in one table. Sales are in another table.

Illustration (ASCII)

   WITHOUT NORMALIZATION:
   +----+----------+----------+
   | ID | NAME     | CLASS    |
   +----+----------+----------+
   | 1  | CHIKA    | MATH     |
   | 2  | CHIKA    | ENGLISH  |
   | 3  | CHIKA    | SCIENCE  |
   +----+----------+----------+
   (name is duplicated)

   WITH NORMALIZATION:
   TABLE 1: STUDENTS
   +----+----------+
   | ID | NAME     |
   +----+----------+
   | 1  | CHIKA    |
   +----+----------+

   TABLE 2: CLASSES
   +----+----------+----------+
   | ID | STUDENT  | CLASS    |
   +----+----------+----------+
   | 1  | 1        | MATH     |
   | 2  | 1        | ENGLISH  |
   | 3  | 1        | SCIENCE  |
   +----+----------+----------+
   (no duplication)
  

Mini Summary

Normalization organises data to reduce duplication. It keeps data clean and accurate.

Summary of Lesson 10

You learned what normalization is. You saw examples from home, school, and Nigeria. Now you know how to organise data efficiently.

๐Ÿ“š Lesson 11: The First Three Normal Forms

Definition

There are several normal forms. The most common are the first three: 1NF, 2NF, and 3NF.

Why It Is Important

Following normal forms keeps your data clean. It stops duplication. It stops errors.

Simple Explanation

1NF: Each column has one value. No lists in a column. 2NF: Every column depends on the primary key. 3NF: No column depends on another non-key column.

Real-Life Example

A bank normalizes its data. Customer names are in one table. Account balances are in another table.

School Example

A school normalizes its data. Student names are in one table. Scores are in another table.

Home Example

At home, you normalize your recipes. Recipe names are in one table. Ingredients are in another table.

Nigerian Example

In a Nigerian market, a trader normalizes data. Customer names are in one table. Sales are in another table.

Normal Forms Table

Normal Form Rule Example
1NF Each column has one value No "Math, English" in one cell
2NF Every column depends on the primary key No partial dependencies
3NF No column depends on another non-key column No transitive dependencies

Illustration (ASCII)

   NORMAL FORMS:
   [ 1NF ] --> [ ONE VALUE PER COLUMN ]
         |
         V
   [ 2NF ] --> [ EVERY COLUMN DEPENDS ON PRIMARY KEY ]
         |
         V
   [ 3NF ] --> [ NO COLUMN DEPENDS ON NON-KEY COLUMN ]
  

Mini Summary

1NF, 2NF, and 3NF are the first three normal forms. They keep data clean and accurate.

Summary of Lesson 11

You learned about the first three normal forms. You saw a table of rules. Now you can normalize your data.

๐Ÿ“š Lesson 12: Primary Keys and Foreign Keys

Definition

A primary key is a unique column that identifies each row. A foreign key is a column that links to a primary key in another table.

Why It Is Important

Primary keys stop duplication. Foreign keys create relationships between tables. They keep data accurate.

Simple Explanation

Imagine a school. Each student has a unique student number. That is a primary key. Each student belongs to a class. The class has a unique class number. The student table has a column for class number. That column is a foreign key.

Real-Life Example

A bank has a customers table and an accounts table. The customers table has a primary key (customer ID). The accounts table has a foreign key (customer ID).

School Example

A school has a students table and a scores table. The students table has a primary key (student ID). The scores table has a foreign key (student ID).

Home Example

At home, you have a recipes table and an ingredients table. The recipes table has a primary key (recipe ID). The ingredients table has a foreign key (recipe ID).

Nigerian Example

In a Nigerian market, a trader has a customers table and a sales table. The customers table has a primary key (customer ID). The sales table has a foreign key (customer ID).

SQL Command for Foreign Key

   CREATE TABLE sales (
       id SERIAL PRIMARY KEY,
       item VARCHAR(50),
       price NUMERIC(10, 2),
       cust_id INTEGER REFERENCES customers(id)
   );
  

Illustration (ASCII)

   PRIMARY KEY AND FOREIGN KEY:
   TABLE 1: CUSTOMERS
   +----+----------+
   | ID | NAME     |   <-- ID is primary key
   +----+----------+
   | 1  | CHIKA    |
   | 2  | EMEKA    |
   +----+----------+

   TABLE 2: SALES
   +----+----------+----------+
   | ID | ITEM     | CUST_ID  |   <-- CUST_ID is foreign key
   +----+----------+----------+
   | 1  | RICE     | 1        |
   | 2  | BEANS    | 2        |
   +----+----------+----------+
  

Mini Summary

A primary key uniquely identifies each row. A foreign key links to a primary key in another table.

Summary of Lesson 12

You learned about primary keys and foreign keys. You saw examples from home, school, and Nigeria. Now you can create relationships between tables.

๐Ÿ“š Lesson 13: Designing a Database Schema

Definition

A schema is the design of a database. It shows the tables, their columns, and the relationships between them.

Why It Is Important

A good schema makes a database efficient. A bad schema causes problems later.

Simple Explanation

Imagine you are building a house. You need a plan. The plan shows the rooms and doors. A database schema is like that plan.

Real-Life Example

A bank designs a schema with a customers table, an accounts table, and a transactions table.

School Example

A school designs a schema with a students table, a teachers table, and a scores table.

Home Example

At home, you design a schema with a recipes table and an ingredients table.

Nigerian Example

In a Nigerian market, a trader designs a schema with a customers table and a sales table.

Illustration (ASCII)

   SCHEMA DESIGN:
   [ CUSTOMERS ] <-- [ SALES ]
         |                |
         V                V
   (customer_id)    (cust_id)
         |                |
         +----[ LINK ]----+
         |
         V
   [ PRODUCTS ]
         |
         V
   (product_id)
  

Mini Summary

A schema is the design of a database. It shows tables, columns, and relationships.

Summary of Lesson 13

You learned how to design a database schema. You saw examples from home, school, and Nigeria. Now you can design your own schema.

๐Ÿ“š Lesson 14: Putting It All Together

Definition

Putting it all together means using joins, subqueries, views, functions, indexes, and normalization to build a complete database.

Why It Is Important

A complete database solves real problems. It helps you store, find, and protect data.

Simple Explanation

Imagine you are building a car. You need an engine, wheels, and a steering wheel. Putting it all together means assembling all the parts. In the same way, you assemble all your SQL skills to build a complete database.

Real-Life Example

A bank builds a complete database with customers, accounts, and transactions.

School Example

A school builds a complete database with students, teachers, and scores.

Home Example

At home, you build a complete database with recipes and ingredients.

Nigerian Example

In a Nigerian market, a trader builds a complete database with customers and sales.

Illustration (ASCII)

   COMPLETE DATABASE:
   [ TABLES ] --> [ JOINS ] --> [ SUBQUERIES ]
         |              |               |
         V              V               V
   [ VIEWS ] --> [ FUNCTIONS ] --> [ INDEXES ]
         |              |               |
         V              V               V
   [ NORMALIZATION ] --> [ SCHEMA DESIGN ]
         |
         V
   [ COMPLETE DATABASE! ๐ŸŽ‰ ]
  

Mini Summary

Putting it all together means using all your SQL skills to build a complete database.

Summary of Lesson 14

You learned how to put everything together. You saw examples from home, school, and Nigeria. Now you can build a complete database.

๐Ÿ“š Lesson 15: Best Practices for Intermediate SQL

Definition

Best practices are the best ways to do things. They help you write clean, efficient, and correct SQL.

Why It Is Important

Following best practices makes your code easier to read. It makes your queries faster. It reduces errors.

Simple Explanation

Imagine you are writing a letter. You use neat handwriting. You use correct spelling. Best practices in SQL are like neat handwriting and correct spelling.

Real-Life Example

A bank follows best practices. Queries are fast and accurate.

School Example

A school follows best practices. Data is clean and organised.

Home Example

At home, you follow best practices. Your recipes are easy to find.

Nigerian Example

In a Nigerian market, a trader follows best practices. Sales records are accurate.

Best Practices List

  1. Use meaningful table and column names.
  2. Always use a primary key.
  3. Use foreign keys to link tables.
  4. Normalize your data.
  5. Create indexes on columns you search often.
  6. Use views for complex queries.
  7. Use functions for reusable code.
  8. Write comments in your SQL.
  9. Test your queries before using them.
  10. Back up your data regularly.

Illustration (ASCII)

   BEST PRACTICES:
   [ MEANINGFUL NAMES ] --> [ PRIMARY KEYS ]
         |                          |
         V                          V
   [ FOREIGN KEYS ] --> [ NORMALIZATION ]
         |                          |
         V                          V
   [ INDEXES ] --> [ VIEWS ] --> [ FUNCTIONS ]
         |                          |
         V                          V
   [ TEST QUERIES ] --> [ BACK UP DATA ]
         |
         V
   [ CLEAN, FAST, ACCURATE DATABASE ]
  

Mini Summary

Best practices help you write clean, efficient, and correct SQL.

Summary of Lesson 15

You learned best practices for intermediate SQL. You saw a list of practices. Now you can write better SQL.

๐Ÿ“– Key Vocabulary

Word Simple Definition
Join An SQL command that combines data from two or more tables.
INNER JOIN Returns only rows that match in both tables.
LEFT JOIN Returns all rows from the left table and matching rows from the right table.
RIGHT JOIN Returns all rows from the right table and matching rows from the left table.
FULL JOIN Returns all rows from both tables.
Subquery A query inside another query.
View A saved query that looks like a table.
Function A reusable piece of code.
Index A data structure that makes queries faster.
Normalization Organising data to reduce duplication.
Primary key A unique column that identifies each row.
Foreign key A column that links to a primary key in another table.
Schema The design of a database.

๐Ÿง  Important Concepts

  • Joins combine data from multiple tables. INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN are common types.
  • INNER JOIN returns only matching rows.
  • LEFT JOIN returns all rows from the left table. RIGHT JOIN returns all rows from the right table.
  • FULL JOIN returns all rows from both tables.
  • Subqueries are queries inside queries. They can be used in WHERE and FROM clauses.
  • Views are saved queries. They make complex queries easy to reuse.
  • Functions are reusable pieces of code. They save time and reduce errors.
  • Indexes make queries faster. They work like the index in a book.
  • Normalization organises data. It reduces duplication and errors.
  • Primary keys uniquely identify rows. Foreign keys link tables.
  • A schema is the design of a database.
  • Best practices make your SQL clean, fast, and accurate.

๐Ÿ“ Step-by-Step Explanations

How to Use INNER JOIN (Step by Step)

  1. Identify the two tables you want to join.
  2. Find the column that links them. Usually a primary key and a foreign key.
  3. Write: SELECT columns FROM table1 INNER JOIN table2 ON table1.key = table2.key;
  4. Run the query.
  5. PostgreSQL returns only rows that match in both tables.

How to Create a View (Step by Step)

  1. Write a SELECT query that you want to save.
  2. Add CREATE VIEW view_name AS before the query.
  3. Run the command.
  4. PostgreSQL saves the view.
  5. Use the view by selecting from it: SELECT * FROM view_name;

How to Create an Index (Step by Step)

  1. Identify the column you search often.
  2. Write: CREATE INDEX index_name ON table_name (column_name);
  3. Run the command.
  4. PostgreSQL creates the index.
  5. Queries on that column become faster.

๐ŸŒ Real-Life Examples

  • A bank uses joins to find customers and their accounts.
  • A school uses joins to find students and their scores.
  • A hospital uses joins to find patients and their treatments.
  • A market uses joins to find customers and their purchases.
  • A library uses joins to find books and their borrowers.
  • A government uses joins to find citizens and their records.
  • A supermarket uses joins to find products and their sales.
  • A family uses joins to find recipes and their ingredients.

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • In Lagos, a bank uses joins to find customers and their accounts.
  • In Abuja, a government office uses joins to find citizens and their records.
  • In Enugu, a school uses joins to find students and their scores.
  • In Kano, a market trader uses joins to find customers and their purchases.
  • In Port Harcourt, a hospital uses joins to find patients and their treatments.
  • In Ibadan, a family uses joins to find recipes and their ingredients.
  • In Jos, a library uses joins to find books and their borrowers.
  • In Nigeria, many companies use PostgreSQL for its powerful join capabilities.

๐Ÿ˜„ Fun Examples Children Can Relate To

  • Imagine a join is like putting two puzzles together. The pieces fit to make a bigger picture.
  • Think of a subquery as a question inside a question. "What is the highest score? Who got it?"
  • Pretend a view is a saved game. You can come back to it later.
  • Imagine a function is a magic spell. You say it once, and it works many times.
  • Think of an index as a book's table of contents. It helps you find things fast.
  • Imagine normalization is like organising your toys into different boxes. No mixing!

๐Ÿ  Everyday Examples

  • You combine your school timetable with your friend's timetable to find a free period. That is a join.
  • You ask: "What is the average score in my class?" That is a subquery.
  • You save a search on your phone. That is like a view.
  • You use a calculator app. That is like a function.
  • You use the index at the back of a textbook. That is like a database index.
  • You organise your clothes into different drawers. That is like normalization.

๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ Parent Tips

  • Help your children practice joins with simple examples.
  • Show your children how to create views and functions.
  • Explain the importance of indexes and normalization.
  • Encourage your children to design their own database schemas.
  • Practice creating tables with primary and foreign keys.
  • Help your children test their queries.
  • Celebrate when your child creates a complete database.
  • Support your child if they want to learn more about SQL.

๐Ÿค“ Interesting Facts

  • Joins are one of the most powerful features of SQL.
  • Subqueries can be nested many levels deep.
  • Views do not store data. They run the query every time.
  • Functions can be written in many languages, including SQL and PL/pgSQL.
  • Indexes can make queries thousands of times faster.
  • Normalization was invented by Edgar F. Codd in the 1970s.
  • Primary keys and foreign keys are the foundation of relational databases.
  • PostgreSQL supports many types of joins and subqueries.

โ“ Did You Know?

  • Did you know that a join can combine data from more than two tables?
  • Did you know that a subquery can be used in SELECT, FROM, and WHERE clauses?
  • Did you know that a view can be used like a table?
  • Did you know that a function can return a table?
  • Did you know that an index can slow down INSERT and UPDATE?
  • Did you know that normalization has five normal forms?
  • Did you know that a foreign key can prevent invalid data?
  • Did you know that a schema can have many tables?

๐Ÿ” Remember This

  • Joins combine data from multiple tables.
  • INNER JOIN returns only matching rows.
  • LEFT JOIN returns all rows from the left table.
  • RIGHT JOIN returns all rows from the right table.
  • FULL JOIN returns all rows from both tables.
  • Subqueries are queries inside queries.
  • Views are saved queries.
  • Functions are reusable pieces of code.
  • Indexes make queries faster.
  • Normalization organises data.
  • Primary keys uniquely identify rows.
  • Foreign keys link tables.
  • A schema is the design of a database.
  • Best practices make your SQL clean, fast, and accurate.

โš ๏ธ Common Mistakes

  1. Forgetting the ON clause in a join.
  2. Using the wrong join type.
  3. Forgetting to use aliases for tables.
  4. Writing subqueries that return multiple rows when one is expected.
  5. Creating views that are too complex.
  6. Creating functions that are too long.
  7. Creating too many indexes. They can slow down INSERT and UPDATE.
  8. Not normalizing data. This causes duplication.
  9. Forgetting to use primary keys.
  10. Forgetting to use foreign keys.

โœ… Best Practices

  • Use meaningful table and column names.
  • Always use a primary key.
  • Use foreign keys to link tables.
  • Normalize your data.
  • Create indexes on columns you search often.
  • Use views for complex queries.
  • Use functions for reusable code.
  • Write comments in your SQL.
  • Test your queries before using them.
  • Back up your data regularly.

๐Ÿ–ผ๏ธ More ASCII Illustrations, Diagrams, Flowcharts, and Tables

Flowchart: Types of Joins

   JOIN
     |
     +---- INNER JOIN (only matching rows)
     |
     +---- LEFT JOIN (all left rows + matching right rows)
     |
     +---- RIGHT JOIN (all right rows + matching left rows)
     |
     +---- FULL JOIN (all rows from both tables)
  

Timeline: Learning Intermediate SQL

   Step 1: Learn what a join is.
   Step 2: Learn INNER JOIN.
   Step 3: Learn LEFT JOIN and RIGHT JOIN.
   Step 4: Learn FULL JOIN.
   Step 5: Learn what a subquery is.
   Step 6: Learn subqueries in WHERE and FROM.
   Step 7: Learn what a view is.
   Step 8: Learn what a function is.
   Step 9: Learn what an index is.
   Step 10: Learn what normalization is.
   Step 11: Learn the first three normal forms.
   Step 12: Learn primary keys and foreign keys.
   Step 13: Learn how to design a schema.
   Step 14: Put it all together.
   Step 15: Learn best practices.
  

Diagram: How a Join Works

   TABLE 1: CUSTOMERS
   +----+----------+
   | ID | NAME     |
   +----+----------+
   | 1  | CHIKA    |
   | 2  | EMEKA    |
   +----+----------+

   TABLE 2: SALES
   +----+----------+----------+
   | ID | ITEM     | CUST_ID  |
   +----+----------+----------+
   | 1  | RICE     | 1        |
   | 2  | BEANS    | 2        |
   +----+----------+----------+

   JOIN ON CUSTOMERS.ID = SALES.CUST_ID
   +----------+----------+
   | NAME     | ITEM     |
   +----------+----------+
   | CHIKA    | RICE     |
   | EMEKA    | BEANS    |
   +----------+----------+
  

Table: Types of Joins

Join Type What It Returns When to Use
INNER JOIN Only matching rows When you need data that exists in both tables
LEFT JOIN All rows from left table + matching rows from right When you need all data from the left table
RIGHT JOIN All rows from right table + matching rows from left When you need all data from the right table
FULL JOIN All rows from both tables When you need all data from both tables

Comparison Table: PostgreSQL vs Other Databases

Feature PostgreSQL MySQL SQLite
Cost Free Free Free
Power Very powerful Powerful Simple
Best for Large apps Websites Small apps
Security Very strong Strong Basic
Users Many at once Many at once One at a time

๐Ÿ“Œ End-of-Module Summary

In this module, you learned intermediate SQL and data modeling. You learned about joins. Joins combine data from multiple tables. You learned about INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN.

You learned about subqueries. Subqueries are queries inside queries. You learned how to use subqueries in WHERE and FROM clauses.

You learned about views. Views are saved queries. They look like tables but do not store data. You learned about functions. Functions are reusable pieces of code. You learned about indexes. Indexes make queries faster. They work like the index in a book.

You learned about normalization. Normalization organises data to reduce duplication. You learned about the first three normal forms: 1NF, 2NF, and 3NF. You learned about primary keys and foreign keys. Primary keys uniquely identify rows. Foreign keys link tables. You learned how to design a database schema.

You learned how to put it all together. You learned best practices for intermediate SQL. Now you are ready to move on to Module 4, where you will learn about performance tuning and optimization. But before you go, make sure you understand the key takeaways below.

โ“ Frequently Asked Questions

  1. What is a join?
    A join is an SQL command that combines data from two or more tables.
  2. What is the difference between INNER JOIN and LEFT JOIN?
    INNER JOIN returns only matching rows. LEFT JOIN returns all rows from the left table and matching rows from the right table.
  3. What is a subquery?
    A subquery is a query inside another query.
  4. What is a view?
    A view is a saved query that looks like a table.
  5. What is a function?
    A function is a reusable piece of code.
  6. What is an index?
    An index is a data structure that makes queries faster.
  7. What is normalization?
    Normalization is organising data to reduce duplication.
  8. What is a primary key?
    A primary key is a unique column that identifies each row.
  9. What is a foreign key?
    A foreign key is a column that links to a primary key in another table.
  10. What is a schema?
    A schema is the design of a database.

โœ๏ธ Matching Exercises

Match the word in Column A with the correct definition in Column B.

Column A Column B
1. Join A. A saved query that looks like a table
2. Subquery B. Organising data to reduce duplication
3. View C. An SQL command that combines data from two or more tables
4. Function D. A unique column that identifies each row
5. Index E. A query inside another query
6. Normalization F. A reusable piece of code
7. Primary key G. A data structure that makes queries faster

Answers: 1-C, 2-E, 3-A, 4-F, 5-G, 6-B, 7-D

๐ŸŽญ Scenario-Based Exercises

  1. Scenario: You want to find students and their scores. Which join do you use?
    Answer: You use INNER JOIN.
  2. Scenario: You want to find all students, even those without scores. Which join do you use?
    Answer: You use LEFT JOIN.
  3. Scenario: You want to find students who scored higher than the average. What do you use?
    Answer: You use a subquery.
  4. Scenario: You want to save a complex query for reuse. What do you use?
    Answer: You use a view.
  5. Scenario: You want to speed up a query. What do you use?
    Answer: You use an index.
  6. Scenario: You want to reduce duplication in your data. What do you use?
    Answer: You use normalization.

๐Ÿ‘ฅ Group Activity

Title: Design a School Database
Instructions: In groups of 3 or 4, design a database for your school. List the tables you need. Choose primary keys. Choose foreign keys. Normalize your data. Present your design to the class.

Example:
Tables: students, teachers, classes, scores.
Primary keys: student_id, teacher_id, class_id, score_id.
Foreign keys: class_id in students, student_id in scores.
Normalized: Yes.

๐Ÿง‘ Individual Activity

Title: My First Join
Instructions: Create two tables. Add data. Write a join to combine them. Write down what you did and what you learned.

Example:
Table 1: students (id, name)
Table 2: scores (id, student_id, score)
Join: SELECT students.name, scores.score FROM students INNER JOIN scores ON students.id = scores.student_id;

๐Ÿ› ๏ธ Mini Project

Title: Build a Shop Database with Joins
Materials: Computer with PostgreSQL installed.
Steps:

  1. Create a database called "myshop".
  2. Create a table for customers.
  3. Create a table for sales.
  4. Add data to both tables.
  5. Write a join to find customers and their purchases.
  6. Write a subquery to find customers who spent more than average.
  7. Create a view of top customers.
  8. Create an index on customer names.
  9. Normalize your data.
  10. Show your database to your class or family.

๐Ÿ“‹ Practical Assignment

Assignment: For one week, practice using joins, subqueries, views, functions, and indexes. Keep a diary. Each day, write down:

  • What join or query you used.
  • What data you found.
  • What you learned.
  • What you will do differently next time.

At the end of the week, write a short report. Share it with your teacher or parent.

๐Ÿ”‘ Key Takeaways

  • Joins combine data from multiple tables.
  • INNER JOIN returns only matching rows.
  • LEFT JOIN returns all rows from the left table.
  • RIGHT JOIN returns all rows from the right table.
  • FULL JOIN returns all rows from both tables.
  • Subqueries are queries inside queries.
  • Views are saved queries.
  • Functions are reusable pieces of code.
  • Indexes make queries faster.
  • Normalization organises data.
  • Primary keys uniquely identify rows.
  • Foreign keys link tables.
  • A schema is the design of a database.
  • Best practices make your SQL clean, fast, and accurate.

๐Ÿ’ฌ Classroom Discussion Questions

  1. What is a join? Give an example.
  2. What is the difference between INNER JOIN and LEFT JOIN?
  3. What is a subquery? How is it used?
  4. What is a view? Why is it useful?
  5. What is a function? How does it save time?
  6. What is an index? How does it make queries faster?
  7. What is normalization? Why is it important?
  8. What are the first three normal forms?
  9. What is a primary key?
  10. What is a foreign key?
  11. What is a schema? How do you design one?
  12. How do you put all these skills together?
  13. What are the best practices for intermediate SQL?
  14. How can you use joins to solve real problems?

โžก๏ธ Preparation for Module 4

In Module 4, you will learn about performance tuning and optimization. You will learn about:

  • Query planning and EXPLAIN ANALYZE.
  • Index optimization.
  • Vacuuming and maintenance.
  • Connection pooling.
  • Monitoring tools.
  • Best practices for high-performance databases.

Before you start Module 4, make sure you understand everything in this module. Practice joins. Create views and functions. Create indexes. Normalize your data. Design a schema. When you are ready, turn the page and continue your journey to becoming a Certified PostgreSQL Expert!

End of Module 3.

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (โ‚ฆ2,000 or 20,000 coins), and get a verified certificate with your name on it.

๐ŸŽ“ Sign Up to Get Certified
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
โ†’