0% found this document useful (0 votes)
45 views44 pages

Relational Algebra Basics and Operators

The document discusses relational algebra, a formal query language for relational databases, detailing its basic operators such as selection, projection, union, set difference, Cartesian product, and rename. It also covers derived operators like join, intersection, and division, as well as relational calculus, a non-procedural query language that focuses on what data is needed without specifying how to obtain it. The document emphasizes the procedural nature of relational algebra and the declarative nature of relational calculus, highlighting their respective roles in database management systems.

Uploaded by

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

Relational Algebra Basics and Operators

The document discusses relational algebra, a formal query language for relational databases, detailing its basic operators such as selection, projection, union, set difference, Cartesian product, and rename. It also covers derived operators like join, intersection, and division, as well as relational calculus, a non-procedural query language that focuses on what data is needed without specifying how to obtain it. The document emphasizes the procedural nature of relational algebra and the declarative nature of relational calculus, highlighting their respective roles in database management systems.

Uploaded by

preethishree900
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Module 2

Relational Algebra, Calculus, and SQL

Relational algebra is one of the two formal query languages associated with the relational model.
Queries in algebra are composed using a collection of operators. A fundamental property is that
every operator in the algebra accepts (one or two) relation instances as arguments and returns a
relation instance as the result.
This property makes it easy to compose operators to form a complex query—a relational algebra
expression is recursively defined to be a relation, a unary algebra operator applied to a single
expression, or a binary algebra operator applied to two expressions. We describe the basic
operators of the algebra (selection, projection, union, cross-product, and difference), as well as
some additional operators that can be defined in terms of the basic operators but arise frequently
enough to warrant special attention, in the following sections.
Each relational query describes a step-by-step procedure for computing the desired answer,
based on the order in which operators are applied in the query. The procedural nature of the
algebra allows us to think of an algebra expression as a recipe, or a plan, for evaluating a query,
and relational systems in fact use algebra expressions to represent query evaluation plans.

Before explaining relational algebra operations, let's define some fundamental concepts:
 Relations: In relational algebra, a relation is a table that consists of rows and columns,
representing data in a structured format. Each relation has a unique name and is made up of
tuples.
 Tuples: A tuple is a single row in a relation, which contains a set of values for each
attribute. It represents a single data entry or record in a relational table.
 Attributes: Attributes are the columns in a relation, each representing a specific
characteristic or property of the data. For example, in a "Students" relation, attributes could
be "Name", "Age", and "Grade".
 Domains: A domain is the set of possible values that an attribute can have. It defines
the type of data that can be stored in each column of a relation, such as integers, strings, or
dates.

Relational algebra is a procedural query language, which takes instances of relations as input
and yields instances of relations as output. It uses operators to perform queries. An operator
can be either unary or binary. They accept relations as their input and yield relations as their
output. Relational algebra is performed recursively on a relation and intermediate results are
also considered relations.
Basic Operators in Relational Algebra
Relational algebra consists of various basic operators that help us to fetch and manipulate data
from relational tables in the database to perform certain operations on relational data. Basic
operators are fundamental operations that include selection (σ), projection (π), union (U), set
difference (−), Cartesian product (×), and rename (ρ).
1. Selection(σ)
The Selection Operation is basically used to filter out rows from a given table based on certain
given condition. It basically allows us to retrieve only those rows that match the condition as per
condition passed during SQL Query.
Example: If we have a relation R with attributes A, B, and C, and we want to select tuples where C > 3,
we write:

A B C

1 2 4

2 2 3

3 2 3

4 3 4

σ(c>3)(R) will select the tuples which have c more than 3.


Output:
A B C

1 2 4

4 3 4

Explanation: The selection operation only filters rows but does not display or change their
order. The projection operator is used for displaying specific columns.
2. Projection(π)
While Selection operation works on rows, similarly projection operation of relational algebra
works on columns. It basically allows us to pick specific columns from a given relational table
based on the given condition and ignoring all the other remaining columns.
Example: Suppose we want columns B and C from Relation R.
π(B,C)(R) will show following columns.
Output:
B C

2 4

2 3

3 4

Explanation: By Default, projection operation removes duplicate values.


3. Union(U)
The Union Operator is basically used to combine the results of two queries into a single result.
The only condition is that both queries must return same number of columns with same data
types. Union operation in relational algebra is the same as union operation in set theory.
Example: Consider the following table of Students having different optional subjects in their
course.

FRENCH
Student_Name Roll_Number

Ram 01

Mohan 02

Vivek 13

Geeta 17

GERMAN
Student_Name Roll_Number

Vivek 13

Geeta 17
Student_Name Roll_Number

Shyam 21

Rohan 25

If FRENCH and GERMAN relations represent student names in two subjects, we can combine
their student names as follows:
π(Student_Name)(FRENCH) U π(Student_Name)(GERMAN)
Output:
Student_Name

Ram

Mohan

Vivek

Geeta

Shyam

Rohan

Explanation: The only constraint in the union of two relations is that both relations must have
the same set of Attributes.
4. Set Difference(-)
Set difference basically provides the rows that are present in one table, but not in another
tables. Set Difference in relational algebra is the same set difference operation as in set theory.
Example: To find students enrolled only in FRENCH but not in GERMAN, we write:
π(Student_Name)(FRENCH) - π(Student_Name)(GERMAN)

Student_Name

Ram
Student_Name

Mohan

Explanation: The only constraint in the Set Difference between two relations is that both
relations must have the same set of Attributes.

5. Rename(ρ)
Rename operator basically allows you to give a temporary name to a specific relational table or
to its columns. It is very useful when we want to avoid ambiguity, especially in complex
Queries. Rename is a unary operation used for renaming attributes of a relation.
Example: We can rename an attribute B in relation R to D
A B C

