0% found this document useful (0 votes)
39 views17 pages

Notes of Class 12th DCC

xyz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views17 pages

Notes of Class 12th DCC

xyz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

1

Data:

Data is raw, unprocessed facts or figures that, on their own, have little meaning. It represents basic
elements like numbers, text, dates, or even observations.

Information:

Definition: Information is processed or organized data that has been given meaning, context, or
relevance. It provides value and helps in decision-making or understanding.

The Relationship Between Data and Information:

✓ Data is the raw material that, when processed, becomes information.


✓ Data alone may not make much sense, but once it is organized and analysed, it becomes
information that can be used to make decisions or draw conclusions.

Introduction to Databases

A database is a structured collection of data that is stored and managed in a way that allows for easy
access, manipulation, and updating. It is designed to handle large amounts of information by
organizing it into tables, records, and fields in a way that is efficient, reliable, and secure.

Databases are a key part of many modern applications, ranging from simple websites to complex
enterprise systems. They help store, retrieve, and manage data, supporting decision-making and
operations within organizations.

Introduction to File System:

Before the use of a computer, a manual file system was used to maintain the records and files. Data
were stored and processed using a traditional file system and it makes it easy to find any information.
In this traditional file system, each file is independent of other file and data in the different file can
be integrated only by writing an individual program for each application.

Introduction to the Database Management System

A Database Management System (DBMS) is a software tool that helps you store, manage, and
retrieve data from a database. It acts as an intermediary between users (or applications) and the
database, making it easier to organize, access, and manipulate large amounts of data.

Common Examples of DBMS:

❖ MySQL
❖ PostgreSQL
❖ Oracle
❖ Microsoft SQL Server

DBMS allows users the following tasks:

Data Definition, Data Manipulation (update), Data Retrieval, User Administration

Data Definition (DDL - Data Definition Language):

Create, modify, and delete database structures (such as tables, indexes, and views).
2

Allows users to define the structure of the database and its components.

Examples:
▪ CREATE TABLE – To create a new table.
▪ ALTER TABLE – To modify an existing table structure.
▪ DROP TABLE – To delete a table from the database.

Data Manipulation (DML - Data Manipulation Language)


It is used for the insertion, modification, and deletion of the actual data in the database.
Examples:
▪ INSERT INTO – To add new records (rows) to a table.
▪ UPDATE – To modify existing data in the database.
▪ DELETE – To remove data from a table.
Data Retrieval:
It is used to retrieve the data from the database which can be used by applications for various
purposes.
Examples:
▪ SELECT – To query and retrieve data from tables.
User Administration:
It is used for registering and monitoring users, maintain data integrity, enforcing data security,
dealing with concurrency control, monitoring performance and recovering information corrupted by
unexpected failure.
▪ BEGIN TRANSACTION – Starts a transaction.
▪ COMMIT – Finalizes and saves the changes made during a transaction.
▪ ROLLBACK – Reverts changes made during a transaction if there’s an error.
Characteristics of Database Management System:
A database management system has following characteristics:
1. Data stored into Tables: Data are never directly stored into the database. Data are stored into
tables, created inside the database.
2. Reduced Redundancy: In the modern world hard drives are very cheap, but earlier when
hard drives were too expensive, unnecessary repetition of data in database was a big
problem. But DBMS follows Normalisation which divides the data in such a way that
repetition is minimum.
3. Data Consistency: On Live data, i.e. data that is being continuously updated and added,
maintaining the consistency of data can become a challenge. But DBMS handles it all by
itself.
4. Support Multiple user and Concurrent Access: DBMS allows multiple users to work on it
(update, insert, delete data) at the same time and still manages to maintain the data
consistency.
5. Query Language: DBMS provides users with a simple Query language, using which data can
be easily fetched, inserted, deleted and updated in a database.
3

6. Security: The DBMS also takes care of the security of data, protecting the data from un-
authorised access. In a typical DBMS, we can create user accounts with different access
permissions, using which we can easily secure our data by restricting user access.
7. Transactions: DBMS supports transactions, which allows us to better handle and man- age
data integrity in real world applications where multi-threading is extensively used.
Difference b/w File System and DBMS
4

Advantages of Database Management System

