Introduction to SQL Basics and Features
Introduction to SQL Basics and Features
Introduction to SQL
Presented by
Chaithra C S
Assistant Professor
Dept. of Computer Applications
JSSSTU, Mysuru
Syllabus
CO4: Apply SQL to handle all the basic and advanced
operations on DBMS.
Introduction to SQL
Overview of the SQL Query Overview of the SQL Query Language, SQL Data Definition, Basic
Structure of SQL Queries, Additional Basic Operations, Set Operations, Null Values, Aggregate
Functions, Nested Sub queries, Modification of the Database. Intermediate SQL: Join Expressions, Views,
Transactions, Integrity Constraints, SQL Data Types and Schemas, Authorization. Embedded and
Dynamic SQL, Data Integrity and constraints, Further data definition commands and SQL Queries with
examples.
Self-Learning and Teamwork
• Additional Basic Operations of SQL
• Further data definition commands and SQL Queries with examples.
Introduction
Overview of the SQL Query Language
◦ Structured Query Language (SQL) is the most widely used language for managing and manipulating
relational databases. Although it is often referred to as a query language, SQL provides much more than just
query capabilities. It encompasses commands for data definition, data manipulation, integrity constraints,
view management, transaction control, and access authorization.
◦ SQL (Structured Query Language):-
◦ It is non-procedural language. It is international standard language for creating or manipulating relational
database. SQL is used to perform operations on the records stored in the database such as updating
records, deleting records, creating and modifying tables.
◦ IBM developed the original version of SQL, originally called Structured English Query Language (SEQUEL),
as part of the System R project in the early 1970s. The Sequel language has evolved since then, and its
name has changed to SQL (Structured Query Language). SQL was developed at IBM by Donald D.
Chamberlin and Raymond F. Boyce in the 1970s for use in system R. Structured Query
Language) is a domain- specific language used in programming and designed for managing data held in a
relational database management system (RDBMS), SQL is often pronounced SEQUEL.
Characteristics of SQL
◦ Oriented towards relational databases: - SQL is oriented specifically around relational databases.
◦ Can operate on Multiple Groups:-SQL commands can operate on several groups of tables as
single objects.
◦ Uses temporary tables: - SQL allows use of temporary tables. Temporary tables are used for
storing intermediate result.
◦ Suitable for Client/Server Environment:- SQL is well-suited to a client server environment,
where the DBMS resides on a server and services the client requests.
◦ Transaction Management: - SQL provides a flexible transaction management. A transaction is a
group of SQL statements that succeed or fail as a group. If any one of the SQL statements fails, the
transaction is aborted.
◦ Constraint Specification: - SQL allows one to specify constraints. Constraints are the rules for
restricting the values that can be placed in a table column.
◦ Privileges Granting:- Privileges can be granted or denied using SQL commands.
Advantages of SQL
There are the following advantages of SQL:
◦ High speed: - Using the SQL queries, the user can quickly and efficiently retrieve a large amount of
records from a database.
◦ Easy to learn and understand: - SQL mainly consists of English Statements and it is very easy to
learn and understand a SQL query.
◦ Portability:-SQL can be used in laptop, PCs, server and even some mobile phones.
◦ Interactive language: - SQL is a domain language used to communicate with the database. It is also
used to receive answers to the complex questions in seconds.
◦ Multiple data view: - Using the SQL language, the users can make different views of the database
structure.
◦ Supports Object Based Programming:-SQL supports the latest object based programming and
is highly flexible.
Disadvantages of SQL
◦ Partial Control: The programmers who use SQL don’t have a full control over the database
because of the hidden business rules.
◦ Implementation: Some of the databases go to the proprietary extensions to standard SQL for
ensuringthe vendor lock-in.
◦ Cost: The operating cost of some SQL versions makes it difficult for some programmers to access it.
Historical Background:
◦ SQL was originally developed by IBM in the early 1970s as part of the System R project under
the name SEQUEL (Structured English Query Language). Later, the language was renamed SQL
(Structured Query Language). Since then, SQL has become the de facto standard for relational
database systems, supported by almost all commercial and open-source DBMSs such as Oracle,
MySQL, PostgreSQL, SQL Server, and DB2.
◦ To ensure standardization, the American National Standards Institute (ANSI) and the
International Organization for Standardization (ISO) published official standards:
◦ SQL-86 (1986) – the first official standard.
◦ SQL-89 (1989) – an extended version.
◦ SQL-92 (1992) – a major revision.
◦ SQL:1999, SQL:2003, SQL:2006, and SQL:2008 – which successively added new features such as
object-oriented capabilities, triggers, recursive queries, and data analytics extensions.
◦ Despite the existence of these standards, commercial implementations of SQL may differ slightly,
supporting certain nonstandard features or omitting others.
Components of SQL
The SQL language is broadly divided into several functional components:
◦ Data Definition Language (DDL): The DDL provides commands for defining database structures
such as relations (tables), specifying their schemas, and modifying or deleting them.
◦ Data Manipulation Language (DML): The DML allows the user to query the database, as well as
insert, update, and delete data.
◦ Integrity Constraints: SQL allows specification of integrity rules that ensure data correctness
and consistency. Updates violating these rules are automatically disallowed.
◦ View Definition: SQL enables the creation of views, which are virtual tables derived from one or
more base tables.
◦ Transaction Control: SQL supports the definition and management of transactions using
commands such as BEGIN, COMMIT, and ROLLBACK.
◦ Embedded and Dynamic SQL: These features specify how SQL commands can be embedded
within general-purpose programming languages like C, C++, or Java.
◦ Authorization: SQL provides commands for defining user access rights and privileges to ensure
database security.
SQL process:
◦ When an SQL command is executing for any
RDBMS, then the system figure out the best
way to carry out the request and the SQL
engine determines that how to interpret the
task.
◦ In the process, various components are
included. These components can be
optimization Engine, Query engine, Query
dispatcher, classic, etc.
◦ All the non-SQL queries are handled by the
classic query engine, but SQL query engine
won't handle logical files.
Rules for Writing SQL Queries
There are certain rules for SQL which would ensure consistency and
functionality across databases. By following these rules, queries will be well
formed and well executed in any database.
◦ End with Semicolon (;): Each SQL statement must end with a semicolon
to execute properly.
◦ Case Insensitivity: SQL keywords (e.g., SELECT, INSERT) are not case-
sensitive. However, table or column names may be case-sensitive depending
on the DBMS.
◦ Whitespace Allowed: Queries can span multiple lines, but use spaces
between keywords and names.
◦ Reserved Words: Avoid using SQL keywords as names. If needed, wrap
them in quotes (" ") or backticks (`).
Rules for Writing SQL Queries
Comments
◦ Single-line: -- comment
◦ Multi-line: /* comment */
Data Constraints: Use NOT NULL, UNIQUE, PRIMARY KEY, etc., to
ensure data accuracy.
String Values: Enclose strings in single quotes ('text').
Naming Rules:
◦ We Start with a letter
◦ We can only use Max 30 characters
◦ We only use letters, numbers and underscores (_)
SQL Datatype
o SQL Datatype is used to define the values that a column can contain.
o Every column is required to have a name and data type in the database table.
Data Type
1. Binary Datatypes
◦ There are Three types of binary Datatypes which are given below:
Data Type
2. Approximate Numeric Datatype :
◦ The subtypes are given below:
Data Type
3. Exact Numeric Datatype
◦ The subtypes are given below:
Data Type
4. Character String Datatype
◦ The subtypes are given below:
Data Type
5. Date and time Datatypes
◦ The subtypes are given below:
Basic Data Types
SQL supports a rich collection of built-in data types. Some of the commonly used ones are:
Type Description
char(n) Fixed-length character string of length n.
varchar(n) Variable-length string with a maximum length n.
int or integer Integer values (machine-dependent size).
smallint Smaller range integer type.
Fixed-point number with p total digits, d of which are after the decimal
numeric(p, d) point. Thus, numeric(3,1) allows 44.5 to be stored exactly, but
neither 444.5 or 0.32 can be stored exactly in a field of this type.
Examples of Violations
Primary-Key Violation:
◦ A tuple containing a null value in a primary-key attribute, or a duplicate key value, is not allowed.
◦ If dept_name is the primary key of the department table, inserting another tuple with the same dept_name is
rejected.
Foreign-Key Violation:
◦ A foreign key must reference an existing tuple in the parent (referenced) table.
◦ If a tuple is inserted into course with a dept_name not present in department, SQL rejects the insertion.
Integrity Constraints and Their Enforcement
SQL enforces database consistency by ensuring that all updates follow the integrity constraints defined
during schema creation. These constraints include primary keys, foreign keys, unique constraints, and
NOT NULL conditions.
Enforcement of Constraints
When a user attempts to perform an operation that violates a constraint, SQL automatically rejects
the modification and generates an error. This prevents the database from entering an inconsistent state.
Examples of Violations
Primary-Key Violation:
◦ A tuple containing a null value in a primary-key attribute, or a duplicate key value, is not allowed.
◦ If dept_name is the primary key of the department table, inserting another tuple with the same dept_name is
rejected.
Foreign-Key Violation:
◦ A foreign key must reference an existing tuple in the parent (referenced) table.
◦ If a tuple is inserted into course with a dept_name not present in department, SQL rejects the insertion.
SQL Commands
SQL commands are instructions. It is used to communicate with the database. It is also used
to perform specific tasks, functions, and queries of [Link] can perform various tasks like
create a table, add data to tables, drop the table, modify the table, set permission for users.
There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
SQL Data Definition
Before data can be stored or manipulated, the structure of the database must be
defined. This structure is specified through the Data Definition Language (DDL).
◦ The SQL DDL allows users to define:
◦ The schema (structure) of each relation.
◦ The types of values associated with each attribute.
◦ Integrity constraints to enforce data validity.
◦ Indexes for efficient data retrieval.
◦ Authorization information controlling access rights.
◦ Physical storage details for optimization (optional in most cases).
SQL Data Definition
1. Data Definition Language (DDL)
◦ o DDL changes the structure of the table like creating a table, deleting a table, altering a
table, etc.
◦ o All the command of DDL are auto-committed that means it permanently save all the
changes in the database.
Here are some commands that come under DDL:
◦ CREATE
◦ ALTER
◦ DROP
◦ TRUNCATE
SQL Data Definition
a. CREATE It is used to create a new table in the database.
Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
Example:
CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);
b. DROP: It is used to delete both the structure and record stored in the table.
Syntax
DROP TABLENAME ;
Example
DROP TABLE EMPLOYEE;
c. ALTER: It is used to alter the structure of the database. This change could be either to modify
the characteristics of an existing attribute or probably to add a new attribute.
SQL Data Definition
Syntax:
To add a new column in the table
ALTER TABLE table_name ADD column_name COLUMN-definition;
To modify existing column in the table:
ALTER TABLE MODIFY(COLUMN DEFINITION....);
EXAMPLE
1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));
[Link]: It is used to delete all the rows from the table and free the space containing the table.
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE EMPLOYEE;
SQL Data Definition
SQL Data Definition
◦ The CREATE TABLE statement in SQL is used to define a new table in a database. It specifies the table name,
column names, and their data types. This command lays the foundation for storing and organizing data.
CREATE table table_name
(
Column1 datatype (size),
column2 datatype (size),
.
.
columnN datatype(size)
);
◦ table_name: The name you assign to the new table.
◦ column1, column2, ... : The names of the columns in the table.
◦ datatype(size): Defines the data type and size of each column.
Explanation:
• CustomerID is an integer and serves as the PRIMARY KEY, ensuring each record is unique.
• FirstName, LastName, and Country are VARCHAR fields to store variable-length text.
• Age has a CHECK constraint, ensuring it’s within the range of 0 to 99.
• Phone is an integer field, although in real scenarios, a VARCHAR would often be used for storing phone
numbers to allow for leading zeros and formatting.
SQL Data Definition
Create Table from Existing Table
We can also create a new table based on the structure (and optionally the data) of an existing table.
The CREATE TABLE AS SELECT command allows us to duplicate an entire table or select specific columns to
form a new one. The following query creates a new table called SubTable that contains CustomerID and
CustomerName from the existing Customer table.
Syntax:
CREATE TABLE new_table_name AS
SELECT column1, column2, ...
FROM existing_table_name
WHERE ...;
In this example, we create a new table SubTable that contains just the CustomerID and CustomerName columns
from the Customer table. This method is useful for creating backups or performing quick data migrations.
Query:
CREATE TABLE SubTable AS
SELECT CustomerID, CustomerName
FROM customer;
SQL Data Definition
Tips for Using CREATE TABLE in SQL
To ensure the smooth creation and management of your tables, keep these points in mind:
1. The CREATE TABLE statement can also define constraints like NOT NULL, UNIQUE, and DEFAULT.
2. If you attempt to create a table that already exists, SQL will throw an error. To avoid this, you can use
the IF NOT EXISTS clause.
CREATE TABLE IF NOT EXISTS Customer (...);
3. Always define appropriate data types for each column (e.g., VARCHAR(50) for names and INT for IDs)
to optimize performance and storage.
4. After creating a table, use the following command to view the structure of your table:
DESC table_name;
5. If you need to change the table’s structure after creation (e.g., renaming a column, adding a new column),
use the ALTER TABLE statement.
◦
SQL Data Definition
SQL DROP Command
The SQL DROP command is used to permanently remove an object from a database, such as a table,
database, index or view. When a table is dropped, both its data and structure are permanently removed,
and the action cannot be undone without a backup.
Permanent Removal: Deletes object and data permanently.
Deletes Dependencies: Removes related constraints and indexes.
Schema Deleted: Removes table structure and schema.
No Integrity Check: Skips constraints and triggers.
Syntax:
DROP object object_name ;
object: The type of object you want to drop (e.g., TABLE, DATABASE).
object_name: The name of the object to be deleted.
SQL Data Definition
Examples of Using the DROP Command
To understand how the DROP command works in SQL, let us explore some practical examples
demonstrating its various applications.
1. DROP Table
To delete an entire table including its data and structure:
Syntax:
DROP TABLE table_name;
2. DROP database
To delete an entire database and all of its associated tables:
Syntax:
DROP DATABASE database_name;
SQL Data Definition
Example 2 – To view only the employees’ IDs and names, you select only 2 2 Ram
Emp_ID and Emp_Name columns in the SELECT command. 3 3 Chirag
◦ SELECT Emp_ID, Emp_Name FROM Employee; 4 4 Pankaj
Example 3 – To retrieve specific records from the table Employee, for
instance, you want to see the information of employees who work in Pune.
◦ SELECT * FROM Employee WHERE Emp_City IN (‘Pune’);
Example: Grants the HR_Manager role permission to view and add data to the Employees table.
GRANT SELECT, INSERT ON Employees TO HR_Manager;
REVOKE: removes specific privilages from users which was previously granted
REVOKE permission ON object FROM user;
Example:
Removes the Sales_Team role's permission to delete data from the Customers table.
REVOKE DELETE ON Customers FROM Sales_Team;
SQL Transaction Control Language
COMMIT: Saves all the changes you made during a transaction permanently.
BEGIN;
-- SQL statements
COMMIT;
ROLLBACK: Undoes changes you made during a transaction if something went wrong.
BEGIN;
-- SQL statements
ROLLBACK;
SAVEPOINT: Sets a point inside a transaction to which you can roll back if needed.
BEGIN;
-- SQL statements
SAVEPOINT my_savepoint;
-- More SQL statements
ROLLBACK TO my_savepoint;
SQL Transaction Control Language
`SAVEPOINT` is used within a transaction to create a named point that can be rolled back to if needed.
It is particularly useful for managing complex transactions that may require undoing specific parts
without rolling back the entire transaction.
SAVEPOINT savepoint_name;
◦ In this syntax, `savepoint_name` is a label for the save point created within the transaction.
◦ Example : Creating savepoint
START TRANSACTION;
INSERT INTO orders (product_id, quantity) VALUES (1, 10);
SAVEPOINT order_savepoint;
◦ In this example, a savepoint named `order_savepoint` is created after inserting a row into the `orders`
table. This allows you to roll back to this point if necessary.
SQL Transaction Control Language
The Rename Operation: When writing SQL queries, it is often necessary to rename attributes or
relations. Reasons include:
◦ Attribute Name Conflicts: Two relations may contain attributes with the same name.
◦ Expressions Without Names: Arithmetic expressions in the SELECT clause produce unnamed
attributes.
◦ Convenience: Long relation names can be replaced with shorter aliases.
The rename operation allows assigning a new name to an attribute or relation within a query.
Syntax: old_name AS new_name
Example renaming attributes:
select name as instructor_name, course_id
from instructor, teaches
where [Link] = [Link];
Additional basic Operations
◦ A table or a column may be given another name in a SQL query by using an alias. This can be helpful if
there are long or complex table or column names which may be converted to short names using
aliases, in particular in complex queries using several tables. Also, for some reasons, we may want to
change the columns’ names in the output from the names used in the base tables. SQL aliases may then
be used. A column alias in the column list of the SELECT statement may be specified by using the AS
keyword.
◦ Alias used in the FROM clause in SQL
SELECT column_name(s)
FROM table_name AS alias_name;
String Constants: A text value enclosed in single quotes. Will store in single quotes
Example : where dept_name = 'Comp. Sci.’
String escaping: Two single quotes inside a string represent one quote.
Syntax: 'It''s correct’
Example: Stores the string: It’s correct
Simple Queries — Selecting Columns and Rows
Retrieving the Whole Table using *
SELECT * is used to retrieve all columns and all rows from a table.
If no WHERE clause is used → entire table is printed.
Syntax:
SELECT *
FROM table_name;
Example: SELECT *
FROM Student;
Syntax:
SELECT column1, column2, ...
FROM table_name;
Example:
Find StudentID, FirstName, LastName:
StudentID FirstName LastName
SELECT StudentID, FirstName, LastName 101 Rahul Sharma
FROM Student;
102 Sara Khan
103 David Lee
Simple Queries — Selecting Columns and Rows
Syntax:
SELECT * SELECT *
FROM Student
FROM table_name
WHERE Country = 'India';
WHERE condition;
StudentID FirstName LastName Country YearOfBirth City
101 Rahul Sharma India 2002 Delhi
110 Priya Singh India 2001 Mumbai
Simple Queries — Selecting Columns and Rows
AND → all conditions must be true Indian students born after 2001:
OR → any one condition must be true
SELECT *
FROM Stud ent
Syntax: WHERE Country = 'India'
SELECT * AND YearOfBirth > 2001;
FROM table_name
WHERE condition1 AND condition2;
102 C101 A
106 C103 A
Simple Queries — Selecting Columns and Rows
Country
List all the Unique Countries:
India
USA SELECT DISTINCT Country
FROM Student;
UK
Canada
Simple Queries — Selecting Columns and Rows
Syntax:
Syntax:
Syntax:
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC|DESC;
Sort students alphabetically by FirstName:
StudentID FirstName LastName
SELECT StudentID, FirstName, LastName
103 David Lee FROM Student
ORDER BY FirstName ASC;
101 Rahul Sharma
FirstName LastName
Find students whose last name starts with “Sh”:
Rahul Sharma
LIKE uses two wildcards to match flexible character patterns: the percent
(%) wildcard and the underscore (_) wildcard. The percent symbol (%)
represents any sequence of zero or more characters, while the underscore (_)
represents exactly one single character.
This makes LIKE extremely useful when the exact value is not known but
the pattern is known. For example, the pattern 'Del%' matches any string
that begins with “Del”, such as “Delhi” or “Delight”, because % allows a
variable number of trailing characters.
STRING MATCHING IN SQL (LIKE OPERATOR)
Similarly, the pattern 'Gup_' matches any four-character string that begins
with “Gup”, since _ matches exactly one trailing character such as “Gupa”
or “Gupt”.
LIKE is fundamentally different from the equality (=) operator because SQL
does not pad strings when matching patterns; equality compares strings by
padding the shorter one with spaces if needed. LIKE simply tests whether
the actual string satisfies the given wildcard pattern.
Syntax: RollNo FName LName City
column_name LIKE 'pattern'; 101 Ravi Singhal Delhi
column_name NOT LIKE 'pattern'; 102 Megha Singh Mumbai
103 Rohan Kumar Mysore
104 Anita Sinha Delhi
105 Mohan Singar Bengaluru
Simple Queries — Selecting Columns and Rows
Example 3: Last name with exactly one character after “Sing” FName LName
SELECT * FROM STUDENT
WHERE LName LIKE 'Sing_’; Megha Singh
Proper
INITCAP(string): NITCAP converts the first letter of every word in the LName
Name
input string into uppercase and converts the remaining letters into
Singhal Singhal
lowercase. It is commonly used to format names or text into proper “title
case”. Singh Singh
Syntax: INITCAP(string) Kumar Kumar
Example SELECT LName, INITCAP(LName) AS ProperName
Sinha Sinha
FROM STUDENT;
Singar Singar
SQL STRING FUNCTIONS
Converted
Computer Science Department
SQL STRING FUNCTIONS
LENGTH(string): The LENGTH function returns the number of characters in the string, including
letters, digits, and special symbols. Spaces are also counted.
Syntax:
LENGTH(string)
LName NameLength
Length of each student’s last name Singhal 7
Singh 5
SELECT LName, LENGTH(LName) AS NameLength
FROM STUDENT; Kumar 5
Sinha 5
Singar 6
SQL STRING FUNCTIONS
SUBSTR extracts a substring from the given string. The starting position is counted from 1, and
the second argument defines how many characters to extract.
Syntax:
SUBSTR(string, start_position, length) LName First3Letters
Singhal Sin
Example: First 3 characters of each Lname
Singh Sin
SELECT LName, SUBSTR(LName, 1, 3) AS First3Letters Kumar Kum
FROM STUDENT; Sinha Sin
Singar Sin
SQL STRING FUNCTIONS
LName Middle2
Singhal ng
Example: Middle 2 characters (starting from position 3) Singh ng
Kumar ma
SELECT LName, SUBSTR(LName, 3, 2) AS Middle2
Sinha nh
FROM STUDENT;
________________________________________________________ Singar ng
Example: Last 3 characters of each LName
-- OR
WHERE column IN (SELECT column FROM table) RollNo FName LName City
Select students whose city is Delhi or Mumbai. 104 Anita Sinha Delhi
Ex: SELECT * FROM STUDENT
WHERE City IN ('Delhi','Mumbai’);
FORMS OF THE WHERE CLAUSE
WHERE NOT IN : The NOT IN operator selects rows whose values are not present in the given
list.
Syntax: WHERE column NOT IN (value1, value2, ...)
SELECT * FROM STUDENT
WHERE City NOT IN ('Delhi','Mumbai’); RollNo FName LName City
The IS NULL operator is used to test whether a column contains no value (NULL). Equality (=)
cannot be used to check for NULL.
Syntax:
SELECT columns RollNo Marks
FROM table
101 80
WHERE EXISTS (
SELECT 1 102 70
FROM another_table
WHERE condition
); FName LName
SELECT [Link], [Link]
Ravi Singhal
FROM STUDENT S
WHERE EXISTS ( Megha Singh
SELECT *
FROM MARKS M
WHERE [Link] = [Link]
);
FORMS OF THE WHERE CLAUSE
WHERE NOT EXISTS:
NOT EXISTS is true only when the subquery returns no rows. Used to find rows that have no
matching record in another table. SELECT [Link], [Link]
FROM STUDENT S
Syntax: WHERE NOT EXISTS (
SELECT *
SELECT columns
FROM MARKS M
FROM table
WHERE [Link] = [Link]
WHERE NOT EXISTS ( );
SELECT 1
FROM another_table
WHERE condition
FName LName
);
Rohan Kumar
Anita Sinha
Mohan Singar
QUERIES INVOLVING MORE THAN ONE TABLE
A subquery (also called an inner query or nested query) is a SELECT statement written inside
another SQL statement. The result of the subquery is used by the outer query to filter rows or
compute values. Subqueries are typically written inside the WHERE, FROM, or SELECT clause.
SELECT columns
FROM table [Link] executes the inner subquery first.
WHERE expression operator ( [Link] subquery returns a value or set of values.
SELECT columns [Link] outer query uses that result to filter its own rows.
FROM table
WHERE condition
);
QUERIES INVOLVING MORE THAN ONE TABLE
SELECT Name
FROM Student
WHERE DeptID IN (
SELECT DeptID
FROM Department
WHERE DeptName='Computer Science’
);
Execution:
Subquery finds DeptID = 10
Outer query selects students whose DeptID = 10
QUERIES INVOLVING MORE THAN ONE TABLE
Nested Subquery: A nested subquery is a subquery inside another subquery.
SQL allows multiple levels of nesting.
Syntax:
How it Works
SELECT ... [Link] innermost subquery executes first.
FROM table [Link] result is used by the next level.
WHERE column IN ( [Link], the outermost query executes.
SELECT column
FROM table
WHERE column IN (
SELECT column
FROM table
WHERE condition
)
);
QUERIES INVOLVING MORE THAN ONE TABLE
Example:
Find courses taken by “Arjun Kumar”:
SELECT *
FROM Course Execution:
WHERE CourseID IN ( Inner → find SID of Arjun
SELECT CourseID Middle → find all CourseIDs of Arjun
FROM Enrollment Outer → fetch details of those courses
WHERE SID IN (
SELECT SID
FROM Student
WHERE FName='Arjun' AND LName='Kumar'
)
);
QUERIES INVOLVING MORE THAN ONE TABLE
JOIN: A join combines rows from two or more tables based on related columns.
Syntax:
SELECT columns
FROM Table1 t1
JOIN Table2 t2
ON t1.common_column = t2.common_column;
How it Works
SQL finds rows where the join condition is TRUE.
It merges columns from both tables into a single result row.
Only matching rows (INNER JOIN) are returned.
QUERIES INVOLVING MORE THAN ONE TABLE
Example: List students with their course names:
Execution:
Join Student -- Enrollment using SID
Join Enrollment -- Course using CourseID
Return merged rows
QUERIES INVOLVING MORE THAN ONE TABLE
Self Join:
A self join is when a table is joined with itself using two different aliases.
Syntax:
SELECT [Link], [Link]
FROM table a
JOIN table b
ON a.common_column = b.common_column
WHERE additional_condition;
How it Works
SQL treats the same table as two separate tables (aliases).
It matches rows in one alias to rows in the other alias.
QUERIES INVOLVING MORE THAN ONE TABLE
Example: Find students who scored above 80 in DBMS and OS:
SELECT [Link]
FROM Enrollment e1
JOIN Enrollment e2 ON [Link] = [Link]
WHERE [Link]=501 AND [Link]=502
AND [Link]>80 AND [Link]>80;
Execution:
e1 = DBMS marks
e2 = OS marks
Same SID must satisfy both conditions
QUERIES INVOLVING MORE THAN ONE TABLE
Example: Find students who scored above 80 in DBMS and OS:
SELECT [Link]
FROM Enrollment e1
JOIN Enrollment e2 ON [Link] = [Link]
WHERE [Link]=501 AND [Link]=502
AND [Link]>80 AND [Link]>80;
Execution:
e1 = DBMS marks
e2 = OS marks
Same SID must satisfy both conditions
College Database Example SID FName LName DeptID
1 Arjun Kumar 10
There are four table: 2 Riya Sharma 20
1. Student 3. Enrolment 3 Vivek Gupta 10
2. Department 4. Course
4 Sneha Reddy 30
CourseID CourseName DeptID 5 Mohan Das 20
501 DBMS 10
502 Operating Systems 10 SID CourseID Marks
601 Digital Circuits 20 1 501 87
701 Thermodynamics 30 2 501 90
30 Mechanical
QUERIES INVOLVING MORE THAN ONE TABLE
(JOINS + SUBQUERIES USING COLLEGE DATABASE)
Q1 — Find all CourseIDs in which “Riya Sharma” is enrolled.
Use a subquery to find the SID of student Riya Sharma, then use this to find all CourseIDs from
ENROLLMENT.
SELECT CourseID
FROM ENROLLMENT
WHERE SID IN (
SELECT SID
FROM STUDENT
WHERE FName='Riya' AND LName='Sharma'
);
Subquery returns SID = 2 for Riya Sharma.
Outer query retrieves all CourseIDs from ENROLLMENT where SID = 2. CourseID
Riya is enrolled only in CourseID 501. 501
QUERIES INVOLVING MORE THAN ONE TABLE
Student Table Department Table
RollNo Name Dept Age Dept DeptName HOD
101 Ananya Rao CSE 20 CSE Computer Science Dr. Vikram Nair
102 Rohan Mehta ECE 19 ECE Electronics & Comm. Dr. Meena Joshi
103 Sneha Patil CSE 21 ME Mechanical Engg. Dr. Prakash Rao
104 Aravind KS ME 22 CIV Civil Engineering Dr. Lakshmi Iyer
Marks Table
RollNo CourseID Marks
101 CS101 86
101 CS102 78
102 EC201 91
103 CS101 67
Joins
A SQL JOIN is an operation that combines rows from two or more tables based on a related
column, usually a primary key–foreign key relationship. Since data in relational databases is
normalized and spread across multiple tables, joins are necessary to reconstruct complete
information. They create a logical link between tables at query time without physically merging
them. Joins allow users to write powerful queries that answer real-world questions involving
multiple entities.
• In practice, information like student details, department details, and marks are stored in separate
tables for consistency and minimal redundancy.
• To answer queries such as “list each student with their department HOD” or “show departments
with no students”, we must access more than one table at once. SQL provides different join types
to handle only matching rows, unmatched rows, or all combinations.
• Thus, joins form the backbone of multi-table query processing in relational database systems.
Inner Join
An INNER JOIN returns only those rows where the join condition between two tables is
satisfied. Rows from either table that do not have a matching value in the other table are
excluded from the result. Effectively, it gives the intersection of both tables with respect to the
join condition. This join is used when we are interested only in fully matched, valid
relationships.
Syntax: Name HOD
SELECT column_list Ananya Rao Dr. Vikram Nair
FROM TableA Rohan Mehta Dr. Meena Joshi
INNER JOIN TableB Sneha Patil Dr. Vikram Nair
ON TableA.common_col = TableB.common_col;
Aravind KS Dr. Prakash Rao
Example:
Display each student’s name along with the HOD of their department.
SELECT [Link], [Link]
FROM Student s
INNER JOIN Department d
ON [Link] = [Link];
Left Outer Join
A LEFT OUTER JOIN returns all rows from the left table and the matching rows from the right
table. If there is no matching row in the right table, the result will still contain the left-table row
but with NULLs in the columns of the right table. It is particularly useful when we want to
retain all master records from the left table and still see where related records are missing in the
right table. This helps in auditing, reporting and integrity checks.
Syntax:
SELECT column_list
FROM TableA
LEFT JOIN TableB
ON TableA.common_col = TableB.common_col;
Example:List all departments and the names Dept DeptName Name
of students enrolled in them CSE Computer Science Ananya Rao
SELECT [Link], [Link], [Link] CSE Computer Science Sneha Patil
FROM Department d
ECE Electronics & Comm. Rohan Mehta
LEFT JOIN Student s
ON [Link] = [Link]; ME Mechanical Engg. Aravind KS
CIV Civil Engineering NULL
Right Outer Join
A RIGHT OUTER JOIN returns all rows from the right table and only the matching rows from the left
table. If a row exists in the right table with no corresponding match in the left table, the result still
includes the right-table row with NULL values for left-table columns. It is essentially the mirror of the left
join and is helpful when the right table is considered the main reference. It highlights missing or
incomplete data in the left table relative to the right.
Syntax:
SELECT column_list Name Dept DeptName
FROM TableA
RIGHT JOIN TableB Ananya Rao CSE Computer Science
ON TableA.common_col = TableB.common_col; Sneha Patil CSE Computer Science
List all departments and show student names where
Rohan Mehta ECE Electronics & Comm.
they exist, ensuring every department appears.
SELECT [Link], [Link], [Link] Aravind KS ME Mechanical Engg.
FROM Student s NULL CIV Civil Engineering
RIGHT JOIN Department d
ON [Link] = [Link];
Full Outer Join (available as UNION)
A FULL OUTER JOIN returns all rows from both tables regardless of whether matches exist. When rows
match, they appear combined once; when a row has no match, it appears with NULL for the columns of
the other table. This join is very useful in reconciliation tasks where differences between two datasets
must be identified. It gives a complete picture of matches and mismatches in one query.
Syntax:
SELECT column_list
FROM TableA
FULL OUTER JOIN TableB Name Dept DeptName
ON TableA.common_col = TableB.common_col; Ananya Rao CSE Computer Science
Sneha Patil CSE Computer Science
Show all departments and all students, including any
department without students and any student with invalid Rohan Mehta ECE Electronics & Comm.
department Aravind KS ME Mechanical Engg.
SELECT [Link], [Link], [Link]
NULL CIV Civil Engineering
FROM Student s
FULL OUTER JOIN Department d
ON [Link] = [Link];
Cross Join
A CROSS JOIN returns the Cartesian product of two tables. Every row from the first table is paired with
every row from the second table, irrespective of matching values. It does not require a join condition and
can produce very large result sets. It is mainly used to generate all combinations, sample data, or when a
later WHERE clause will filter the combinations.
Syntax: Name Dept
SELECT column_list Ananya Rao CSE
FROM TableA
CROSS JOIN TableB; Ananya Rao ECE
Ananya Rao ME
Generate all possible combinations of students and Ananya Rao CIV
departments
Rohan Mehta CSE
SELECT [Link], [Link] … …
FROM Student s
CROSS JOIN Department d;
Enrollment Table
SID CourseID Semester Year
Syntax:
SELECT column_list
FROM table1
INTERSECT
CourseID
SELECT column_list
FROM table2; C102
Query:
(SELECT CourseID FROM Enrollment WHERE Semester='ODD' AND Year=2023)
INTERSECT
(SELECT CourseID FROM Enrollment WHERE Semester='EVEN' AND Year=2024);
Set operations
EXCEPT Operation
• EXCEPT returns rows from the first SELECT that do not appear in the second SELECT.
• It removes duplicates before performing the difference and outputs only distinct results.
• This is used to find discontinued courses, subjects not taught in next semester, or changes in curriculum.
• It follows mathematical set difference (A − B).
Syntax;
SELECT column_list
FROM table1
EXCEPT
SELECT column_list
FROM table2;
Query: The courses offered in ODD 2023 but not in EVEN 2024. CourseID
C101
(SELECT CourseID FROM Enrollment WHERE Semester='ODD' AND Year=2023) C103
EXCEPT
(SELECT CourseID FROM Enrollment WHERE Semester='EVEN' AND Year=2024); C104
Working with NULL Values
• A NULL value in SQL represents missing, unknown, or inapplicable data.
• Any arithmetic or comparison involving NULL results in NULL or UNKNOWN, not TRUE or FALSE.
• SQL uses three-valued logic: TRUE, FALSE, UNKNOWN, making NULL handling different from normal
values.
• To check NULL values, SQL provides special predicates IS NULL and IS NOT NULL.
• NULL is not equal to zero, an empty string, or any other value.
SID Name Email
Syntax; S01 Arjun arjun@[Link]
column IS NULL
S02 Meera NULL
column IS NOT NULL
S03 Rahul rahul@[Link]
Query: Find all students whose email is NOT provided
SELECT SID, Name
FROM Student
WHERE Email IS NULL; SID Name
S02 Meera
AGGREGATE FUNCTIONS
• Aggregate functions operate on groups of rows and return a single computed value.
• They are used in statistical reports such as average marks, total enrollments, minimum fees, or maximum
attendance.
• Common SQL aggregate functions include COUNT, SUM, AVG, MIN, and MAX.
SID Marks
• These functions ignore NULL values (except COUNT(*)).
• They are widely used in analytics, dashboards, and performance summaries. S01 85
Syntax: S02 90
SELECT AGG_FUNC(column)
S03 NULL
FROM table
WHERE condition; S04 70
Null is ignored
AGGREGATE FUNCTIONS SID Name Marks
S01 Arjun 85
COUNT() – Counting Rows
S02 Meera 90
• COUNT() is used to count the number of rows in a table.
• COUNT(column) counts only non-NULL values, whereas COUNT() counts all rows S03 Rohan 75
including NULLs. S04 Sneha NULL
• It is used widely for calculating number of students, courses, registrations, or entries.
S05 Kavya 95
• COUNT ignores NULL values unless COUNT() is used.
Syntax: S06 Varun 60
SELECT COUNT(column_name) FROM table;
SELECT COUNT(*) FROM table;
Syntax:
SELECT AVG(column_name) FROM table;
(405 ÷ 5 = 81)
AGGREGATE FUNCTIONS
MIN() – Minimum Value
• MIN() returns the smallest value in a numeric or text column.
• It ignores NULL values and considers only valid entries.
• Used for identifying the lowest score, minimum fee, earliest date, etc.
• It works on numbers, strings (alphabetical order), and dates.
Syntax:
SELECT MIN(column_name) FROM table;
LowestMarks
Query: Find the lowest marks in the class 60
Syntax:
SELECT MAX(column_name) FROM table;
HighestMarks
Query: Find the highest marks in the class 95
Syntax:
SELECT COUNT(DISTINCT column_name) FROM table; UniqueMarks
Syntax:
SELECT column, AGG_FUNC(column)
FROM table
GROUP BY column
HAVING condition_on_aggregate;
Original Query
Internal trasformation
Country TotalStudents
India 3
USA 1
UK 1
UPDATING A VIEW
Syntax:
UPDATE view_name
SET column = value
WHERE condition;
• Embedded SQL is the technique of writing SQL statements inside a host programming language
such as C, C++, Java, or COBOL using special syntax like EXEC SQL.
• The SQL commands are processed by a precompiler, converted into function calls of the host
language, and then executed like normal program code.
• Embedded SQL allows programmers to use procedural constructs (loops, IF-ELSE, functions)
along with SQL queries.
• It is mainly used when the program logic is fixed and SQL queries are known at compile time.
Embedded SQL
• SQL code is written inside a host language using EXEC SQL prefix.
• SQL statements are statically embedded, meaning they are known before program execution.
• Requires a precompiler (preprocessor) to convert SQL to host-language function calls.
• Uses host variables to exchange data between SQL and program, prefixed by colon (:).
• Uses cursors to fetch rows one-by-one due to impedance mismatch.
• Easier error handling using SQLCA, SQLCODE, SQLSTATE.
Embedded SQL
• Dynamic SQL is SQL that is constructed and executed at runtime, usually using strings in
languages like Java, Python, or C.
• It allows greater flexibility because the exact SQL statement does not need to be known during
compilation.
• Dynamic SQL is used when the query structure depends on user input, changing table names, or
conditions determined at runtime
String query = "SELECT Name, Dept FROM Student WHERE Dept = '" + dept + "'";
while ([Link]()) {
[Link]([Link]("Name") + " " + [Link]("Dept"));
}
Difference Between Embedded SQL and Dynamic SQL
Good for stable applications where queries do not Good for flexible applications where queries change
change. often.
Cannot easily build SQL with dynamic table names or Fully supports dynamic table names, columns, and
conditions. WHERE clauses.
Safer and detects errors early. Higher chance of SQL injection if not coded carefully.
Requires cursors to handle multiple rows. Fetching data depends on host language library.
Used in enterprise software (banking apps, ERP). Used in websites, dashboards, reporting tools.