1 2 4

2 2 3

3 2 3

4 3 4

ρ(D/B)R will rename the attribute 'B' of the relation by "D".

Output Table:
A D C

1 2 4

2 2 3

3 2 3

4 3 4

6. Cartesian Product(X)
The Cartesian product combines every row of one table with every row of another table,
producing all the possible combination. It's mostly used as a precursor to more complex
operation like joins. Let’s say A and B, so the cross product between A X B will result in all
the attributes of A followed by each attribute of B. Each record of A will pair with every
record of B.

Relation A:
Name Age Sex

Ram 14 M

Sona 15 F

Kim 20 M

Relation B:
ID Course

1 DS

2 DBMS

Output: If relation A has 3 rows and relation B has 2 rows, the Cartesian product A × B will
result in 6 rows.
Name Age Sex ID Course

Ram 14 M 1 DS

Ram 14 M 2 DBMS

Sona 15 F 1 DS

Sona 15 F 2 DBMS

Kim 20 M 1 DS
Name Age Sex ID Course

Kim 20 M 2 DBMS

Explanation: If A has 'n' tuples and B has 'm' tuples then A X B will have 'n*m' tuples.

Derived Operators in Relational Algebra


Derived operators are built using basic operators and include operations like join, intersection,
and division. These operators help perform more complex queries by combining basic
operations to meet specific data retrieval needs.

1. Join Operators
Join operations in relational algebra combine data from two or more relations based on a
related attribute, allowing for more complex queries and data retrieval. Different types of joins
include:
1.1 Inner Join
An inner join combines rows from two relations based on a matching condition and only
returns rows where there is a match in both relations. If a record in one relation doesn't have a
corresponding match in the other, it is excluded from the result. This is the most common type
of join.
a. Conditional Join:
 A conditional join is an inner join where the matching condition can involve any
comparison operator like equals (=), greater than (>), etc.
 Example: Joining Employees and Departments on DepartmentID where Salary >
50000 will return employees in departments with a salary greater than 50,000
b. Equi Join:
 An equi join is a type of conditional join where the condition is specifically equality (=)
between columns from both relations.
 Example: Joining Customers and Orders on CustomerID where both relations have this
column, returning only matching records.
c. Natural Join:
 A natural join automatically combines relations based on columns with the same name
and type, removing duplicate columns in the result. It’s a more efficient way of joining.
 Example: Joining Students and Enrollments where StudentID is common in both, and
the result contains only unique columns.
1.2 Outer Join
An outer join returns all rows from one relation, and the matching rows from the other relation.
If there is no match, the result will still include all rows from the outer relation
with NULL values in the columns from the unmatched relation.
a. Left Outer Join:
 A left outer join returns all rows from the left relation and the matching rows from the right
relation.
 If there is no match, the result will include NULL values for the right relation’s attributes.
 Example: Joining Employees with Departments using a left outer join ensures all
employees are listed, even those who aren't assigned to any department, with NULL values
for the department columns.
b. Right Outer Join:
 A right outer join returns all rows from the right relation and the matching rows from the
left relation.
 If no match exists, the left relation's columns will contain NULL values.
 Example: Joining Departments with Employees using a right outer join includes all
departments, even those with no employees assigned, filling unmatched employee columns
with NULL.
c. Full Outer Join:
 A full outer join returns all rows when there is a match in either the left or right relation.
 If a row from one relation does not have a match in the other, NULL values are included for
the missing side.
 Example: Joining Customers and Orders using a full outer join will return all customers and
orders, even if there’s no corresponding order for a customer or no customer for an order.

2. Set Intersection(∩)
Set Intersection basically allows to fetches only those rows of data that are common between
two sets of relational tables. Set Intersection in relational algebra is the same set intersection
operation in set theory.
Example: Consider the following table of Students having different optional subjects in their
course.

Relation FRENCH
Student_Name Roll_Number

Ram 01

Mohan 02

Vivek 13

Geeta 17

Relation GERMAN
Student_Name Roll_Number

Vivek 13

Geeta 17

Shyam 21

Rohan 25