✓ Data Security: A Database Management System (DBMS) provides a better platform for data
privacy and security policies thus, helping companies to improve Data Security.
✓ Data integration: Due to the Database Management System we have access to well-
managed and synchronized forms of data thus it makes data handling very easy and gives an
integrated view of how a particular organization is working and also helps to keep track of
how one segment of the company affects another segment.
✓ Data abstraction: The major purpose of a database system is to provide users with an
abstract view of the data
✓ Reduction in data Redundancy: When working with a structured database, DBMS provides
the feature to prevent the input of duplicate items in the database. for e.g. – If there are two
same students in different rows, then one of the duplicate data will be deleted.
✓ Data sharing: A DBMS provides a platform for sharing data across multiple applications and
users, which can increase productivity and collaboration.
✓ Data consistency and accuracy: DBMS ensures that data is consistent and accurate by
enforcing data integrity constraints and preventing data duplication.
✓ Data organization: A DBMS provides a systematic approach to organizing data in a structured
way, which makes it easier to retrieve and manage data efficiently.
✓ Efficient data access and retrieval: DBMS allows for efficient data access and retrieval by
providing indexing and query optimization techniques that speed up data retrieval.
✓ Concurrency and maintained Atomicity: That means, if some operation is performed on one
particular table of the database, then the change must be reflected for the entire database.
✓ Scalability and flexibility: DBMS is highly scalable and can easily accommodate changes in
data volumes and user requirements. DBMS can easily handle large volumes of data, and can
scale up or down depending on the needs of the organization. It provides flexibility in data
storage, retrieval, and manipulation, allowing users to easily modify the structure and
content of the database as needed.

Disadvantages of Database Management System

✓ Complex Design: Database design is complex, difficult and time consuming.


✓ Damaged Part : If one part of database is corrupted or damaged, then entire database
may get affected.
✓ Compatibility: DBMS software may not be compatible with other software systems or
platforms, making it difficult to integrate with other applications.
✓ Security: A DBMS can be vulnerable to security breaches if not properly configured and
managed. This can lead to data loss or theft.
✓ Data Isolation: Because data are scattered in various files, and files may be in different
formats, writing new application programs to retrieve the appropriate data is difficult.
✓ Difficulty in Accessing Data: Suppose that one of the university clerks needs to find out
the names of all students who live within a particular postal-code area.

What is Structured Query Language (SQL)

SQL (Structured Query Language) is a standard programming language used for managing and
manipulating relational databases. It allows users to interact with databases by performing various
tasks such as:
5

• Querying Data: SQL enables users to retrieve specific data from a database using the SELECT
statement.

• Inserting Data: Data can be added into a database using the INSERT INTO statement.

• Updating Data: The UPDATE statement is used to modify existing data in the database.

• Deleting Data: SQL allows for deleting records from the database with the DELETE
statement.

• Creating and Modifying Structures: SQL provides commands like CREATE TABLE, ALTER
TABLE, and DROP TABLE to define and manage the structure of a database.

• Managing Permissions: It includes commands like GRANT and REVOKE to control access to
data.

• Joining Tables: SQL allows combining data from multiple tables using JOIN operations.

Characteristics of the SQL

SQL (Structured Query Language) is a powerful language used for managing and manipulating
relational databases. Here are the key characteristics of SQL:

1. Declarative Language:
SQL is a declarative language, which means users describe what they want to do with data
(e.g., select, insert, update), but not how the database should perform the operations.

2. Platform Independent:
SQL can be used across various platforms and DBMSs (like MySQL, PostgreSQL, SQL Server,
and Oracle).

3. Data Definition (DDL):


SQL provides commands for defining and managing database structures, such as:

✓ CREATE: To create databases, tables, views, indexes, etc.

✓ ALTER: To modify existing database structures.

✓ DROP: To delete databases, tables, etc.

✓ TRUNCATE: To remove all records from a table, while preserving the structure.

4. Data Manipulation (DML):


SQL enables users to manipulate data within tables through commands like:

✓ SELECT: To query and retrieve data.

✓ INSERT: To add new data.

✓ UPDATE: To modify existing data.

✓ DELETE: To remove data.

5. Integrity Constraints:
SQL allows the definition of rules to ensure data accuracy and consistency, such as:

✓ PRIMARY KEY: A unique identifier for records in a table.


6

✓ FOREIGN KEY: Ensures referential integrity between tables.

✓ UNIQUE: Ensures all values in a column are distinct.

✓ CHECK: Ensures values in a column meet specific conditions.

✓ NOT NULL: Ensures that a column does not accept NULL values.

6. Normalization:
SQL supports data normalization techniques, which help in organizing data into tables to
minimize redundancy and dependency.

7. Join Operations:
SQL enables combining data from multiple tables using JOIN operations:

✓ INNER JOIN: Returns matching rows from both tables.

