mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-28 18:26:54 +00:00
feat(curriculum): working with rdbs lectures (#61450)
Co-authored-by: Hillary Nyakundi <63947040+larymak@users.noreply.github.com> Co-authored-by: Dario <105294544+Dario-DC@users.noreply.github.com>
This commit is contained in:
@@ -4526,7 +4526,12 @@
|
||||
"title": "Bash Commands Quiz",
|
||||
"intro": ["Test what you've learned bash commands with this quiz."]
|
||||
},
|
||||
"voks": { "title": "306", "intro": [] },
|
||||
"lecture-working-with-relational-databases": {
|
||||
"title": "Working with Relational Databases",
|
||||
"intro": [
|
||||
"Learn how to work with Relational Databases in these lectures."
|
||||
]
|
||||
},
|
||||
"workshop-database-of-video-game-characters": {
|
||||
"title": "Build a Database of Video Game Characters",
|
||||
"intro": [
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
---
|
||||
title: Introduction to Working with Relational Databases
|
||||
block: lecture-working-with-relational-databases
|
||||
superBlock: full-stack-developer
|
||||
---
|
||||
|
||||
## Introduction to Working with Relational Databases
|
||||
|
||||
Learn about Working with Relational Databases in these lectures.
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "Working with Relational Databases",
|
||||
"blockType": "lecture",
|
||||
"blockLayout": "challenge-list",
|
||||
"isUpcomingChange": true,
|
||||
"dashedName": "lecture-working-with-relational-databases",
|
||||
"superBlock": "full-stack-developer",
|
||||
"helpCategory": "Backend Development",
|
||||
"challengeOrder": [
|
||||
{
|
||||
"id": "687ea6c021dd5913cf8fd8dd",
|
||||
"title": "What Are Relational Databases, and How Do They Differ from Non-Relational Databases?"
|
||||
},
|
||||
{
|
||||
"id": "687ea86615674e19296a78ce",
|
||||
"title": "What Are Some Common Relational Databases, and How Do You Install and Use Postgres?"
|
||||
},
|
||||
{
|
||||
"id": "687ea8757080091969f07122",
|
||||
"title": "What Is SQL, and How Can You Create a Database with Tables?"
|
||||
},
|
||||
{
|
||||
"id": "687ea899461e37199cf03cf9",
|
||||
"title": "What Are the Basic Data Types in SQL?"
|
||||
},
|
||||
{
|
||||
"id": "687ea8a88c9e9419af7cd8c3",
|
||||
"title": "How Do You Insert and View Data in a Table?"
|
||||
},
|
||||
{
|
||||
"id": "687ea8bb2b781b19c790d00e",
|
||||
"title": "What Are Primary and Foreign Keys in SQL, and How Do They Work?"
|
||||
},
|
||||
{
|
||||
"id": "687ea8e0cab41019dc8a728a",
|
||||
"title": "What Are the Different Types of Relationships in a Relational Database?"
|
||||
},
|
||||
{
|
||||
"id": "687ea8eba2a8b119f2ad9f8c",
|
||||
"title": "What Are the Different Ways to Join Tables?"
|
||||
}
|
||||
]
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
---
|
||||
id: 687ea6c021dd5913cf8fd8dd
|
||||
title: What Are Relational Databases, and How Do They Differ from Non-Relational Databases?
|
||||
challengeType: 19
|
||||
dashedName: what-are-relational-databases-and-how-do-they-differ-from-non-relational-databases
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A relational database is a collection of data organized into tables. These tables are made of rows and columns.
|
||||
|
||||
Rows represent individual records. For example, if you're storing user data, each row could represent a specific user.
|
||||
|
||||
Columns represent the attributes or fields that describe each record. The table might include columns for common user attributes, such as name and national ID number.
|
||||
|
||||
One of the key characteristics of relational databases is that they allow us to connect different pieces of information by linking tables through common attributes, making it easier to see how they relate to each other.
|
||||
|
||||
Relational databases require a schema. The schema defines the overall structure of the database, including its tables, columns, data types, relationships, and constraints.
|
||||
|
||||
All tables in a relational database have a primary key, which is a unique identifier for each row. They enable relationships between tables via foreign keys. You'll learn more about primary keys, foreign keys, and how they work in the coming lectures. For now, just know they are fundamental to linking records across tables.
|
||||
|
||||
For example, let's say that you're creating a database for an organization that runs a wildlife conservation center for critically endangered animals.
|
||||
|
||||
One of the tables could store general information about the animals, you might call it `animals`. Each row could represent an animal, while each column could represent an attribute of that animal, like species, size, weight, age, and other unique characteristics.
|
||||
|
||||
To uniquely identify each animal, you would typically add an `id` column to the table. This would be the primary key of the table because it's unique for each animal. The ID of each animal could be used to link its record in this table to related records in other tables.
|
||||
|
||||
You could also have a `species` table to store information about each species, such as their habitat and conservation status. Each animal in the `animals` table could reference a species from this table using a species ID.
|
||||
|
||||
You could also create a table to store the veterinary records of the animals. This way, the center can track their health, treatments, and medications.
|
||||
|
||||
Once you have this general schema, you could link these tables to the `animals` table, which acts as the central point for animal-related data.
|
||||
|
||||
This way, you don't have to keep all the information about an animal in the same table. Instead, you can store related data in separate tables and link them through relationships. By creating these relationships, you can get the specific data you need with a single query.
|
||||
|
||||
A query is a request for specific data from the database. Examples of queries that you could make in the context of our example would be finding all animals that need a veterinary checkup, finding the most critically endangered species in the center, finding the number of animals who were born in captivity, and more. You can customize the queries to fit your needs.
|
||||
|
||||
Our example was related to wildlife conservation, but relational databases have a wide range of applications across industries such as healthcare, construction, business, gaming, education, government, e-commerce, social media, and more.
|
||||
|
||||
They offer several advantages, including scalability. They can handle large datasets, so they're perfect for complex, real-world applications. They also enforce data integrity through primary keys, foreign keys, and data types, which ensures that the data will be consistent and accurate.
|
||||
|
||||
In addition to relational databases, you can work with non-relational databases.
|
||||
|
||||
The main difference between relational and non-relational databases is how the data is stored. Non-relational databases, also known as NoSQL databases, are more flexible. They store data in individual files that are not connected. Their data model is more flexible too.
|
||||
|
||||
While some non-relational databases may have a basic schema or data model, it is often less rigid than the schema defined in relational databases. You can add, modify, or remove data fields if necessary.
|
||||
|
||||
The decision to use a relational or non-relational database depends on various factors, including the nature of the data and the specific requirements of the application. You should evaluate the tradeoffs between these two approaches to choose the best one for your application.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
|
||||
Which of the following is a key characteristic of relational databases?
|
||||
|
||||
## --answers--
|
||||
|
||||
Flexible schema
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about how data is organized in relational databases.
|
||||
|
||||
---
|
||||
|
||||
Document-based structure
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about how data is organized in relational databases.
|
||||
|
||||
---
|
||||
|
||||
Key-value pairs
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about how data is organized in relational databases.
|
||||
|
||||
---
|
||||
|
||||
Structured data in tables
|
||||
|
||||
## --video-solution--
|
||||
|
||||
4
|
||||
|
||||
## --text--
|
||||
|
||||
Which of the following statements is true about relational databases?
|
||||
|
||||
## --answers--
|
||||
|
||||
They are always more scalable than non-relational databases.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the structure and characteristics of relational databases.
|
||||
|
||||
---
|
||||
|
||||
They are always more performant than non-relational databases.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the structure and characteristics of relational databases.
|
||||
|
||||
---
|
||||
|
||||
They require a predefined schema.
|
||||
|
||||
---
|
||||
|
||||
They are not suitable for large-scale applications.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the structure and characteristics of relational databases.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
3
|
||||
|
||||
## --text--
|
||||
|
||||
Which of the following statements is true about non-relational databases?
|
||||
|
||||
## --answers--
|
||||
|
||||
They always have a fixed schema.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the key differences between relational and non-relational databases.
|
||||
|
||||
---
|
||||
|
||||
They are not suitable for large-scale applications.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the key differences between relational and non-relational databases.
|
||||
|
||||
---
|
||||
|
||||
They allow for more flexible data modeling.
|
||||
|
||||
---
|
||||
|
||||
They are always slower than relational databases.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the key differences between relational and non-relational databases.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
3
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
---
|
||||
id: 687ea86615674e19296a78ce
|
||||
title: What Are Some Common Relational Databases, and How Do You Install and Use Postgres?
|
||||
challengeType: 19
|
||||
dashedName: what-are-some-common-relational-databases-and-how-do-you-install-and-use-postres
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Relational databases have a wide range of applications, including web development, inventory management systems, healthcare systems, e-commerce applications, and more.
|
||||
|
||||
Some of the most common relational databases are MySQL, PostgreSQL, SQLite, and Microsoft SQL Server. Let's learn a little bit about each one of them.
|
||||
|
||||
MySQL is an open-source relational database management system. It's very popular for web development because it's easy to use, reliable, and efficient for building real-world applications. It also has an active community of developers that support and maintain it.
|
||||
|
||||
PostgreSQL is officially described as "The World's Most Advanced Open Source Relational Database." It's a free, open source object-relational database system known for its reliability, data integrity, and extensibility. For example, you can define your own data types, custom functions, and write code in different programming languages without re-compiling your database.
|
||||
|
||||
SQLite is a free, open source, and lightweight file-based SQL database engine. It's one of the most widely used database engines in the world. SQLite is self-contained and serverless. It's a zero-configuration database, which means that it doesn't require an initial setup process, which is great for getting started quickly.
|
||||
|
||||
These three databases are free and open source. There are other popular proprietary options too, including Microsoft SQL Server and Oracle database.
|
||||
|
||||
Microsoft SQL server is a popular relational database management system developed by Microsoft and used in various applications.
|
||||
|
||||
Oracle database is a scalable relational database management system often used for enterprise applications that require high performance.
|
||||
|
||||
Great. Now that you know more about the different options available, let's see how you can install PostgreSQL.
|
||||
|
||||
First, you need to go to the official website: <a href="https://www.postgresql.org/" target="_blank">https://www.postgresql.org/</a>.
|
||||
|
||||
Once you're there, click on the "Download" button.
|
||||
|
||||
This will take you to a page where you can select your operating system. If you click on one, you will be taken to the instructions for that OS.
|
||||
|
||||
We will go through the installation process for the Windows operating system, but the process is similar across operating systems.
|
||||
|
||||
From this page, you can download the installer by clicking on the "Download the installer" link.
|
||||
|
||||
This will take you to a page where you can choose the version of PostgreSQL you want to install. If you click on the corresponding icon, the download should start.
|
||||
|
||||
Then, in your Downloads folder or the folder where you store your downloads by default, you should see the installer.
|
||||
|
||||
If you double-click on it, you will start the setup process. Click Next.
|
||||
|
||||
Choose the directory where PostgreSQL will be installed. You'll see one by default but you can customize it.
|
||||
|
||||
Then, select the component that you want to install. There are four possible components:
|
||||
|
||||
- PostgreSQL Server, the database engine itself.
|
||||
- pgAdmin 4, a user-friendly tool for database management.
|
||||
- Stack Builder, a tool for downloading and installing additional PostgreSQL-related software and extensions
|
||||
- And Command Line Tools, to interact with the PostgreSQL server directly from your terminal. This includes psql, an interactive terminal for executing SQL queries.
|
||||
|
||||
When you're ready, click Next.
|
||||
|
||||
Then, select a directory to store your data. You will see a default path but you can customize this. When you're ready, click Next.
|
||||
|
||||
Now you'll need to enter a password for the database superuser, the user with unrestricted access to all databases and objects. Type in your password, retype it, and then click Next.
|
||||
|
||||
Then, select the port number the server should listen on. By default, it's 5432. Then, click Next.
|
||||
|
||||
You'll need to choose a locale for the new database cluster. This is important for the database to interpret locale-sensitive data types. Then, click Next.
|
||||
|
||||
Finally, you'll see a pre-installation summary. Take a moment to review this and click Next.
|
||||
|
||||
You will need to confirm that you want to start the installation process. If you click Next, the process will start. It should only take a few minutes.
|
||||
|
||||
When the process is completed, based on the components that you installed, you may have to choose if you want to launch Stack Builder to download and install additional tools, drivers, and applications.
|
||||
|
||||
If you decide to launch Stack Builder, you'll see a screen where you can start the installation. Alternatively, you can click Cancel to do this later on.
|
||||
|
||||
Congratulations! Now you have PostgreSQL installed on your computer. The process should be similar for other operating systems. After this, you can start using the database.
|
||||
|
||||
Go to your apps and search for pgAdmin, an open source administration and development platform for PostgreSQL that should have been installed if you selected it in the components. Click on pgAdmin 4 to open it.
|
||||
|
||||
You'll see an initial loading screen when the application starts. Then, you should see a dashboard where you can start a new server, check your databases, configure pgAdmin, and more. You'll also find helpful links to the documentation.
|
||||
|
||||
If you click on "Servers" at the top left, you will need to enter the password that you chose during the installation.
|
||||
|
||||
After entering your password, you should see a screen where you will have access to your databases, including their tables.
|
||||
|
||||
You'll also find another very helpful tool, psql, an interactive terminal for SQL queries. To open it, search for psql on your system. Click on it.
|
||||
|
||||
It will open the SQL Shell, where you can start running commands.
|
||||
|
||||
And that's how you can install PostgreSQL on Windows. The process is very similar for macOS and Linux.
|
||||
|
||||
Alternatively, if you are installing it on macOS, you can use Homebrew, a package manager. Once you have Homebrew installed, run this command to install PostgreSQL:
|
||||
|
||||
```bash
|
||||
brew install postgresql@<version>
|
||||
```
|
||||
|
||||
You can specify the version that you want to install by writing the number after the at (`@`) symbol.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
|
||||
Which of the following is NOT a common relational database?
|
||||
|
||||
## --answers--
|
||||
|
||||
MySQL
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the popular relational databases you learned about during the lecture.
|
||||
|
||||
---
|
||||
|
||||
Node
|
||||
|
||||
---
|
||||
|
||||
PostgreSQL
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the popular relational databases you learned about during the lecture.
|
||||
|
||||
---
|
||||
|
||||
SQLite
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the popular relational databases you learned about during the lecture.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
2
|
||||
|
||||
## --text--
|
||||
|
||||
PostgreSQL is known for its:
|
||||
|
||||
## --answers--
|
||||
|
||||
Weak SQL support and limited features.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about PostgreSQL's reputation regarding standards and customization.
|
||||
|
||||
---
|
||||
|
||||
Strong SQL support and powerful features.
|
||||
|
||||
---
|
||||
|
||||
Exclusive use in small systems.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about PostgreSQL's reputation regarding standards and customization.
|
||||
|
||||
---
|
||||
|
||||
Small developer community.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about PostgreSQL's reputation regarding standards and customization.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
2
|
||||
|
||||
## --text--
|
||||
|
||||
Which of the following is an open source, lightweight, file-based relational database?
|
||||
|
||||
## --answers--
|
||||
|
||||
Microsoft SQL Server
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which option is known for its simplicity.
|
||||
|
||||
---
|
||||
|
||||
PostgreSQL
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which option is known for its simplicity.
|
||||
|
||||
---
|
||||
|
||||
SQLite
|
||||
|
||||
---
|
||||
|
||||
MySQL
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which option is known for its simplicity.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
3
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
---
|
||||
id: 687ea8757080091969f07122
|
||||
title: What Is SQL, and How Can You Create a Database with Tables?
|
||||
challengeType: 19
|
||||
dashedName: what-is-sql-and-how-can-you-create-a-database-with-tables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
SQL stands for Structured Query Language. It was developed in the 1970s, when it was initially known as the structured English query language (SEQUEL). This term was later shortened to SQL.
|
||||
|
||||
SQL is a programming language used for storing and managing data in relational databases.
|
||||
|
||||
Like you learned in a previous lecture, relational databases organize data into tables. Each table has a set of rows and columns, where the data attributes and their relationships are represented. Each row represents a record while each column represents a specific attribute or field of that record.
|
||||
|
||||
With SQL, you can add, change, delete, find, and retrieve data from a relational database. It provides a comprehensive set of commands for querying, filtering, sorting, and aggregating data.
|
||||
|
||||
SQL can help optimize database performance, by querying only the necessary data, and it can be easily integrated with a wide range of programming languages, so you can use it to interact with databases directly from your applications.
|
||||
|
||||
It has been also adopted as an industry standard. It enforces data integrity and includes many security features, like support for user authentication and data encryption.
|
||||
|
||||
It's also scalable, portable, and compatible with a wide range of database management systems.
|
||||
|
||||
SQL is based on commands, commonly known as SQL statements or SQL queries.
|
||||
|
||||
As a developer, you will write these statements using specific SQL language elements or keywords. They allow you to perform the necessary operations on your database.
|
||||
|
||||
Before you can enter SQL commands, you need to open the psql shell so you can directly interact with the PostgreSQL database. In the command prompt or terminal, enter:
|
||||
|
||||
```bash
|
||||
psql -U <username> -d <database_name>
|
||||
```
|
||||
|
||||
Replace `username` with your username and `database_name` with the database you want to connect to. If you haven't created own your database yet, use `postgres`, it comes with the installation.
|
||||
|
||||
Once connected, you will see the prompt change to:
|
||||
|
||||
```bash
|
||||
postgres=#
|
||||
```
|
||||
|
||||
It shows the database name you are connected to and waits for SQL commands.
|
||||
|
||||
Let's go over some of the most fundamental SQL commands that you should be familiar with. You'll notice that, by convention, SQL commands end with a semicolon (`;`).
|
||||
|
||||
First, you can use this command to create a database named `my_database`:
|
||||
|
||||
```sql
|
||||
CREATE DATABASE my_database;
|
||||
```
|
||||
|
||||
You can type `CREATE` followed by `DATABASE`, and the name of the database that you want to create. Notice that the SQL keywords of the command are written in capital letters.
|
||||
|
||||
Then, once you have your database, you can connect to it.
|
||||
|
||||
How you connect to the database really depends on the environment and tool you're using.
|
||||
|
||||
In the command prompt or terminal, you can use the method shown earlier. In the interactive psql shell, you can switch databases with the `\c` shortcut command followed by the database name like this:
|
||||
|
||||
```bash
|
||||
\c my_database
|
||||
```
|
||||
|
||||
Note that the `\c` command and other shortcut commands (ones with a backslash in front of them) are part of the psql shell and not part of the SQL language itself, so they do not require a semi-colon to complete the command.
|
||||
|
||||
Now that you've connected to your new database, you will see the prompt has changed:
|
||||
|
||||
```bash
|
||||
my_database=#
|
||||
```
|
||||
|
||||
Once you have created and connected to a database, you can create a table with the `CREATE TABLE` keywords:
|
||||
|
||||
```sql
|
||||
CREATE TABLE products (
|
||||
id SERIAL,
|
||||
name VARCHAR(255)
|
||||
);
|
||||
```
|
||||
|
||||
In the command, you write `CREATE TABLE`, followed by the name of the table that you want to create. In this case, it will create a table named `products`.
|
||||
|
||||
Then, within parentheses, you write the names of the columns that the table should have and specify the data type of the values that will be stored in each column.
|
||||
|
||||
In the example, the table will have two columns, a column for the product ID and another one for the name of the product.
|
||||
|
||||
The standard naming convention for table and column names is snake case, writing words in lowercase and separating them with an underscore (`_`). For example: `delivery_orders`
|
||||
|
||||
These are few essential SQL commands you should know to get started.
|
||||
|
||||
With SQL, you can easily query, manipulate, and analyze data to make informed decisions and solve real-world problems.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
|
||||
What does the acronym SQL stand for?
|
||||
|
||||
## --answers--
|
||||
|
||||
Structured Query Language
|
||||
|
||||
---
|
||||
|
||||
Simple Query Language
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the purpose of SQL and the words in the acronym that describe its functionality.
|
||||
|
||||
---
|
||||
|
||||
Sequential Query Language
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the purpose of SQL and the words in the acronym that describe its functionality.
|
||||
|
||||
---
|
||||
|
||||
Standard Query Language
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the purpose of SQL and the words in the acronym that describe its functionality.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
1
|
||||
|
||||
## --text--
|
||||
|
||||
What is SQL primarily used for?
|
||||
|
||||
## --answers--
|
||||
|
||||
Creating web pages.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about how SQL interacts with data.
|
||||
|
||||
---
|
||||
|
||||
Developing mobile applications.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about how SQL interacts with data.
|
||||
|
||||
---
|
||||
|
||||
Managing relational databases.
|
||||
|
||||
---
|
||||
|
||||
Writing server-side scripts.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about how SQL interacts with data.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
3
|
||||
|
||||
## --text--
|
||||
|
||||
What is a relational database?
|
||||
|
||||
## --answers--
|
||||
|
||||
A collection of unstructured data.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about how data is organized in a relational database.
|
||||
|
||||
---
|
||||
|
||||
A database that stores data in tables.
|
||||
|
||||
---
|
||||
|
||||
A programming language.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about how data is organized in a relational database.
|
||||
|
||||
---
|
||||
|
||||
A type of network.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about how data is organized in a relational database.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
2
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
---
|
||||
id: 687ea899461e37199cf03cf9
|
||||
title: What Are the Basic Data Types in SQL?
|
||||
challengeType: 19
|
||||
dashedName: what-are-the-basic-data-types-in-sql
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
To define a table in SQL, you need to specify the data type of each column.
|
||||
|
||||
Remember that this is the basic syntax for creating a table in SQL. Each column has its own data type.
|
||||
|
||||
```sql
|
||||
CREATE TABLE table_name(
|
||||
column1 data_type column_constraint,
|
||||
column2 data_type column_constraint,
|
||||
column3 data_type column_constraint,
|
||||
... etc
|
||||
);
|
||||
```
|
||||
|
||||
As a developer, your goal is to choose these data types as accurately as possible.
|
||||
|
||||
There are six popular categories of data types in SQL:
|
||||
|
||||
- Numeric, such as `INTEGER`, `FLOAT`, `SERIAL`, and `DECIMAL`.
|
||||
- Date and time, such as `TIMESTAMP`, `DATE`, and `TIME`.
|
||||
- Character and string. These include `CHAR`, `VARCHAR`, and `TEXT`.
|
||||
- Unicode, including `NTEXT`, and `NVARCHAR`. These are used to make sure that text will be stored and retrieved correctly, regardless of the characters' origin.
|
||||
- Binary, used to store non-textual data, like images, audio, and video files.
|
||||
- And other miscellaneous data types, such as `XML` and `TABLE`.
|
||||
|
||||
In this lecture, we'll cover some of the most widely used ones with PostgreSQL. Data types will vary across database management systems, but they are generally pretty similar. So you'll need to check the full list in the documentation.
|
||||
|
||||
We'll start with numeric values.
|
||||
|
||||
First, we have the `INTEGER` data type:
|
||||
|
||||
```sql
|
||||
units_sold INTEGER
|
||||
```
|
||||
|
||||
In this example, we assign this data type to a `units_sold` column.
|
||||
|
||||
`INTEGER` types consume 4 bytes in the database and can range in value from -2,147,483,648 to 2,147,483,647. The official PostgreSQL documentation describes it as the "typical choice for integer."
|
||||
|
||||
We also have `SMALLINT` and `BIGINT`, which are basically the same as `INTEGER` except have a smaller and bigger range of numbers, respectively, due to how much size they are allotted in the database.
|
||||
|
||||
A useful feature available in PostgreSQL is to create a column using the `SERIAL` keyword. Here, an `id` column is created using `SERIAL`:
|
||||
|
||||
```sql
|
||||
id SERIAL
|
||||
```
|
||||
|
||||
While it's not a true data type, it's very helpful for creating unique identifier columns because the column will have an `INTEGER` type, will not allow `NULL` values, and automatically increment when rows are added.
|
||||
|
||||
For example, the first row will automatically have an `id` of `1`, the second row will have an `id` of `2`, and so on, creating a unique ID for each record.
|
||||
|
||||
In MySQL, the equivalent of `SERIAL` would be the `AUTO_INCREMENT` attribute, used to generate sequential integers automatically:
|
||||
|
||||
```sql
|
||||
id INT AUTO_INCREMENT
|
||||
```
|
||||
|
||||
You can see that different database management systems may have different ways of achieving exactly the same functionality in your database.
|
||||
|
||||
These are the most commonly used numeric data types, but sometimes, you may need to represent text or sequences of characters.
|
||||
|
||||
For this, you have the `VARCHAR` data type. This data type is used for a variable string length. You can set the maximum character length within parentheses:
|
||||
|
||||
```sql
|
||||
name VARCHAR(50)
|
||||
```
|
||||
|
||||
In this example, we define a `name` column, where the values can be up to 50 characters long.
|
||||
|
||||
This data type sets a maximum length for the strings, but if you need to store strings of any length, you can use `TEXT` instead:
|
||||
|
||||
```sql
|
||||
name TEXT
|
||||
```
|
||||
|
||||
In addition to numbers and strings, it's also common to store dates and times.
|
||||
|
||||
For example, if you create a table to store events, you may need to store the date of each event in a specific format. For this, you have the `DATE` data type:
|
||||
|
||||
```sql
|
||||
event_date DATE
|
||||
```
|
||||
|
||||
To store time, you can also use the `TIME` data type. For example, you may store the time when an event starts:
|
||||
|
||||
```sql
|
||||
start_time TIME
|
||||
```
|
||||
|
||||
The `TIMESTAMP` data type combines both of them. It includes both the date and time. It may also include the time zone if you write `TIMESTAMP WITH TIME ZONE`:
|
||||
|
||||
```sql
|
||||
event_timestamp TIMESTAMP
|
||||
```
|
||||
|
||||
```sql
|
||||
event_timestamp TIMESTAMP WITH TIME ZONE
|
||||
```
|
||||
|
||||
And finally, if you need to store a boolean value, `TRUE` or `FALSE`, you can use the `BOOLEAN` data type:
|
||||
|
||||
```sql
|
||||
is_active BOOLEAN
|
||||
```
|
||||
|
||||
Now you know some of the most common data types in SQL, but there are many more. You can check the documentation of your database management system to find more information about the data types that you can use.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
|
||||
Which data type is used to store whole numbers in PostgreSQL?
|
||||
|
||||
## --answers--
|
||||
|
||||
`VARCHAR`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which option represents a numerical value without decimal points.
|
||||
|
||||
---
|
||||
|
||||
`TEXT`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which option represents a numerical value without decimal points.
|
||||
|
||||
---
|
||||
|
||||
`INTEGER`
|
||||
|
||||
---
|
||||
|
||||
`BOOLEAN`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which option represents a numerical value without decimal points.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
3
|
||||
|
||||
## --text--
|
||||
|
||||
If you need to store a long text document or a very long string, which data type should you use in PostgreSQL?
|
||||
|
||||
## --answers--
|
||||
|
||||
`VARCHAR(255)`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which option is designed to store character strings of unlimited or very large lengths.
|
||||
|
||||
---
|
||||
|
||||
`INTEGER`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which option is designed to store character strings of unlimited or very large lengths.
|
||||
|
||||
---
|
||||
|
||||
`CHAR(100)`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which option is designed to store character strings of unlimited or very large lengths.
|
||||
|
||||
---
|
||||
|
||||
`TEXT`
|
||||
|
||||
## --video-solution--
|
||||
|
||||
4
|
||||
|
||||
## --text--
|
||||
|
||||
Which data type would you use to store a `TRUE` or `FALSE` value in a PostgreSQL database?
|
||||
|
||||
## --answers--
|
||||
|
||||
`INTEGER`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the data type that represents a logical state.
|
||||
|
||||
---
|
||||
|
||||
`VARCHAR`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the data type that represents a logical state.
|
||||
|
||||
---
|
||||
|
||||
`BOOLEAN`
|
||||
|
||||
---
|
||||
|
||||
`TEXT`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the data type that represents a logical state.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
3
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
---
|
||||
id: 687ea8a88c9e9419af7cd8c3
|
||||
title: How Do You Insert and View Data in a Table?
|
||||
challengeType: 19
|
||||
dashedName: how-do-you-insert-and-view-data-in-a-table
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Let's see some of the fundamental commands that you can use to insert and view data in SQL.
|
||||
|
||||
First of all, to view data, you need to insert it. So we'll start with insertions.
|
||||
|
||||
The examples that we will cover in this lecture will be based on this table of dog records:
|
||||
|
||||
```sql
|
||||
CREATE TABLE dogs(
|
||||
id SERIAL,
|
||||
name VARCHAR(100),
|
||||
age INTEGER
|
||||
);
|
||||
```
|
||||
|
||||
The table will store the names and ages of various dogs.
|
||||
|
||||
If we assume that we are working with PostgreSQL, we can use the `SERIAL` data type for the `id`. Since `id` was created using `SERIAL`, its value will be an `INTEGER`, starting from `1`, and incremented automatically when a new record is inserted. So you will not need to pass a value for it when you insert a record.
|
||||
|
||||
Let's start by inserting records to our `dogs` table with the `INSERT INTO` statement. There are many ways to do this. The first one would be inserting a single row and specifying the columns of the values that will be inserted.
|
||||
|
||||
You write `INSERT INTO`, followed by the name of the table (in this case, `dogs`), then the columns within parentheses, then `VALUES`, and their corresponding values within parentheses.
|
||||
|
||||
This is an example, we're inserting a dog record with the `name` of `'Gino'`, whose `age` is `3`, remember that the `id` will be assigned automatically:
|
||||
|
||||
```sql
|
||||
INSERT INTO dogs (name, age)
|
||||
VALUES ('Gino', 3);
|
||||
```
|
||||
|
||||
This is usually the safest option because you specify the columns explicitly, so the values will be assigned to those columns in order.
|
||||
|
||||
Notice that `'Gino'` needs to be in single quotes because it is a `VARCHAR` type.
|
||||
|
||||
Another alternative is to insert the record without specifying the columns, like this:
|
||||
|
||||
```sql
|
||||
INSERT INTO dogs
|
||||
VALUES ('Gino', 3);
|
||||
```
|
||||
|
||||
This is valid too, but it's more prone to errors because the values are assigned to the columns based on their order.
|
||||
|
||||
You can also insert multiple records in the same SQL command by separating them with a comma.
|
||||
|
||||
Here, we are inserting two dog records, one for `'Gino'` and another one for `'Nora'`.
|
||||
|
||||
```sql
|
||||
INSERT INTO dogs (name, age)
|
||||
VALUES
|
||||
('Gino', 3),
|
||||
('Nora', 2);
|
||||
```
|
||||
|
||||
And just like you can insert records, you can query information from the database. In the context of databases, a query is a request for data.
|
||||
|
||||
In SQL, the `SELECT` statement is used for querying data from one or more tables. You can customize the query to get the exact information that you need.
|
||||
|
||||
If you need to query all the information from the `dogs` table, you just need to write `SELECT`, followed by an asterisk (`*`), then `FROM`, and the name of the table, `dogs`:
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM dogs;
|
||||
```
|
||||
|
||||
In this command, the asterisk is a wildcard character that represents "all columns."
|
||||
|
||||
You will get all the data of all the records in the table:
|
||||
|
||||
```sql
|
||||
id | name | age
|
||||
----+------+-----
|
||||
1 | Gino | 3
|
||||
2 | Nora | 2
|
||||
```
|
||||
|
||||
To query specific columns, you can write the names of those columns in the command, right after `SELECT`, separated by a comma. In this example, we query the `name` and `age` columns of the `dogs` table:
|
||||
|
||||
```sql
|
||||
SELECT name, age
|
||||
FROM dogs;
|
||||
```
|
||||
|
||||
The result will only include the `name` and `age` columns:
|
||||
|
||||
```sql
|
||||
name | age
|
||||
------+-----
|
||||
Gino | 3
|
||||
Nora | 2
|
||||
```
|
||||
|
||||
Sometimes, you might need to query data based on a specific condition. For example, to get all dogs who are less than 3 years old you can use the `WHERE` keyword and the less than (`<`) comparison operator:
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM dogs
|
||||
WHERE age < 3;
|
||||
```
|
||||
|
||||
The result will only include dogs whose age is less than 3:
|
||||
|
||||
```sql
|
||||
id | name | age
|
||||
----+------+-----
|
||||
2 | Nora | 2
|
||||
```
|
||||
|
||||
If you are just trying to find the `age` of `'Gino'`, you can you can use the equals (`=`) comparison operator:
|
||||
|
||||
```sql
|
||||
SELECT age
|
||||
FROM dogs
|
||||
WHERE name = 'Gino';
|
||||
```
|
||||
|
||||
And here's the result:
|
||||
|
||||
```sql
|
||||
age
|
||||
-----
|
||||
3
|
||||
```
|
||||
|
||||
These are common and simple ways to insert and view data in SQL, but there are many different options that you can choose from and some of them are more advanced. You'll learn about them in coming lectures.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
|
||||
What does the asterisk (`*`) represent in the SQL statement `SELECT * FROM products;`?
|
||||
|
||||
## --answers--
|
||||
|
||||
It selects the last column from the `products` table.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about what you would need to write explicitly if you didn't use the asterisk.
|
||||
|
||||
---
|
||||
|
||||
It indicates that there is an error in the SQL query.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about what you would need to write explicitly if you didn't use the asterisk.
|
||||
|
||||
---
|
||||
|
||||
It selects all columns from the `products` table.
|
||||
|
||||
---
|
||||
|
||||
It selects all rows where a column contains the asterisk character.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about what you would need to write explicitly if you didn't use the asterisk.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
3
|
||||
|
||||
## --text--
|
||||
|
||||
Which SQL command is used to add a new record to a table named `products`?
|
||||
|
||||
## --answers--
|
||||
|
||||
`SELECT name, price FROM products;`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the basic actions you perform on data. Which SQL keyword corresponds to adding something new?
|
||||
|
||||
---
|
||||
|
||||
`INSERT INTO products (name, price) VALUES ('New Product', 4.5);`
|
||||
|
||||
---
|
||||
|
||||
`UPDATE products SET name = 'New Product' WHERE price = 4.5;`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the basic actions you perform on data. Which SQL keyword corresponds to adding something new?
|
||||
|
||||
---
|
||||
|
||||
`CREATE TABLE products (name VARCHAR(100), price DECIMAL);`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the basic actions you perform on data. Which SQL keyword corresponds to adding something new?
|
||||
|
||||
## --video-solution--
|
||||
|
||||
2
|
||||
|
||||
## --text--
|
||||
|
||||
Given the following query:
|
||||
|
||||
```bash
|
||||
SELECT price FROM products WHERE category = 'Laptops';
|
||||
```
|
||||
|
||||
What is the main purpose of the `WHERE category = 'Laptops'` clause?
|
||||
|
||||
## --answers--
|
||||
|
||||
To specify that only the price column should be displayed.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the effect that this part of the query will have on which rows are included in the final result.
|
||||
|
||||
---
|
||||
|
||||
To sort the resulting list of products based on their category.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the effect that this part of the query will have on which rows are included in the final result.
|
||||
|
||||
---
|
||||
|
||||
To filter the rows, returning only the products whose category is `'Laptops'`.
|
||||
|
||||
---
|
||||
|
||||
To update the category of all products to `'Laptops'`.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about the effect that this part of the query will have on which rows are included in the final result.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
3
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
---
|
||||
id: 687ea8bb2b781b19c790d00e
|
||||
title: What Are Primary and Foreign Keys in SQL, and How Do They Work?
|
||||
challengeType: 19
|
||||
dashedName: what-are-primary-and-foreign-keys-in-sql-and-how-do-they-work
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In SQL, primary keys and foreign keys are used to establish relationships between tables.
|
||||
|
||||
Let's start with primary keys.
|
||||
|
||||
A primary key is a column or set of columns that uniquely identifies each record (row) in a table. This constraint ensures that no records in the table will have the same value for the primary key.
|
||||
|
||||
This is why a table can only have one primary key.
|
||||
|
||||
Values in the primary key column can't be `NULL` either, so they will always have a valid value.
|
||||
|
||||
In PostgreSQL, to make a column the primary key of your table, you just need to add `PRIMARY KEY` after the data type:
|
||||
|
||||
```sql
|
||||
column_name data_type PRIMARY KEY
|
||||
```
|
||||
|
||||
This is an example of a `students` table:
|
||||
|
||||
```sql
|
||||
CREATE TABLE students (
|
||||
student_id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(100)
|
||||
);
|
||||
```
|
||||
|
||||
Each student will have its own `student_id`, and this ID will be the primary key of the table. The `SERIAL` type is useful here because it ensures the `student_id` will always have a unique value.
|
||||
|
||||
A composite primary key is for when a table doesn't have a single unique column to identify the row. In this case, you can use a combination of two or more columns as the primary key that, together, are unique.
|
||||
|
||||
To do this, denote which columns are the composite primary key when you create the table like this:
|
||||
|
||||
```sql
|
||||
CREATE TABLE table_name (
|
||||
column1 data_type column_constraint,
|
||||
column2 data_type column_constraint,
|
||||
column3 data_type column_constraint,
|
||||
...
|
||||
PRIMARY KEY (column1, column2)
|
||||
);
|
||||
```
|
||||
|
||||
Imagine you have a table with `student_id` and `course_id` columns that tells you what students are enrolled in various classes.
|
||||
|
||||
Each student will be enrolled in several classes, and each class will have several students enrolled in it. So neither column is unique - but you will never have the same student enrolled in the same class more than once. So you can use the combination of the two columns as the primary key:
|
||||
|
||||
```sql
|
||||
CREATE TABLE course_enrollments (
|
||||
student_id INT,
|
||||
course_id INT,
|
||||
...
|
||||
PRIMARY KEY (student_id, course_id),
|
||||
);
|
||||
```
|
||||
|
||||
Primary keys are essential for ensuring data uniqueness and integrity, for optimizing data retrieval, and for establishing relationships with other tables in a relational database.
|
||||
|
||||
That takes us to the next type of key that we will cover in this lecture: foreign keys.
|
||||
|
||||
A foreign key is a column (or set of columns) in a table that references the primary key of another table. A table can have multiple foreign keys.
|
||||
|
||||
In this example, we have two tables, `customers`, and `orders`:
|
||||
|
||||
```sql
|
||||
CREATE TABLE customers (
|
||||
customer_id SERIAL PRIMARY KEY,
|
||||
first_name VARCHAR(100) NOT NULL,
|
||||
...
|
||||
);
|
||||
|
||||
CREATE TABLE orders (
|
||||
order_id SERIAL PRIMARY KEY,
|
||||
customer_id INTEGER,
|
||||
...
|
||||
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
|
||||
);
|
||||
```
|
||||
|
||||
The primary key of the `customers` table is `customer_id` and the primary key of the `orders` table is `order_id`.
|
||||
|
||||
But notice that there is also a `customer_id` column in the `orders` table.
|
||||
|
||||
Why are we storing customer information in the `orders` table?
|
||||
|
||||
We do this to create a relationship between the `customers` and `orders` tables. Each order will store the ID of the customer who submitted it.
|
||||
|
||||
To create the relationship between the tables, we will make the `customer_id` column in the `orders` table a foreign key that references the `customer_id` column in the `customers` table:
|
||||
|
||||
```sql
|
||||
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
|
||||
```
|
||||
|
||||
Values in a foreign key column must either match the primary key values in the referenced table or be `NULL` (if the foreign key allows `NULL`s).
|
||||
|
||||
Why is this helpful?
|
||||
|
||||
By making sure that these columns in both tables match exactly, foreign and primary keys prevent the creation of "orphaned" records, records that refer to a non-existent record in another table.
|
||||
|
||||
Primary and foreign keys are fundamental for relational databases. They power the "relational" aspect of these databases, allowing you to model real-world data in an accurate way.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
|
||||
What is the primary purpose of a primary key in a relational database table?
|
||||
|
||||
## --answers--
|
||||
|
||||
To link the table to other tables.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about what makes each row in a table distinct.
|
||||
|
||||
---
|
||||
|
||||
To uniquely identify each record in the table.
|
||||
|
||||
---
|
||||
|
||||
To define the data type of a column.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about what makes each row in a table distinct.
|
||||
|
||||
---
|
||||
|
||||
To enforce relationships with foreign keys in the same table.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about what makes each row in a table distinct.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
2
|
||||
|
||||
## --text--
|
||||
|
||||
A foreign key in one table typically references which key in another table?
|
||||
|
||||
## --answers--
|
||||
|
||||
Another foreign key
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which key in the referenced table ensures the integrity and validity of the relationship created by the foreign key.
|
||||
|
||||
---
|
||||
|
||||
A unique index
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which key in the referenced table ensures the integrity and validity of the relationship created by the foreign key.
|
||||
|
||||
---
|
||||
|
||||
A primary key
|
||||
|
||||
---
|
||||
|
||||
Any column with the same data type
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which key in the referenced table ensures the integrity and validity of the relationship created by the foreign key.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
3
|
||||
|
||||
## --text--
|
||||
|
||||
Which of the following is a characteristic of a primary key?
|
||||
|
||||
## --answers--
|
||||
|
||||
It can contain NULL values.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Remember the fundamental requirement for identifying each row distinctly.
|
||||
|
||||
---
|
||||
|
||||
It can be repeated in the same table.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Remember the fundamental requirement for identifying each row distinctly.
|
||||
|
||||
---
|
||||
|
||||
A table can have multiple primary keys.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Remember the fundamental requirement for identifying each row distinctly.
|
||||
|
||||
---
|
||||
|
||||
It must contain unique values.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
4
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
---
|
||||
id: 687ea8e0cab41019dc8a728a
|
||||
title: What Are the Different Types of Relationships in a Relational Database?
|
||||
challengeType: 19
|
||||
dashedName: what-are-the-different-types-of-relationships-in-a-relational-database
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Like you learned in previous lectures, relational databases store data in tables, which are made of rows and columns.
|
||||
|
||||
The "relational" aspect of "relational databases" comes from the fact that records in different tables can have different types of relationships.
|
||||
|
||||
There are five main types of relations:
|
||||
|
||||
- one-to-one
|
||||
- one-to-many
|
||||
- many-to-one
|
||||
- many-to-many
|
||||
- And self-referencing relationships (also known as recursive relationships).
|
||||
|
||||
Two tables have a **one-to-one** relationship when each record in the first table can be associated with at most one record in the second table, and vice versa.
|
||||
|
||||
For example, let's say a company only assigns one vehicle per employee.
|
||||
|
||||
In that case, the database could have an `employees` table and a `vehicles` table, where each employee record corresponds to one, and only one, vehicle record in the database.
|
||||
|
||||
In contrast, **one-to-many** relationships occur when one record in a table can be related to one or more records in another table.
|
||||
|
||||
For example, if we have a `customers` table and an `orders` table, each customer could be related to one or more orders but each order can only be related to one customer.
|
||||
|
||||
This is the same as the **many-to-one** relation, but from the opposite perspective. One or more orders can be related to one customer.
|
||||
|
||||
**Many-to-many** relationships occur when a record in a table can be related to multiple records in another table and vice versa.
|
||||
|
||||
For example, let's analyze a database for a library. For simplicity purposes, let's assume that this database only has two tables: `books` and `authors`.
|
||||
|
||||
An author can write multiple books, and a single book can be written by multiple authors.
|
||||
|
||||
Implementing this type of relationship is a little bit more complex because the relational model at its core doesn't support many-to-many relationships directly.
|
||||
|
||||
To handle this, you would usually create an intermediate table, also known as a junction table.
|
||||
|
||||
This table solves these initial limitations by transforming the many-to-many relationship into two one-to-many relationships.
|
||||
|
||||
It creates a one-to-many relationship between the first table and the junction table and a one-to-many relationship between the second table and the junction table.
|
||||
|
||||
The name of the junction table is usually a combination of the entities. In the context of our example of `books` and `authors`, you may call it `books_authors`.
|
||||
|
||||
In the junction table itself, you would associate the authors and their books by creating two columns: a column for the author's id (`author_id`) and another column for the book's id (`book_id`).
|
||||
|
||||
These would be foreign keys referencing their corresponding primary keys in the `authors` and `books` tables, respectively.
|
||||
|
||||
With this junction table, you'll be able to query all the authors of a given book or all books written by a given author.
|
||||
|
||||
Using a junction table makes it easier to query the data, prevents redundancy, and simplifies the database schema. They are very helpful for implementing many-to-many relationships.
|
||||
|
||||
And finally, we find **self-referencing** relationships, which occur when the records of a table can be related to other records on the same table. This is also known as a recursive relationship.
|
||||
|
||||
Understanding these relationships is essential for designing and modeling complex and efficient relational databases.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
|
||||
In which type of relationship can one record in Table A be associated with zero, one, or many records in Table B, while each record in Table B can be associated with only one record in Table A?
|
||||
|
||||
## --answers--
|
||||
|
||||
One-to-one
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which relationship type explicitly describes a single entity on one side relating to multiple entities on the other.
|
||||
|
||||
---
|
||||
|
||||
One-to-many
|
||||
|
||||
---
|
||||
|
||||
Many-to-many
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which relationship type explicitly describes a single entity on one side relating to multiple entities on the other.
|
||||
|
||||
---
|
||||
|
||||
Self-referencing
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which relationship type explicitly describes a single entity on one side relating to multiple entities on the other.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
2
|
||||
|
||||
## --text--
|
||||
|
||||
What is a many-to-many relationship in a relational database?
|
||||
|
||||
## --answers--
|
||||
|
||||
A relationship where one row in a table is related to many rows in another table.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about how the entities can be related to each other.
|
||||
|
||||
---
|
||||
|
||||
A relationship where one row in a table is related to only one row in another table.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about how the entities can be related to each other.
|
||||
|
||||
---
|
||||
|
||||
A relationship where multiple rows in one table are related to multiple rows in another table.
|
||||
|
||||
---
|
||||
|
||||
A relationship where there is no connection between the tables.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about how the entities can be related to each other.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
3
|
||||
|
||||
## --text--
|
||||
|
||||
Which type of relationship involves records within the same table being linked to other records in that same table?
|
||||
|
||||
## --answers--
|
||||
|
||||
One-to-many
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about a scenario where an entity has a relationship with other entities of the same type.
|
||||
|
||||
---
|
||||
|
||||
Many-to-one
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about a scenario where an entity has a relationship with other entities of the same type.
|
||||
|
||||
---
|
||||
|
||||
Many-to-many
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about a scenario where an entity has a relationship with other entities of the same type.
|
||||
|
||||
---
|
||||
|
||||
Self-referencing
|
||||
|
||||
## --video-solution--
|
||||
|
||||
4
|
||||
+293
@@ -0,0 +1,293 @@
|
||||
---
|
||||
id: 687ea8eba2a8b119f2ad9f8c
|
||||
title: What Are the Different Ways to Join Tables?
|
||||
challengeType: 19
|
||||
dashedName: what-are-the-different-ways-to-join-tables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Even though relational databases organize data into separate tables, SQL's `JOIN` operations allow you to combine related information from tables to query data.
|
||||
|
||||
There are five main types of `JOIN` operations:
|
||||
|
||||
- `INNER JOIN`
|
||||
- `FULL OUTER JOIN`
|
||||
- `LEFT OUTER JOIN`
|
||||
- `RIGHT OUTER JOIN`
|
||||
- `SELF JOIN`
|
||||
- And `CROSS JOIN`
|
||||
|
||||
Let's start with `INNER JOIN`.
|
||||
|
||||
An `INNER JOIN` filters the result to include only rows where the values in the joining columns that you specify are equal in both tables. Basically, it gives you the intersection of the data.
|
||||
|
||||
To illustrate this, let's say that we have two tables.
|
||||
|
||||
The first is this `products` table with multiple products. It includes their ID's, names, category, price, and origin.
|
||||
|
||||
```sql
|
||||
| product_id | product_name | category | price (USD) | origin |
|
||||
| ---------- | ---------------- | ----------- | ----------- | ------------- |
|
||||
| 1 | Ice Cream | Food | 2.50 | India |
|
||||
| 2 | Pizza Margherita | Food | 12.00 | Italy |
|
||||
| 3 | Sushi | Food | 18.75 | Japan |
|
||||
| 4 | T-Shirt | Clothing | 25.00 | USA |
|
||||
| 5 | Jeans | Clothing | 60.00 | Argentina |
|
||||
| 6 | Coffee | Beverages | 35.00 | France |
|
||||
| 7 | Juice | Beverages | 5.00 | Colombia |
|
||||
```
|
||||
|
||||
And second, we have a `sales` table, with the sale ID, product ID, quantity, and sale date.
|
||||
|
||||
```sql
|
||||
| sale_id | product_id | quantity | sale_date |
|
||||
| ------- | ---------- | -------- | ---------- |
|
||||
| 101 | 1 | 2 | 2025-07-18 |
|
||||
| 102 | 2 | 3 | 2025-02-13 |
|
||||
| 103 | 6 | 10 | 2025-06-08 |
|
||||
| 104 | 5 | 8 | 2025-01-10 |
|
||||
| 105 | 2 | 1 | 2025-05-15 |
|
||||
```
|
||||
|
||||
We can perform an `INNER JOIN` based on the `product_id` like this:
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM products
|
||||
INNER JOIN sales
|
||||
ON products.product_id = sales.product_id;
|
||||
```
|
||||
|
||||
This will only get the rows that have the same `product_id` in both tables. So if a product is not in the sales table or in products table, it will not be included.
|
||||
|
||||
This is the result:
|
||||
|
||||
```sql
|
||||
product_id | product_name | category | price | origin | sale_id | product_id | quantity | sale_date
|
||||
---------- | ---------------- | --------- |-------|-----------|---------|------------|----------|------------
|
||||
1 | Ice Cream | Food | 2.50 | India | 101 | 1 | 2 | 2025-07-18
|
||||
2 | Pizza Margherita | Food | 12.00 | Italy | 102 | 2 | 3 | 2025-02-13
|
||||
2 | Pizza Margherita | Food | 12.00 | Italy | 105 | 2 | 1 | 2025-05-15
|
||||
5 | Jeans | Clothing | 60.00 | Argentina | 104 | 5 | 8 | 2025-01-10
|
||||
6 | Coffee | Beverages | 35.00 | France | 103 | 6 | 10 | 2025-06-08
|
||||
```
|
||||
|
||||
We only see the rows of the products that have been sold. For example, `'Pizza Margherita'` is in the `sales` table, with a `product_id` of `2`, so we get that product in the result.
|
||||
|
||||
However, `'T-Shirts'` with a `product_id` of `4` were not sold, so this product is not in the `sales` table. They are not in both tables, so they are not included in the result.
|
||||
|
||||
Joining tables does exactly what it sounds like. It joins two or more tables into one, which is why we see all the columns from both tables, including `product_id` twice.
|
||||
|
||||
A `FULL OUTER JOIN` returns all rows from both tables.
|
||||
|
||||
If a match is found in the specified columns, the data is combined and you get all columns for each matching record.
|
||||
|
||||
If there's no match in the specified columns, in either one of the tables, the missing columns are filled with `NULL` values.
|
||||
|
||||
Let's perform a `FULL OUTER JOIN` in our example, based on the `product_id` column. This column will determine if there is a match or not.
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM products
|
||||
FULL OUTER JOIN sales
|
||||
ON products.product_id = sales.product_id;
|
||||
```
|
||||
|
||||
This is the result:
|
||||
|
||||
```sql
|
||||
product_id | product_name | category | price | origin | sale_id | product_id | quantity | sale_date
|
||||
---------- | ---------------- | --------- |-------|-----------|---------|------------|----------|------------
|
||||
1 | Ice Cream | Food | 2.50 | India | 101 | 1 | 2 | 2025-07-18
|
||||
2 | Pizza Margherita | Food | 12.00 | Italy | 102 | 2 | 3 | 2025-02-13
|
||||
3 | Sushi | Food | 18.75 | Japan | | | |
|
||||
4 | T-Shirt | Clothing | 25.00 | USA | | | |
|
||||
5 | Jeans | Clothing | 60.00 | Argentina | 104 | 5 | 8 | 2025-01-10
|
||||
6 | Coffee | Beverages | 35.00 | France | 103 | 6 | 10 | 2025-06-08
|
||||
7 | Juice | Beverages | 5.00 | Colombia | | | |
|
||||
2 | Pizza Margherita | Food | 12.00 | Italy | 105 | 2 | 1 | 2025-05-15
|
||||
```
|
||||
|
||||
Notice how `'Pizza Margherita'` has all the data, including columns from the `sales` table because there was a match.
|
||||
|
||||
But `'T-Shirt'` has empty (`NULL`) columns because no match was found in the `sales` table (this product was not sold).
|
||||
|
||||
A `LEFT OUTER JOIN` is used to get all the records from the left table and the matching information from the right table for each row of the left table.
|
||||
|
||||
If no match is found, the columns from the right table are filled in with `NULL` values.
|
||||
|
||||
Let's perform a `LEFT OUTER JOIN` in our example.
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM products
|
||||
LEFT JOIN sales
|
||||
ON products.product_id = sales.product_id;
|
||||
```
|
||||
|
||||
This is the result:
|
||||
|
||||
```sql
|
||||
product_id | product_name | category | price | origin | sale_id | product_id | quantity | sale_date
|
||||
---------- | ---------------- | --------- |-------|-----------|---------|------------|----------|------------
|
||||
1 | Ice Cream | Food | 2.50 | India | 101 | 1 | 2 | 2025-07-18
|
||||
2 | Pizza Margherita | Food | 12.00 | Italy | 102 | 2 | 3 | 2025-02-13
|
||||
3 | Sushi | Food | 18.75 | Japan | | | |
|
||||
4 | T-Shirt | Clothing | 25.00 | USA | | | |
|
||||
5 | Jeans | Clothing | 60.00 | Argentina | 104 | 5 | 8 | 2025-01-10
|
||||
6 | Coffee | Beverages | 35.00 | France | 103 | 6 | 10 | 2025-06-08
|
||||
7 | Juice | Beverages | 5.00 | Colombia | | | |
|
||||
2 | Pizza Margherita | Food | 12.00 | Italy | 105 | 2 | 1 | 2025-05-15
|
||||
```
|
||||
|
||||
In this case, it's the same as the `FULL OUTER JOIN` because it includes all rows from the first table, `products`.
|
||||
|
||||
A `RIGHT OUTER JOIN` is very similar, but now we get all the records from the right table and the matching information from the left table for each row of the right table.
|
||||
|
||||
If there's no match, the columns from the left table are filled in with `NULL` values.
|
||||
|
||||
Let's perform a `RIGHT OUTER JOIN` in our example.
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM products
|
||||
RIGHT JOIN sales
|
||||
ON products.product_id = sales.product_id;
|
||||
```
|
||||
|
||||
Here is the result:
|
||||
|
||||
```sql
|
||||
product_id | product_name | category | price | origin | sale_id | product_id | quantity | sale_date
|
||||
---------- | ---------------- | --------- |-------|-----------|---------|------------|----------|------------
|
||||
1 | Ice Cream | Food | 2.50 | India | 101 | 1 | 2 | 2025-07-18
|
||||
2 | Pizza Margherita | Food | 12.00 | Italy | 102 | 2 | 3 | 2025-02-13
|
||||
6 | Coffee | Beverages | 35.00 | France | 103 | 6 | 10 | 2025-06-08
|
||||
5 | Jeans | Clothing | 60.00 | Argentina | 104 | 5 | 8 | 2025-01-10
|
||||
2 | Pizza Margherita | Food | 12.00 | Italy | 105 | 2 | 1 | 2025-05-15
|
||||
```
|
||||
|
||||
You'll notice that it has fewer rows. This is because it takes all the records from the right table (`sales` in this case), and this table has fewer rows than the `products` table.
|
||||
|
||||
If it finds a match in the `products` table, it fills those columns with the data. But if there's no match, the columns are filled with `NULL`.
|
||||
|
||||
In this case, every product that has been sold has a record in the `products` table, so the data is complete.
|
||||
|
||||
These are the most commonly-used `JOIN` operations, but there are two additional ones that you should know about.
|
||||
|
||||
A `SELF JOIN` allows you to join the table with itself. You can think of it as joining two copies of the same table. This is helpful for comparing different rows within the same table.
|
||||
|
||||
A `CROSS JOIN`, also known as a Cartesian Join, joins every row from the first table with every row of the second table. Therefore, it generates all possible row combinations. This operation doesn't need any conditions to join the tables.
|
||||
|
||||
These `JOIN` operations are fundamental for working with SQL. By choosing the right one, you can query the data you need as efficiently as possible.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
|
||||
Which SQL `JOIN` operation returns only the rows where there is a match in both tables based on the join condition?
|
||||
|
||||
## --answers--
|
||||
|
||||
`LEFT JOIN`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which join type is most restrictive in terms of only including records that match both tables.
|
||||
|
||||
---
|
||||
|
||||
`INNER JOIN`
|
||||
|
||||
---
|
||||
|
||||
`RIGHT JOIN`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which join type is most restrictive in terms of only including records that match both tables.
|
||||
|
||||
---
|
||||
|
||||
`FULL JOIN`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which join type is most restrictive in terms of only including records that match both tables.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
2
|
||||
|
||||
## --text--
|
||||
|
||||
Which SQL `JOIN` operation would you use if you need to retrieve all customers (left) and, for each customer, any orders (right) they might have placed? Customers with no orders should still be included in the result.
|
||||
|
||||
## --answers--
|
||||
|
||||
`LEFT JOIN`
|
||||
|
||||
---
|
||||
|
||||
`INNER JOIN`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which join ensures that all records from the customers table are included in the output.
|
||||
|
||||
---
|
||||
|
||||
`RIGHT JOIN`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which join ensures that all records from the customers table are included in the output.
|
||||
|
||||
---
|
||||
|
||||
`FULL JOIN`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about which join ensures that all records from the customers table are included in the output.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
1
|
||||
|
||||
## --text--
|
||||
|
||||
Which SQL `JOIN` operation returns all rows from both tables, including unmatched rows (with `NULL`s for the columns of the table without a match)?
|
||||
|
||||
## --answers--
|
||||
|
||||
`LEFT JOIN`
|
||||
|
||||
### --feedback--
|
||||
|
||||
This join aims to be the most inclusive, taking all records from both tables.
|
||||
|
||||
---
|
||||
|
||||
`INNER JOIN`
|
||||
|
||||
### --feedback--
|
||||
|
||||
This join aims to be the most inclusive, taking all records from both tables.
|
||||
|
||||
---
|
||||
|
||||
`RIGHT JOIN`
|
||||
|
||||
### --feedback--
|
||||
|
||||
This join aims to be the most inclusive, taking all records from both tables.
|
||||
|
||||
---
|
||||
|
||||
`FULL JOIN`
|
||||
|
||||
## --video-solution--
|
||||
|
||||
4
|
||||
@@ -1427,6 +1427,9 @@
|
||||
"dashedName": "relational-databases",
|
||||
"comingSoon": true,
|
||||
"blocks": [
|
||||
{
|
||||
"dashedName": "lecture-working-with-relational-databases"
|
||||
},
|
||||
{
|
||||
"dashedName": "workshop-database-of-video-game-characters"
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user