From the above table of FRENCH and GERMAN, the Set Intersection is used as follows:
π(Student_Name)(FRENCH ∩ π(Student_Name)(GERMAN)
Output:
Student_Name

Vivek

Geeta

Explanation: The only constraint in the Set Difference between two relations is that both
relations must have the same set of Attributes.

3. Division (÷)
The Division Operator is used to find tuples in one relation that are related to all tuples in
another relation. It’s typically used for "for all" queries.

Student_Course (Dividend Table):


Student_ID Course_ID

101 C1
Student_ID Course_ID

101 C2

102 C1

103 C1

103 C2

Course (Divisor Table):


Course_ID

C1

C2

Example: Query is to find students who are enrolled in all courses listed in the Course table.
In this case, students must be enrolled in both C1 and C2.
Student_Course(Student_ID, Course_ID)÷ Course(Course_ID)
Output:
Student_ID

101

103

Relational calculus

Relational calculus, a non-procedural query language in database management systems, guides


users on what data is needed without specifying how to obtain it. Commonly utilized in
commercial relational languages like SQL-QBE and QUEL, relational calculus ensures a focus
on desired data without delving into procedural details, promoting a more efficient and abstract
approach to querying in relational databases.

What is Relational Calculus?

Before understanding Relational calculus in DBMS, we need to understand Procedural


Language and Declarative Langauge.

1. Procedural Language - Those Languages which clearly define how to get the required
results from the Database are called Procedural Language. Relational algebra is a
Procedural Language.
2. Declarative Language - Those Language that only cares about What to get from the
database without getting into how to get the results are called Declarative
Language. Relational Calculus is a Declarative Language.

How Relational Calculus Works in DBMS

In general terms, relational calculus serves as a logical query language in a database management
system (DBMS). It enables users to phrase queries in a more formal manner, focusing on what
data needs to be retrieved from the database rather than how to go about the retrieval. Here’s
how relational calculus functions in a DBMS:

1. Query Expression:

 Users write queries using relational calculus expressions. These expressions consist of
logical conditions or predicates that specify the data requirements.
 For Tuple Relational Calculus (TRC), queries are expressed in the form { t | P(t) }, where
t represents a tuple, and P(t) is a condition that the tuple must satisfy.
 For Domain Relational Calculus (DRC), queries are expressed as {<x1, x2, …, xn> |
P(x1, x2, …, xn)}, where <x1, x2, …, xn> represents attribute values, and P is the
condition.

2. Evaluation of Conditions:

 The DBMS evaluates the conditions specified in the query. It checks which records in the
database satisfy the logical predicates.
 For TRC, this involves filtering entire tuples (rows) based on the conditions. For DRC, it
involves filtering attribute values within those tuples.

3. Fetching Data from Relations (Tables):


 The relational calculus expression is applied to the relevant database relations (tables).
 The DBMS scans the tables to find the tuples or attribute values that meet the specified
conditions.

4. Logical Optimization:

 Before executing the query, the DBMS may optimise the logical expression to improve
performance.
 This step involves rewriting the logical conditions or rearranging operations without
changing the result, making the query execution faster.

5. Result Compilation:

 The data that satisfies the conditions is collected and compiled into a result set.
 For TRC, the result includes tuples that meet the criteria. For DRC, the result contains
specific attribute values that match the condition.

6. Displaying Results:

 Finally, the DBMS displays the output of the query to the user.
 The results can be presented as tables (for TRC) or as a list of values (for DRC),
depending on the nature of the query.

So Relational Calculus is a Declarative Language that uses Predicate Logic or First-Order Logic
to determine the results from Database.

Types of Relational Calculus in DBMS

Relational Calculus is of Two Types:

1. Tuple Relational Calculus (TRC)


2. Domain Relational Calculus (DRC)
Tuple Relational Calculus (TRC)

Tuple Relational Calculus in DBMS uses a tuple variable (t) that goes to each row of the table
and checks if the predicate is true or false for the given row. Depending on the given predicate
condition, it returns the row or part of the row.

The Tuple Relational Calculus expression Syntax

{t \| P(t)}

Where t is the tuple variable that runs over every Row, and P(t) is the predicate logic expression
or condition.

Let's take an example of a Customer Database and try to see how TRC expressions work.

Customer Table
Customer_id Name Zip code

1 Rohit 12345

2 Rahul 13245

3 Rohit 56789

4 Amit 12345.

Example 1: Write a TRC query to get all the data of customers whose zip code is 12345.

TRC Query: {t \| t ∈ Customer ∧ [Link] = 12345} or TRC Query: {t \| Customer(t) ∧


t[Zipcode] = 12345 }

Workflow of query - The tuple variable "t" will go through every tuple of the Customer table.
Each row will check whether the Cust_Zipcode is 12345 or not and only return those rows that
satisfies the Predicate expression condition.

The TRC expression above can be read as "Return all the tuple which belongs to the
Customer Table and whose Zipcode is equal to 12345."

Result of the TRC expression above:


Customer_id Name Zip code

1 Rohit 12345
Customer_id Name Zip code
4. Amit 12345
1 Rohit 12345

Example 2: Write a 2 Rahul 13245 TRC query to get the


customer id of all the Customers.
3 Rohit 56789
TRC query: { t \| ∃s (s ∈ Customer ∧
4 Amit 12345
s.Customer_id = t.customer_id) }

Result of the TRC Query:

Customer_id

Domain Relational Calculus (DRC)

Domain Relational Calculus uses domain Variables to get the column values required from the
database based on the predicate expression or condition.

The Domain realtional calculus expression syntax:

{<x1,x2,x3,x4...> \| P(x1,x2,x3,x4...)}

where,

<x1,x2,x3,x4...> are domain variables used to get the column values required,
and P(x1,x2,x3...) is predicate expression or condition.

Let's take the example of Customer Database and try to understand DRC queries with some
examples.

Customer Table
Example 1: Write a DRC query to get the data of all customers with Zip code 12345.

DRC query: {<x1,x2,x3> \| <x1,x2> ∈ Customer ∧ x3 = 12345 }

Workflow of Query: In the above query x1,x2,x3 (ordered) refers to the attribute or column
which we need in the result, and the predicate condition is that the first two domain variables x1
and x2 should be present while matching the condition for each row and the third domain
variable x3 should be equal to 12345.

Result of the DRC query will be:

Customer_id Name Zip code

1 Rohit 12345

4 Amit 12345

2: Write a DRC query to get the customer id of all the customer.

DRC Query: { <x1> \| ∃ x2,x3(<x1,x2,x3> ∈ Customer ) }

Result of the above Query will be:

Customer_id

4
SQL Commands
SQL commands are fundamental building blocks used to perform given operations on database.
The operations include queries of data. creating a table, adding data to tables, dropping the table,
modifying the table and set permission for users.
SQL Commands are mainly categorized into five categories:

1. DDL - Data Definition Language


DDL (Data Definition Language) consists of SQL commands that can be used for defining,
altering and deleting database structures such as tables, indexes and schemas. It simply deals
with descriptions of the database schema and is used to create and modify the structure of
database objects in the database.

Command Description Syntax

Create database or its objects (table, CREATE TABLE table_name


CREATE index, function, views, store (column1 data_type, column2
procedure and triggers) data_type, ...);

DROP Delete objects from the database DROP TABLE table_name;

ALTER TABLE table_name ADD


ALTER Alter the structure of the database COLUMN column_name
data_type;
Command Description Syntax

Remove all records from a table,


TRUNCATE including all spaces allocated for the TRUNCATE TABLE table_name;
records are removed

Add comments to the data COMMENT ON TABLE


COMMENT
dictionary table_name IS 'comment_text';

RENAME TABLE
Rename an object existing in the
RENAME old_table_name TO
database
new_table_name;

Example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
hire_date DATE
);
In this example, a new table called employees is created with columns for employee ID, first
name, last name and hire date.