✓ LEFT JOIN: Returns all rows from the left table and matching rows from the right.

✓ RIGHT JOIN: Returns all rows from the right table and matching rows from the left.

✓ FULL OUTER JOIN: Returns all rows when there is a match in either left or right table.

8. Aggregation:
SQL supports aggregate functions to summarize data, such as:

✓ COUNT(): Counts rows.

✓ SUM(): Adds up values.

✓ AVG(): Calculates average values.

✓ MAX(): Finds the maximum value.

✓ MIN(): Finds the minimum value.

11. Scalability and Performance:


SQL databases can handle large volumes of data and are optimized for efficient query
processing.

Applications of SQL

1. Data Retrieval and Reporting

• Business Intelligence (BI): SQL is extensively used in BI tools and applications to query and
retrieve data from databases for reporting, dashboards, and data analysis. For example, SQL
is used in tools like Tableau, Power BI, and Google Data Studio.

• Data Analytics: Analysts use SQL to extract, manipulate, and aggregate data to uncover
insights and trends, performing complex queries for data mining, statistical analysis, and
predictive modeling.

2. Data Management

• Data Insertion and Updates: SQL is used to insert new records into a database, modify
existing records, and delete outdated or incorrect data. For example, e-commerce platforms
use SQL for managing customer orders, inventories, and product data.
7

• Data Maintenance: Database administrators (DBAs) use SQL to maintain and optimize the
performance of databases, including tasks like database backups, indexing, and schema
modifications.

4. Enterprise Resource Planning (ERP) Systems

• Business Operations Management: SQL plays a crucial role in managing large enterprise
systems such as ERP software (e.g., SAP, Oracle ERP). These systems store, retrieve, and
update data related to accounting, supply chain management, inventory, sales, human
resources, and more.

5. Customer Relationship Management (CRM) Systems

• Customer Data Management: SQL is used in CRM systems (e.g., Salesforce, HubSpot) to
store and manage customer information, sales leads, communications, and transaction
history. Queries help in tracking customer interactions and providing insights into sales
trends.

6. Financial and Banking Systems

• Transaction Management: In financial systems, SQL is used to manage banking transactions,


accounts, and balance details. Banks and financial institutions rely heavily on SQL to manage
secure data transactions, generate reports, and handle large volumes of data.

• Data Security and Audit Logs: SQL helps to manage and audit transaction logs, ensuring
compliance with regulatory standards (e.g., SOX, GDPR).

7. Healthcare Systems

• Electronic Health Records (EHR): SQL is used in healthcare databases to store and retrieve
patient records, medical histories, appointment schedules, lab results, and insurance
information.

• Data Integration: SQL queries can integrate data from various healthcare sources to provide
a comprehensive view of patient care and clinical performance.

8. E-commerce Platforms

• Product Catalogs: SQL is used in e-commerce applications to manage product inventories,


customer orders, and payment details. For example, when a customer searches for products,
SQL queries retrieve relevant product details from the database.

• Order Processing: SQL queries track customer orders, process payments, and update order
statuses in real-time.

9. Social Media Platforms

• User Data Management: Social media platforms (e.g., Facebook, Twitter) use SQL to store
and manage user profiles, posts, comments, and interaction histories. SQL queries help
retrieve data related to user activity and interactions.

• Content Moderation: SQL can be used to track and store flagged content, moderation logs,
and user behavior, ensuring compliance with platform policies.
8

10. Education and Learning Management Systems (LMS)

• Student Records: SQL is used to store and manage student information, including grades,
courses, schedules, and attendance.

• Course Management: Educational institutions use SQL for managing course catalogs,
instructor assignments, student enrollments, and assessment data.

11. Government and Public Sector

• Public Records Management: Government agencies use SQL databases to store and manage
public records, such as tax information, legal documents, and public health records.

• Census and Survey Data: SQL is used to store and analyze data collected through national
15. Research and Scientific Databases

• Experimental Data Management: SQL is used by researchers to store experimental data,


track changes over time, and manage results from various research projects.

• Bioinformatics: In fields like genomics and bioinformatics, SQL is used to store large datasets
and perform complex queries related to genes, proteins, and sequences.

12. Mobile Applications

• Local Data Storage: SQL is used for local data storage in mobile applications, where
lightweight relational databases like SQLite are used to store data on the device, such as user
preferences, offline content, and app settings.

Advantages of SQL

✓ Simplicity and Ease of Use:


SQL uses a simple, declarative syntax that is easy to learn and understand. You can perform
complex queries with just a few lines of code.
✓ Powerful Data Manipulation:
SQL can handle a wide variety of tasks like querying, inserting, updating, and deleting large
datasets with minimal effort.
✓ Data Integrity and Accuracy:
SQL allows you to set integrity constraints such as primary keys, foreign keys, and unique
constraints, ensuring the accuracy and consistency of the data.
✓ High Performance:
SQL databases are optimized for querying large datasets. With features like indexing and
query optimization, SQL databases can perform efficiently, even with large volumes of data.
✓ Security:
SQL allows fine-grained control over user permissions and access, ensuring data security. You
can grant or revoke permissions at various levels (e.g., table, column).
✓ Data Scalability:
SQL is highly scalable and can be used to manage databases ranging from small, single-user
applications to large, enterprise-level systems.

Disadvantages of SQL

✓ Complexity for Large Databases:


While SQL is simple for basic operations, complex queries involving multiple joins,
aggregations can become difficult to write and maintain in large databases.
9

✓ Performance Issues with Huge Datasets:


As data grows, the performance of SQL queries can degrade, especially without proper
indexing and optimization. Complex queries can take longer to execute.
✓ Learning Curve for Advanced Features:
queries can be challenging for beginners.
✓ Database Dependency:
SQL syntax and functionality can vary slightly between different database systems. This can
create issues when migrating between platforms or working in multi-database environments.

Math functions in SQL

Name Description

ABS Returns the absolute value

ACOS Returns the arc cosine of an argument

ASIN Returns the arc sine of an argument

ATAN Returns the arc tangent of an argument

CEIL,CEILING Rounds up a float to the nearest integer value

COS Returns the cosine of an argument

COT Returns the cotangent of an argument

EXP Returns the e constant (2.71828…) that raises to a power of a specified number

LN Returns the natural logarithm of the argument

LOG Returns the natural logarithm of the first argument

LOG10 Returns the base-10 logarithm of the argument

LOG2 Returns the base-2 logarithm of the argument

MOD Returns the remainder (modulo) of a number divided by another

PI Returns the value of pi which is 3.14159265358979

POWER Returns a number raised to a power of a specified number

RAND Returns a random floating-point value

ROUND Rounds a number to a specific precision

SIGN Returns the sign of an argument

SIN Returns the sine of an argument


10

Name Description

SQRT Returns the square root of an argument

TAN Returns the tangent of an argument

What is Date Functions in SQL:

Date functions in SQL are used to perform operations on date and time data types, such as retrieving
parts of a date, manipulating date values, calculating date differences, and formatting dates. These
functions are essential for handling time-based data in databases.

Common Types of Date Functions in SQL:

✓ NOW(): Returns the current date and time


✓ CURDATE(): Returns the current date (without the time part) based on the system's date.
✓ CURTIME(): Returns the current time (without the date part) based on the system's time.
✓ DATE(): Extracts the date part (year, month, day) from a datetime or timestamp value,
ignoring the time part.
✓ EXTRACT(): Extracts a specific part of a date (e.g., year, month, day, hour, minute, second).
✓ DATE_ADD(): Adds a specified time interval (like days, months, years) to a date.
✓ DATE_SUB(): Subtracts a specified time interval from a date.
✓ DATE_DIFF(): Returns the difference in days between two dates.

Aggregate functions in SQL:

an aggregate function is a function that operates on a set of values to return a single value.

Here are some commonly used aggregate functions in SQL:

✓ COUNT(): Returns the number of rows in a set or group.


Example: SELECT COUNT(*) FROM employees;
✓ SUM(): Returns the total sum of a numeric column.
Example: SELECT SUM(salary) FROM employees;
✓ AVG(): Returns the average value of a numeric column.
Example: SELECT AVG(salary) FROM employees;
✓ MIN(): Returns the minimum value in a column.
Example: SELECT MIN(salary) FROM employees;
✓ MAX(): Returns the maximum value in a column.
Example: SELECT MAX(salary) FROM employees;
✓ FIRST(): Returns the first value in a column.
Example: SELECT FIRST(salary) FROM employees;
✓ LAST(): Returns the last value in a column.
Example: SELECT LAST(salary) FROM employees;

SOME SQL STATEMENTS:

CREATE TABLE:

The CREATE TABLE statement in SQL is used to create a new table in a database. The basic syntax
defines the table name, followed by a list of columns and their data types.
11

Let’s create a simple employees table:

CREATE TABLE employees (


employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
hire_date DATE,
salary DECIMAL(10, 2),
department_id INT
);