Creating Tables
A table is the core structure of a database where data is stored in rows and columns. While
creating a table, you must define:

Column names
Data types (e.g., INT, VARCHAR, DATE)
Constraints (e.g., PRIMARY KEY, NOT NULL, UNIQUE, DEFAULT, FOREIGN KEY)
Syntax:

CREATE TABLE table_name (


column1 datatype constraint,
column2 datatype constraint,
...
);

Example: Creating a Student Table


Here, we are creating a table named Student to store student details like ID, name, subject, year
and marks.

CREATE TABLE Student (


StudentID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Subject VARCHAR(50),
Year INT,
Marks INT
);
Explanation: In this table, StudentID is the unique identifier (Primary Key), Name must not be
empty, Subject stores the subject name, Year represents the study year and Marks stores the
marks scored by the student.

1. Verifying Table Creation


After running the CREATE TABLE query, the system shows a success message like Table
created successfully. To confirm that the table exists, we can list all tables in the current
database using:

SHOW TABLES;
This will display all the tables created inside the database and from here you can confirm that
Student table has been successfully created.

2. Deleting a Table
If you no longer need a table, use:

DROP TABLE Student;


Explanation: This removes the Student table permanently from the database.

DML - Data Manipulation Language

DML commands are used to manipulate the data stored in database tables. With DML, you can
insert new records, update existing ones, delete unwanted data or retrieve information. Its is used
to fetch data from the database. The main command is SELECT, which retrieves records based
on the query. The output is returned as a result set (a temporary table) that can be viewed or used
in applications.
Command Description Syntax

INSERT INTO table_name (column1, column2, ...)


INSERT Insert data into a table
VALUES (value1, value2, ...);

Update existing data UPDATE table_name SET column1 = value1,


UPDATE
within a table column2 = value2 WHERE condition;

Delete records from a


DELETE DELETE FROM table_name WHERE condition;
database table

Command Description Syntax

It is used to retrieve data from the SELECT column1, column2, ...FROM


SELECT
database table_name WHERE condition;

Indicates the table(s) from which SELECT column1


FROM
to retrieve data. FROM table_name;

SELECT column1
Filters rows before any grouping
WHERE FROM table_name
or aggregation
WHERE condition;

SELECT column1,
GROUP Groups rows that have the same AVG_FUNCTION(column2)
BY values in specified columns. FROM table_name
GROUP BY column1;

SELECT column1,
AVG_FUNCTION(column2)
HAVING Filters the results of GROUP BY FROM table_name
GROUP BY column1
HAVING condition;

DISTINCT Removes duplicate rows from SELECT DISTINCT column1,


the result set column2, ...
Command Description Syntax

FROM table_name;

SELECT column1
ORDER Sorts the result set by one or
FROM table_name
BY more columns
ORDER BY column1 [ASC | DESC];

By default, it sorts in ascending SELECT * FROM table_name LIMIT


LIMIT
order unless specified as DESC number;

SQL INSERT INTO Statement

Last Updated : 03 Nov, 2025

The SQL INSERT INTO statement is used to add new records into a table. It allows inserting
data into all columns or specific ones, depending on the requirement.

an insert a single row or multiple rows at once.

Supports inserting data directly or from another table using a subquery.

1. Inserting Data into All Columns

This method is used when you want to insert data into all columns of a table without specifying
column names. We simply provide the values for each column, in the same order that the
columns are defined in the table.

Syntax:

INSERT INTO table_name


VALUES (value1, value2, value3, ...);
table_name: name of the table where data will be inserted
value1, value2... : values that correspond to each column in order.
Example: Let’s see how the INSERT INTO statement works with practical examples.
CREATE DATABASE StudentDB;

USE StudentDB;

CREATE TABLE Student (


ROLL_NO INT PRIMARY KEY,
NAME VARCHAR(50),
ADDRESS VARCHAR(100),
PHONE VARCHAR(15),
AGE INT );

INSERT INTO Student (ROLL_NO, NAME, ADDRESS, PHONE, AGE)


VALUES (1, 'Liam', 'New York', 'xxxxxxxxxx', 18),
(2, 'Sophia', 'Berlin', 'xxxxxxxxxx', 18),
(3, 'Akira', 'Tokyo', 'xxxxxxxxxx', 20),
(4, 'Carlos', 'Tokyo', 'xxxxxxxxxx', 18);

Output

ROLL_NO NAME ADDRESS PHONE AGE

1 Liam New York xxxxxxxxxx 18

2 Sophia Berlin xxxxxxxxxx 18

3 Akira Tokyo xxxxxxxxxx 20

4 Carlos Tokyo xxxxxxxxxx 18

If we don’t want to specify the column names (and you’re inserting data into all columns), we
can directly insert values in the order they appear in the table structure. Here's an example:

Query:

INSERT INTO Student


VALUES (5, 'Isabella', 'Rome', 'xxxxxxxxxx', 19);
Output

ROLL_NO NAME ADDRESS PHONE AGE

1 Liam New York xxxxxxxxxx 18

2 Sophia Berlin xxxxxxxxxx 18

3 Akira Tokyo xxxxxxxxxx 20

4 Carlos Tokyo xxxxxxxxxx 18

5 Isabella Rome xxxxxxxxxx 19

2. Inserting Data into Specific Columns

In some cases, you might want to insert data into only certain columns, leaving the others empty
or with default values. In such cases, we can specify the column names explicitly.

Syntax

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);

Parameters:

table_name: name of the table.


column1, column2..: name of first column, second column.
value1, value2, value3..: the values for each specified column of the new record.

Example: Let’s say we only want to insert the student's ID, name, and age into the Student
table, and leave the address and phone number as NULL (the default value).

INSERT INTO Student (ROLL_NO, NAME, AGE)


VALUES (6, 'Hiroshi', 19);

Output
ROLL_NO NAME ADDRESS PHONE AGE

1 Liam New York xxxxxxxxxx 18

2 Sophia Berlin xxxxxxxxxx 18

3 Akira Tokyo xxxxxxxxxx 20

4 Carlos Tokyo xxxxxxxxxx 18

5 Isabella Rome xxxxxxxxxx 19

6 Hiroshi NULL NULL 19

Inserting Multiple Rows at Once

Instead of running multiple INSERT INTO commands, you can insert multiple rows into a table
in a single query. This is more efficient and reduces the number of database operations.

Syntax

INSERT INTO table_name (column1, column2, ...)


VALUES (value1, value2, ...), (value1, value2, ...), (value1, value2, ...);

Example: If we want to add multiple students to Student table in one go, query would look like
this:
INSERT INTO Student (ROLL_NO, NAME, ADDRESS, PHONE, AGE)
VALUES
(7, 'Mateo Garcia', 'Madrid', 'xxxxxxxxxx', 15),
(8, 'Hana Suzuki', 'Osaka', 'xxxxxxxxxx', 18),
(9, 'Oliver Jensen', 'Copenhagen', 'xxxxxxxxxx', 17),
(10, 'Amelia Brown', 'London', 'xxxxxxxxxx', 17);

Output
ROLL_NO NAME ADDRESS PHONE AGE

1 Liam New York xxxxxxxxxx 18

2 Sophia Berlin xxxxxxxxxx 18

3 Akira Tokyo xxxxxxxxxx 20

4 Carlos Tokyo xxxxxxxxxx 18

5 Isabella Rome xxxxxxxxxx 19

6 Hiroshi NULL NULL 19

7 Mateo Garcia Madrid xxxxxxxxxx 15

8 Hana Suzuki Osaka xxxxxxxxxx 18

9 Oliver Jensen Copenhagen xxxxxxxxxx 17

10 Amelia Brown London xxxxxxxxxx 17

Inserting Data from One Table into Another Table

We can also copy data from one table into another table using the INSERT INTO SELECT
statement. This is very useful when we want to move or replicate data from one table to another
without manually typing all the data.

Here, we are using below table OldStudent as another table and we will insert its rows into
Student table using different methods.
ROLL_NO NAME ADDRESS PHONE AGE

101 Arjun Mehta Mumbai 9999999999 21

102 Emily Clark Sydney 8888888888 22

103 Kenji Sato Tokyo 7777777777 19

Method 1: Insert All Columns from Another Table

Inserts every column from source table into destination table


INSERT INTO target_table
SELECT * FROM source_table;

Example: If you want to copy all data from the OldStudent table into the Student table, use this
query:
INSERT INTO Student
SELECT * FROM OldStudent;

Output
ROLL_NO NAME ADDRESS PHONE AGE

1 Liam New York xxxxxxxxxx 18

2 Sophia Berlin xxxxxxxxxx 18

3 Akira Tokyo xxxxxxxxxx 20

4 Carlos Tokyo xxxxxxxxxx 18

5 Isabella Rome xxxxxxxxxx 19

6 Hiroshi NULL NULL 19

7 Mateo Garcia Madrid xxxxxxxxxx 15


ROLL_NO NAME ADDRESS PHONE AGE

8 Hana Suzuki Osaka xxxxxxxxxx 18

9 Oliver Jensen Copenhagen xxxxxxxxxx 17

10 Amelia Brown London xxxxxxxxxx 17

101 Arjun Mehta Mumbai 9999999999 21

102 Emily Clark Sydney 8888888888 22

103 Kenji Sato Tokyo 7777777777 19

Method 2: Insert Specific Columns from Another Table

Allows inserting only selected columns from the source table.


INSERT INTO target_table (col1, col2, ...) SELECT col1, col2, ...

FROM source_table;

Example: Let’s say we want to copy only the Name and Age columns from OldStudent into
Student:
INSERT INTO Student (Name, Age) SELECT Name, Age
FROM OldStudent;

Output

ROLL_NO NAME ADDRESS PHONE AGE

1 Liam New York xxxxxxxxxx 18

2 Sophia Berlin xxxxxxxxxx 18

3 Akira Tokyo xxxxxxxxxx 20

4 Carlos Tokyo xxxxxxxxxx 18


ROLL_NO NAME ADDRESS PHONE AGE

5 Isabella Rome xxxxxxxxxx 19

6 Hiroshi NULL NULL 19

7 Mateo Garcia Madrid xxxxxxxxxx 15

8 Hana Suzuki Osaka xxxxxxxxxx 18

9 Oliver Jensen Copenhagen xxxxxxxxxx 17

10 Amelia Brown London xxxxxxxxxx 17

NULL Arjun Mehta NULL NULL 21

NULL Emily Clark NULL NULL 22

NULL Kenji Sato NULL NULL 19

Note: Columns not included in INSERT statement (ROLL_NO, ADDRESS, PHONE) are
automatically filled with NULL in target table.

Method 3: Insert Specific Rows Based on Condition