ALTER TABLE:

The ALTER TABLE statement in SQL is used to modify an existing table's structure. You can use it to
add, modify, or delete columns, constraints, or other table properties.

To add a new column to an existing table:

ALTER TABLE employees


ADD email VARCHAR(100);

DROP TABLE:

The DROP TABLE statement in SQL is used to delete an existing table from the database, along with
all the data stored within it. This operation is irreversible, meaning once the table is dropped, both
the table structure and the data are permanently removed.

If you have a table named employees and you want to remove it, you can use the following
statement:

DROP TABLE employees;

INSERT INTO:

The INSERT INTO statement in SQL is used to add new rows of data into an existing table. This
statement allows you to insert single or multiple rows into a table.

1. Inserting a Single Row


Assume there is a table called employees with columns employee_id, first_name, last_name,
and hire_date. You can insert a single row like this:

INSERT INTO employees (employee_id, first_name, last_name, hire_date)


VALUES (1, 'John', 'Doe', '2024-12-04');

2. Inserting Multiple Rows


To insert multiple rows into the employees table:

INSERT INTO employees (employee_id, first_name, last_name, hire_date)


VALUES (2, 'Alice', 'Smith', '2024-12-05'),
(3, 'Bob', 'Johnson', '2024-12-06'),
(4, 'Charlie', 'Brown', '2024-12-07');
12

3. Inserting Data Without Specifying Column Names


If you are inserting data into every column in the table and the order of values matches the
column order, you can omit the column names in the INSERT INTO statement.

INSERT INTO employees


VALUES (5, 'David', 'Williams', '2024-12-08');

DELETE STATEMENT:

The DELETE statement in SQL is used to remove one or more rows from an existing table. This
operation permanently removes the data from the table, but the structure of the table (such as
columns, constraints, etc.) remains intact.

1. Deleting Specific Rows (with a condition)

If you want to delete specific rows based on a condition, use the WHERE clause.

Example:

DELETE FROM employees


WHERE employee_id = 1;

2. Deleting All Rows (without a condition)

If you want to delete all rows from a table but keep the table structure (columns, constraints, etc.)
intact, omit the WHERE clause.

Example:

DELETE FROM employees;

3. Using Multiple Conditions

You can specify multiple conditions in the WHERE clause to delete rows that meet more complex
criteria.

Example:

DELETE FROM employees


WHERE hire_date < '2020-01-01' AND salary < 50000;

UPDATE STATEMENT:

The UPDATE statement in SQL is used to modify the existing data in one or more rows of a table. It
allows you to change the values in one or more columns for specific rows based on a given condition.

1. Updating Specific Rows

You can update specific rows by using the WHERE clause to filter the rows based on a condition.
13

Example:

Suppose you have a table employees with columns employee_id, first_name, last_name, and salary.
If you want to update the salary of the employee with employee_id = 1, you would write:

UPDATE employees
SET salary = 60000
WHERE employee_id = 1;

2. Updating Multiple Columns

You can update multiple columns in the same row by separating each column-value pair with a
comma.

Example:

If you want to update both the salary and the last_name for the employee with employee_id = 2, you
would write:

UPDATE employees
SET salary = 65000, last_name = 'Smith'
WHERE employee_id = 2;

3. Updating All Rows (without a condition)

If you omit the WHERE clause, all rows in the table will be updated. Be cautious, as this will affect
every row in the table.

Example:

UPDATE employees
SET salary = 50000;

SELECT STATEMENT:

The SELECT statement in SQL is used to query data from one or more tables in a database. It allows
you to retrieve specific columns, rows, or combinations of both based on the conditions you specify.

1. Selecting Specific Columns

To select specific columns from a table, list the column names in the SELECT statement.

Example:

SELECT first_name, last_name


FROM employees;

2. Selecting All Columns

To select all columns from a table, use the * wildcard.


14

Example:

SELECT *
FROM employees;

3. Using DISTINCT to Avoid Duplicate Rows

The DISTINCT keyword is used to eliminate duplicate values in the result set.

Example:

SELECT DISTINCT department_id


FROM employees;

4. Using Aggregate Functions

You can use aggregate functions like COUNT(), SUM(), AVG(), MIN(), and MAX() to perform
calculations on your data.

Example (SUM):

SELECT SUM(salary)
FROM employees
WHERE department_id = 3;

5. Using Logical Operators in WHERE Clause

You can combine conditions using logical operators like AND, OR, and NOT.

Example:

SELECT first_name, last_name, salary