You can also insert specific rows based on a condition by using the WHERE clause with the
SELECT statement.
INSERT INTO target_table
SELECT * FROM source_table
WHERE condition;

Example: If we want to copy only students older than 20 years from OldStudent to
Student, we would write:
INSERT INTO Student
SELECT * FROM OldStudent
WHERE Age > 20;
Output

ROLL_NO NAME ADDRESS PHONE AGE

1 Liam New York xxxxxxxxxx 18

2 Sophia Berlin xxxxxxxxxx 18

3 Akira Tokyo xxxxxxxxxx 20

4 Carlos Tokyo xxxxxxxxxx 18

5 Isabella Rome xxxxxxxxxx 19

6 Hiroshi NULL NULL 19

7 Mateo Garcia Madrid xxxxxxxxxx 15

8 Hana Suzuki Osaka xxxxxxxxxx 18

9 Oliver Jensen Copenhagen xxxxxxxxxx 17

10 Amelia Brown London xxxxxxxxxx 17

101 Arjun Mehta Mumbai 9999999999 21

102 Emily Clark Sydney 8888888888 22

SQL UPDATE Statement

The SQL UPDATE statement is used to modify existing records in a table. It allows you to
change one or more column values for specific rows using the WHERE clause. Without a
WHERE condition, all rows in the table will be updated.
Example: First, we will create a demo SQL database and table, on which we will use the
UPDATE Statement command.

Query:

UPDATE Employees SET Salary = 65000 WHERE Name = 'Bob';

Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2,...
WHERE condition

table_name: Name of the table you want to update.

SET: The column(s) you want to update and their new values.

WHERE: Filters the specific rows you want to update.

Note: The SET keyword assigns new values to columns, while the WHERE clause selects
which rows to update. Without WHERE, all rows will be updated.

Examples of SQL UPDATE Statement

Let’s begin by creating a Customer table with some sample data. This table contains each
customer's unique ID, name, last name, phone number and country. We will use it to
demonstrate how the UPDATE statement works in SQL.
Query:
CREATE TABLE Customer (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age INT,
Phone VARCHAR(15)
);

-- Insert sample data


INSERT INTO Customer (CustomerID, CustomerName, LastName, Country, Age, Phone)
VALUES
(1, 'Liam', 'Brown', 'United Kingdom', 25, '441234567890'),
(2, 'Sofia', 'Martinez', 'Spain', 23, '341234567890'),
(3, 'Akira', 'Tanaka', 'Japan', 26, '811234567890'),
(4, 'Hans', 'Müller', 'Germany', 27, '491234567890'),
(5, 'Olivia', 'Dubois', 'France', 24, '331234567890');

Output:

Example 1: Update Single Column Using UPDATE Statement


We have a Customer table and we want to Update the CustomerName where the Age is 23.
Query:
UPDATE Customer
SET CustomerName = 'Isabella'
WHERE Age = 23;
Output:
Explanation:
 The query updates the CustomerName to 'Isabella'
 It only affects the row where Age = 23
 Used to modify existing data in a specific record.

Example 2: Updating Multiple Columns using UPDATE Statement


We need to update both the CustomerName and Country for a specific CustomerID.
Query:
UPDATE Customer
SET CustomerName = 'John',
Country = 'Spain'
WHERE CustomerID = 1;
Output:

Explanation:
 The query targets the row where CustomerID = 1.
 It updates CustomerName to 'John' and Country to 'Spain'.
 Both columns are updated simultaneously in a single SQL statement.
Note: For updating multiple columns we have used comma(,) to separate the names and values of
two columns.
Example 3: Omitting WHERE Clause in UPDATE Statement
If we accidentally omit the WHERE clause, all the rows in the table will be updated, which is a
common mistake. Let’s update the CustomerName for every record in the table:
Query:
UPDATE Customer
SET CustomerName = 'ALice';
Output

Explanation:

 The query updates every row in the Customer table.


 It sets the CustomerName column to 'Alice' for all records.

 Since there is no WHERE clause, the change applies to the entire table.

SQL DELETE Statement

The SQL DELETE statement is used to remove specific rows from a table while keeping the
table structure intact. It is different from DROP, which deletes the entire table.

 It removes rows based on conditions.


 Retains table schema, constraints, and indexes.
 Can delete a single row or all rows.

Example: First, we create a demo SQL database and table, on which we will use the SQL
DELETE command.

Query:
DELETE FROM Employees
WHERE EmployeeID = 5;
Output:

DELETE FROM table_name

WHERE some_condition;

Some_condition: A condition used to filter the rows you want to delete.

table_name: The name of the table from which you want to delete the rows.

Note: We can delete single or multiple records using the WHERE clause; if it’s omitted, all
records in the table are removed.

Examples of SQL DELETE Statement

Assume we have created a table named GFG_Employee in SQL, which contains the personal
details of the Employee including their id, name, email and department etc. as shown below.
CREATE TABLE GFG_Employees (
id INT PRIMARY KEY,
name VARCHAR (20) ,
email VARCHAR (25),
department VARCHAR(20)
);

INSERT INTO GFG_Employees (id, name, email, department) VALUES


(1, 'Jessie', 'jessie23@[Link]', 'Development'),
(2, 'Praveen', 'praveen_dagger@[Link]', 'HR'),
(3, 'Bisa', 'dragonBall@[Link]', 'Sales'),
(4, 'Rithvik', 'msvv@[Link]', 'IT'),
(5, 'Suraj', 'srjsunny@[Link]', 'Quality Assurance'),
(6, 'Om', 'OmShukla@[Link]', 'IT'),
(7, 'Naruto', 'uzumaki@[Link]', 'Development');

Select * From GFG_Employees

Output:

Example 1: Deleting Single Record

We can use the DELETE statement with a condition to delete a specific row from a table. The
WHERE clause ensures only the intended record is removed. We can delete the records named
Rithvik by using the below query:

Query:

DELETE FROM GFG_Employees


WHERE NAME = 'Rithvik';
Output:

Example 2: Deleting Multiple Records

To delete multiple records, you can specify a condition that matches several rows. Let's delete
the rows from the table GFG_Employees where the department is "Development". This will
delete 2 rows (the first row and the seventh row).

Query:
DELETE FROM GFG_Employees
WHERE department = 'Development';

Output

Example 3: Delete All Records from a Table

If we need to delete all records from the table, we can omit the WHERE clause, or alternatively
use the DELETE statement with an asterisk (*) to denote all rows.

Query:
DELETE FROM GFG_Employees;
Or
DELETE * FROM GFG_Employees;

Output:

All of the records in the table will be deleted, there are no records left to display. The table
GFG_Employees will become empty.

Rolling Back DELETE Operations

Since the DELETE statement is a DML operation, it can be rolled back when executed in a
statement. If you accidentally delete records or need to repeat the process, you can use the
ROLLBACK command.

Query:

BEGIN TRANSACTION;

DELETE FROM GFG_Employees;

WHERE department = 'Development';

-- If needed, you can rollback the deletion

ROLLBACK;
Explanation: The ROLLBACK command will undo the changes made by the DELETE
statement, effectively restoring the records that were deleted during the transaction.

SQL SELECT Query

The SQL SELECT statement retrieves data from one or more tables and returns it as a tabular
result set of rows and columns. You can fetch all columns with * or choose specific columns,
and narrow results using WHERE filters. Queries can be ordered with ORDER BY, grouped and
aggregated with GROUP BY/HAVING, and combined across tables using JOINs.

Syntax:
SELECT column1,column2.... FROM table_name;
column1, column2: columns you want to retrieve.
table_name: name of the table you're querying.

Examples of SELECT Statement

Let us start by creating a sample table that we will use for our examples. We will also insert
some sample data to make the demonstration more practical.
CREATE TABLE Customer (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age INT(2),
Phone VARCHAR(10) );

INSERT INTO Customer (CustomerID, CustomerName, LastName, Country, Age, Phone)


VALUES (1, 'Liam', 'Smith', 'USA', 23, 'xxxxxxxxxx'),
(2, 'Sophia', 'Miller', 'USA', 21, 'xxxxxxxxxx'),
(3, 'Akira', 'Tanaka', 'Japan', 24, 'xxxxxxxxxx'),
(4, 'Carlos', 'Hernandez', 'USA', 21, 'xxxxxxxxxx'),
(5, 'Isabella', 'Rossi', 'Italy', 22, 'xxxxxxxxxx');

Output

CustomerID CustomerName LastName Country Age Phone

1 Liam Smith USA 23 xxxxxxxxxx

2 Sophia Miller USA 21 xxxxxxxxxx

3 Akira Tanaka Japan 24 xxxxxxxxxx

4 Carlos Hernandez USA 21 xxxxxxxxxx


CustomerID CustomerName LastName Country Age Phone

5 Isabella Rossi Italy 22 xxxxxxxxxx

Example 1: Select Specific Columns


In this example, we will demonstrate how to retrieve specific columns from the Customer table.
Here we will fetch only CustomerName and LastName for each record.

Query:

SELECT CustomerName, LastName FROM Customer;


Output:
CustomerName LastName

Liam Smith

Sophia Miller

Akira Tanaka

Carlos Hernandez

Isabella Rossi

Example 2: Select All Columns

In this example, we will fetch all the fields from table Customer:

Query
SELECT * FROM Customer;

Example 3: SELECT Statement with WHERE Clause

Suppose we want to see table values with specific conditions then WHERE Clause is used with
select statement. In this example, filter customers who are 21 years old.
Query:
SELECT CustomerName
FROM Customer
where Age = '21';

Output

CustomerName

Sophia

Carlos

Example 4: SELECT with GROUP BY Clause

In this example, we will use SELECT statement with GROUP BY Clause to group rows and
perform aggregation. Here, we will count the number of customers from each country.

Query:
SELECT Country, COUNT(*) AS customer_count
FROM Customer
GROUP BY Country;

Output
Country customer_count

USA 3

Japan 1

Italy 1

Example 5: SELECT with DISTINCT Clause

In this example, we will use DISTINCT keyword to return only unique values from a column.
Here, we will fetch unique countries from the Customer table.
Query:

SELECT DISTINCT Country FROM Customer;


Output:
Country

USA

Japan

Italy

Example 6: SELECT Statement with HAVING Clause

The HAVING clause is used to filter results after applying GROUP BY. In this example, we will
find countries that have 2 or more customers in the Customer table.

Query:
SELECT Country, COUNT(*) AS customer_count
FROM Customer
GROUP BY Country
HAVING COUNT(*) >= 2;

Output
Country customer_count

USA 3

Example 7: SELECT Statement with ORDER BY clause

In this example, we will use SELECT Statement with ORDER BY clause. Here, Sort results by
Age in descending order.

Query:
SELECT * FROM Customer ORDER BY Age DESC;
Output:
ustomerID CustomerName LastName Country Age Phone

3 Akira Tanaka Japan 24 xxxxxxxxxx

1 Liam Smith USA 23 xxxxxxxxxx

5 Isabella Rossi Italy 22 xxxxxxxxxx

2 Sophia Miller USA 21 xxxxxxxxxx

4 Carlos Hernandez USA 21 xxxxxxxxxx

WHERE Clause

We will create a basic employee table structure in SQL for performing all the where clause
operation.

Example 1: Where Clause with Logical Operators

To fetch records of Employee with age equal to 24.

Query:

SELECT * FROM Emp1 WHERE Age=24;


Output:

Example 2: WHERE with Comparison Operators

To fetch the EmpID, Name and Country of Employees with Age greater than 21.
Query:

SELECT EmpID, Name, Country FROM Emp1 WHERE Age > 21;
Output:

Example 3: Where Clause with BETWEEN Operator

The BETWEEN operator is used to filter records within a specified range, and it includes both
the start and end values. In this example, we want to find employees whose age is between 22
and 24, including both 22 and 24.

Query:
SELECT * FROM Emp1
WHERE Age BETWEEN 22 AND 24;

Output:

Example 4: Where Clause with LIKE Operator

It is used to fetch filtered data by searching for a particular pattern in the where clause. In this
example we want to find records of Employees where Name starts with the letter. The
'%'(wildcard) signifies the later characters here which can be of any length and value.
Query:

SELECT *

FROM Employee WHERE Name LIKE 'L%';


Output:

Example 5: Where Clause with IN Operator

It is used to fetch the filtered data same as fetched by '=' operator just the difference is that here
we can specify multiple values for which we can get the result set. Here we want to find the
Names of Employees where Age is 21 or 23.

Query:

SELECT Name FROM Emp1 WHERE Age IN (21,23);


Output:

Operators Used in WHERE Clause

Operator Description

> Greater Than

>= Greater than or Equal to


Operator Description

< Less Than

<= Less than or Equal to

= Equal to

<> Not Equal to

BETWEEN In an inclusive Range

LIKE Search for a pattern

To specify multiple
IN possible values for a
column

Common questions

Powered by AI

SQL's flexibility in specifying all columns or specific columns in the INSERT INTO statement enhances database operations by allowing tailored data insertion. Inserting into all columns is direct, requiring values for each field, which is suitable for complete data entries . Specifying columns offers efficiency by enabling partial data insertion, useful for datasets with optional or default fields, reducing unnecessary input when certain fields are irrelevant or optional, thus improving operation speed and accuracy in dynamic data environments .

The SQL INSERT INTO statement is used to add new records to a table, supporting multiple variations such as inserting into all columns, specific columns, multiple rows simultaneously, and data from another table. When inserting into all columns, values are provided in the same order as the table columns . Specifying columns allows selective data insertion, useful for leaving some fields empty or with default values. Inserting multiple rows reduces operations and improves efficiency, while using a SELECT statement copies data from another table, enabling data replication or transfer .

Relational algebra is a procedural query language, meaning it defines a sequence of operations to perform to get the desired result. It uses operators like selection, projection, union, etc., and each operation is applied in a specific order that the user dictates, resembling a recipe or plan for query execution . In contrast, declarative languages like relational calculus describe what data is desired without specifying a procedure for retrieving it. This non-procedural approach focuses on the outcome rather than the execution method, offering more abstraction and efficiency in querying relational databases .

Set operations like union and difference in relational algebra facilitate complex data retrieval and manipulation by combining or comparing datasets. The union operation merges data from two relations into a single set, including all distinct tuples from both, which is useful for consolidating data sources . The difference operation subtracts tuples of one relation from another, allowing users to isolate data differences or exclusive records. These operations enhance the ability to cross-analyze and integrate data from different tables, exemplified by merging student lists from two semesters via union or finding disenrolled students using difference .

Logical optimization in relational calculus involves rewriting and rearranging the logical conditions or operations in a query without altering its outcome, aiming to enhance query performance. This optimization ensures faster execution by minimizing the computational resources necessary for query processing, which is particularly valuable in large databases where efficient query execution can significantly affect overall system performance. By optimizing the logical expressions, the DBMS can reduce the execution time, thereby improving the database's responsiveness .

The declarative nature of relational calculus allows users to specify the desired results without detailing the procedure to obtain these results, thereby simplifying query formulation and focusing on the "what" rather than the "how." This abstraction enhances ease of use and makes queries more straightforward to write and understand, as it removes the complexity associated with specifying an execution order of operations .

Tuple Relational Calculus (TRC) uses tuple variables and evaluates conditions on full rows, while Domain Relational Calculus (DRC) operates on domain variables, checking conditions for specific attribute values . For instance, a TRC query to retrieve customer details with a zip code of 12345 is expressed as {t | Customer(t) ∧ t[Zipcode] = 12345} . Conversely, a DRC query to find names and ages of a customer could be {<Name, Age> | Customer(x, Name, y, Age)} which checks conditions on the attributes Name and Age .

Relational algebra serves as a foundational framework for formulating query evaluation plans in relational databases by providing a series of operators that can be combined procedurally to express complex queries. This capability allows the system to decompose a high-level query into a structured set of executable steps, ensuring systematic data retrieval and manipulation . The clarity and structure afforded by relational algebra's procedural nature enable efficient representation and optimization of these plans, as each operator corresponds to specific operations the database must execute .

The projection operation in relational algebra is significant as it retrieves specific columns from a table, effectively reducing dimensionality and focusing on specific attributes needed for analysis . In contrast, selection filters rows based on conditions, retaining entire tuples that match the criteria. While projection condenses attributes, selection narrows down data entries, allowing combined use to extract precisely targeted information—such as selecting students with particular grades and projecting their names and IDs for a focused result .

The division operation in relational algebra is used to find tuples in one relation that relate to all tuples in another relation, resembling the "for all" concept . For example, considering a Student_Course table listing student enrollments and a Course table with available courses, the division can identify students enrolled in all courses. Here, dividing Student_Course by Course where Student_ID ÷ Course_ID yields students like 101 and 103, who are enrolled in every course listed in the Course table .

You might also like