FROM employees
WHERE department_id = 3 AND salary > 50000;

SQL CLAUSES:

1. WHERE

The WHERE clause is used to filter records based on specified conditions. It is used to retrieve only
those rows that meet the condition(s).

Example:

SELECT first_name, last_name


FROM employees
WHERE department_id = 3;
15

2. GROUP BY

The GROUP BY clause is used to group rows that have the same values in specified columns into
summary rows, like calculating the average salary or total sales per department.

Example:

SELECT department_id, AVG(salary)


FROM employees
GROUP BY department_id;

3. HAVING

The HAVING clause is used to filter groups created by GROUP BY. It is similar to the WHERE clause but
applies to grouped data.

Example:

SELECT department_id, AVG(salary)


FROM employees
GROUP BY department_id
HAVING AVG(salary) > 50000;

4. ORDER BY

The ORDER BY clause is used to sort the result set by one or more columns in either ascending (ASC)
or descending (DESC) order.

Example:

SELECT first_name, last_name, salary


FROM employees
ORDER BY salary DESC;

JOINS IN SQL:

In SQL, the JOIN operation is used to combine data from two or more tables based on a related
column between them. It helps in retrieving related data from multiple tables, typically by matching
columns that share common values.

There are several types of joins in SQL:

✓ Natural Join
✓ Inner Join (Equi Join)
✓ Left Outer Join
✓ Right Outer Join
✓ Full Outer Join

NATURAL JOIN:

A NATURAL JOIN is a type of join that automatically joins two tables based on all columns with the
same name and data type in both tables. It simplifies the SQL query by eliminating the need to
16

explicitly specify the join condition using the ON keyword. Instead, the database system
automatically matches columns with the same name and performs the join.

Example Query:

SELECT employee_id, first_name, last_name, department_name


FROM employees
NATURAL JOIN departments;

INNER JOIN (EQUI JOIN):

An INNER JOIN returns only the rows that have matching values in both tables. If there is no match,
the row is excluded from the result.

Example:

Suppose you have two tables:

• employees (employee_id, first_name, department_id)

• departments (department_id, department_name)

To get the list of employees along with their department names:

SELECT e.first_name, e.last_name, d.department_name


FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id;

Result: Returns a list of employees and their respective departments, but only where a match exists
for the department_id in both tables.

LEFT JOIN (or LEFT OUTER JOIN):

A LEFT JOIN (or LEFT OUTER JOIN) returns all the rows from the left table and the matched rows from
the right table. If there is no match, NULL values are returned for columns of the right table.

Example:

To list all employees along with their department names (including employees without a
department):

SELECT e.first_name, e.last_name, d.department_name


FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id;

Result: Returns all employees, including those without a department. For employees without a
department, the department_name will be NULL.

RIGHT JOIN (or RIGHT OUTER JOIN):

A RIGHT JOIN (or RIGHT OUTER JOIN) returns all the rows from the right table and the matched rows
from the left table. If there is no match, NULL values are returned for columns of the left table.
17

Example:

To list all departments along with the employees who belong to those departments (including
departments without employees):

SELECT e.first_name, e.last_name, d.department_name


FROM employees e
RIGHT JOIN departments d ON e.department_id = d.department_id;

Result: Returns all departments, including those without employees. For departments without
employees, the first_name and last_name will be NULL.

FULL JOIN (or FULL OUTER JOIN):

A FULL JOIN (or FULL OUTER JOIN) returns all rows when there is a match in either the left or the
right table. If there is no match, NULL values are returned for the non-matching side.

Example:

To list all employees and all departments, including those without a department or without
employees:

SELECT e.first_name, e.last_name, d.department_name


FROM employees e
FULL JOIN departments d ON e.department_id = d.department_id;

Result: Returns all employees and all departments. For employees without a department, the
department_name will be NULL. For departments without employees, the first_name and last_name
will be NULL.

Summary of Join Types:

Join
Description Result
Type

INNER Returns rows that have matching


Only rows where there is a match between both tables.
JOIN values in both tables.

Returns all rows from the left table All rows from the left table, matched rows from the
LEFT
and matched rows from the right right table. If no match, NULL is returned for columns
JOIN
table. from the right table.

Returns all rows from the right table All rows from the right table, matched rows from the
RIGHT
and matched rows from the left left table. If no match, NULL is returned for columns
JOIN
table. from the left table.

FULL Returns rows when there is a match All rows from both tables, with NULL values for columns
JOIN in either table. of the table that has no matching rows.

You might also like