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

UNIT III dbms notes

This document covers essential SQL concepts including basic querying, the use of WHERE clauses, arithmetic and logical operations, and SQL functions for date, time, numeric, and string conversions. It explains how to create tables, implement key and integrity constraints, and perform various types of joins and subqueries. Additionally, it provides examples of SQL syntax and operations for filtering, aggregating, and manipulating data.

Uploaded by

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

UNIT III dbms notes

This document covers essential SQL concepts including basic querying, the use of WHERE clauses, arithmetic and logical operations, and SQL functions for date, time, numeric, and string conversions. It explains how to create tables, implement key and integrity constraints, and perform various types of joins and subqueries. Additionally, it provides examples of SQL syntax and operations for filtering, aggregating, and manipulating data.

Uploaded by

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

UNIT III: SQL:

Basic SQL querying (select and project) using where clause, arithmetic & logical operations, SQL
functions(Date and Time, Numeric, String conversion).Creating tables with relationship,
implementation of key and integrity constraints, nested queries, sub queries, grouping, aggregation,
ordering, implementation of different types of joins, view(updatable and non-updatable), relational set
operations.

Basic SQL querying (select and project) using where clause:

1. SELECT (σ) in Relational Algebra

• Selection (σ) is used to filter rows (tuples) based on a condition.

• In SQL, the WHERE clause is equivalent to the SELECT (σ) operation in relational algebra.

• Example: In Relational Algebra:

• 𝜎 𝑎𝑔𝑒>20 (Students)

• In SQL:

• SELECT * FROM Students WHERE age > 20;

• This selects all students where age is greater than 20.

2. PROJECT (π) in Relational Algebra

• Projection (π) is used to select specific columns (attributes).

• In SQL, the SELECT column_names statement performs projection.

• Example: In Relational Algebra:

• πfirst_name,last_name(Students)

• In SQL:

• SELECT first_name, last_name FROM Students;

• This retrieves only the first_name and last_name of all students.

Combining both SELECT and PROJECT in SQL:

• If we need to apply both selection and projection, we use SELECT column_names along
with WHERE.

• Example: In Relational Algebra:

• πfirst_name,last_name(σage>20(Students))

• In SQL:

• SELECT first_name, last_name FROM Students WHERE age > 20;

• This filters students where age is greater than 20 (SELECT σ) and retrieves only the
first_name and last_name (PROJECT π).
SQL Where Clause:

• A where clause in SQL is a data manipulation language statement.

• Where clauses are not mandatory clauses of SQL DML statements but it can be used to limit
the number of rows affected by a SQL DML statement or returned by query.

• Actually, it follows the records.it returns only those queries which the specific conditions.

• Syntax: Select column1, column2, ………, column from table_name where[condition];

• Where clause uses some conditional selection.

• = • Equal to

• > • Greater than

• < • Less than

• <= • Greater than or equal to

• >= • Less than or equal to

• <> • Not equal to

Arithmetic and Logical Operations:

SQL operators: SQL statements generally contain some reserved words or characters that are used to
perform operations such as arithmetic and logical operations etc. Their reserved words are known as
operators.

LOGICAL OPERATORS:

• What Are Logical Operators in SQL?

• Logical operators in SQL are used to combine multiple conditions in a query to control the
flow of execution. They evaluate whether these conditions are TRUE, FALSE, or NULL,
assisting in refining query results effectively. By using these operators, developers can
retrieve highly specific data based on given conditions.

• We will use the following employee table throughout the examples. This table represents
employee details, including their unique ID, name, city, and country.
1. AND Operator: The AND operator is used to combine two or more conditions in an SQL query.
It returns records only when all conditions specified in the query are true. This operator is commonly
used when filtering data that must satisfy multiple criteria simultaneously.

• Example

• Retrieve the records of employees from the employees table who are located
in 'Allahabad' and belong to 'India', ensuring that both conditions are met.

• Query:

• SELECT * FROM employee WHERE emp_city = 'Allahabad' AND emp_country = 'India';

2. IN Operator: The IN operator simplifies the process of checking if a value matches any value in a
list, making it more efficient and readable compared to using multiple OR conditions. This operator is
especially helpful when we need to filter results based on multiple possible values for a given column,
reducing the complexity of the query.

• Example

• Retrieve the records of employees from the employee table who are located in
either 'Allahabad' or 'Patna'.

• Query:

• SELECT * FROM employee WHERE emp_city IN ('Allahabad', 'Patna');


3. NOT Operator: The NOT operator is used to reverse the result of a condition,
returning TRUE when the condition is FALSE. It is typically used to exclude records that match a
specific condition, making it useful for filtering out unwanted data.

• Example

• Retrieve the records of employees from the employee table whose city names do not start
with the letter 'A'.

• Query:

• SELECT * FROM employee WHERE emp_city NOT LIKE 'A%';

4. OR Operator: The OR operator combines multiple conditions in a SQL query and


returns TRUE if at least one of the conditions is satisfied. It is ideal for situations where you want to
retrieve records that meet any of several possible conditions.

• Example

• Retrieve the records of employees from the employee table who are either from 'Varanasi' or
have 'India' as their country.

• Query

• SELECT * FROM employee WHERE emp_city = 'Varanasi' OR emp_country = 'India';


5. LIKE Operator: The LIKE operator in SQL is used in the WHERE clause to search for a specified
pattern in a column. It is particularly useful when we want to perform pattern matching on string data.
The LIKE operator works with two main wildcards:

• %: Represents zero or more characters. It allows matching any sequence of characters in the
string.

• _: Represents exactly one character. It is used when you want to match a specific number of
characters at a given position.

• Example

• Retrieve the records of employees from the employee table whose city names start with the
letter 'P'.

• Query:

• SELECT * FROM employee WHERE emp_city LIKE 'P%';

6. BETWEEN Operator: The BETWEEN operator in SQL allows us to test if a value or expression
lies within a specified range. The BETWEEN condition is inclusive, meaning it includes both
the lower and in the results. This operator is particularly useful when we need to filter records based
on a range of values, such as numerical ranges, dates, or even text values.

• Example

• Retrieve the records of employees from the employee table whose emp_id values fall within
the range of 101 to 104 (inclusive).

• Query:

SELECT * FROM employee WHERE emp_id BETWEEN 101 AND 104;


7. ALL Operator: The ALL operator in SQL is used to compare a value to all values returned by a
subquery. It returns TRUE if the condition specified is TRUE for all values retrieved by the
subquery. The ALL operator is commonly used with SELECT, WHERE, and HAVING clauses to
ensure that a value satisfies a condition when compared to a set of values.

• Example

• Retrieve the records of employees whose emp_id is equal to all emp_id values in
the employees table where the emp_city is 'Varanasi'.

• Query:

• SELECT * FROM employee WHERE emp_id = ALL


(SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');

8. ANY Operator: The ANY operator in SQL is used to compare a value with the results of
a subquery. It returns TRUE if the value satisfies the condition with any of the values returned by the
subquery. This operator allows for greater flexibility when you want to check if a value matches at
least one of the results in a set of values.

• Example

• Retrieve the records of employees whose emp_id matches any of the emp_id values in
the employees table where the emp_city is 'Varanasi'.

• Query:

• SELECT * FROM employee WHERE emp_id = ANY


(SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');
9. EXISTS Operator: The EXISTS operator in SQL is used to check whether a subquery returns any
rows. It evaluates to TRUE if the subquery results in one or more rows. The EXISTS operator is
typically used with SELECT, UPDATE, INSERT, and DELETE statements to determine if any
rows exist that meet a specified condition. It is often used in correlated subqueries where the
subquery references columns from the outer query.

• Example

• Retrieve the names of employees from the employee table if there are any employees in
the employee table who are located in 'Patna'.

• Query

• SELECT emp_name FROM employee WHERE EXISTS


(SELECT emp_id FROM employee WHERE emp_city = 'Patna');

10. SOME Operator: The SOME operator in SQL is used in conjunction with comparison operators
such as <, >, =, <=, etc., to compare a value with the results of a subquery. It returns TRUE if the
condition is met with any value returned by the subquery. The SOME operator allows us to perform
comparisons with any of the values returned by a subquery, and it is particularly useful when we
want to match a value against a set of values rather than a single value.

• Example

• Retrieve the records of employees from the employee table where the emp_id is less
than any of the emp_id values from employees located in 'Patna'.

• Query:
• SELECT * FROM employee WHERE emp_id < SOME
(SELECT emp_id FROM employee WHERE emp_city = 'Patna');

Arithmetic Operations: The SQL Arithmetic operators are used to perform basic mathematical
operations on numeric data types in a database. The most common arithmetic operators used in SQL
are:

Here is a list of all the arithmetic operators available in SQL.


SELECT * FROM EMPLOYEE;

Output:
SQL Addition (+) Operator

The addition operator in SQL is used to add two or more numeric values. It is similar to the "plus"
symbol in basic mathematics.

Example

In the following example, we are trying to perform the addition operation to give all employees a
bonus of 5000 to their existing salary.

SELECT ID, NAME, SALARY + 5000 AS “SALARY_BONUS” FROM employee;

Output:

SQL Subtraction (-) Operator


The subtraction operator in SQL is used to subtract one numeric value from another. It is similar to
the "minus" symbol in basic mathematics.

Example

In here, we are using the - operator to find the salary difference between the highest-paid and lowest-
paid employees.

SELECT MAX(salary), MIN(salary), MAX(SALARY)-MIN(SALARY) AS salary_difference


FROM employee;

Output:

SQL Multiplication (*) Operator

The multiplication operator in SQL is used to perform mathematical multiplication on numeric values.
It allows us to multiply two or more columns or numeric expressions together, resulting in a new
value representing the product of the operands.
Example

Now, we are performing * operation to give all employees a 10% bonus on their salary.

SELECT NAME, AGE, ADDRESS, SALARY * 1.10 AS new_salary_with_bonus FROM


employee;

Output:

SQL Division (/) Operator

The division operator (/) in SQL is used to perform mathematical division on numeric values. It
allows us to divide one numeric operand by another, resulting in a new value representing the quotient
of the division.

Example

Here, we are using the / operator to calculate the average salary of all employees.

SELECT AVG(SALARY) AS average_salary FROM employee;

Output:

SQL Modulus (%) Operator

The modulus operator (%) in SQL is used to find the remainder after dividing one numeric value by
another. It returns the integer remainder of the division operation.
Example

In the following example, we are using the % operator to find out the employees having an even
employee ID.

SELECT * FROM employee WHERE ID % 2 = 0;


SQL Functions

SQL provides built-in functions to perform operations on Date and Time values, Numeric values,
and String conversions.

1. Date and Time Functions

These functions help in manipulating and extracting information from date and time values.

1.1 SYSDATE

 Returns the current system date and time.


 Example:
 SELECT SYSDATE FROM DUAL;

Output:

SYSDATE
-------------------
2025-03-19 14:30:45
1.2 CURRENT_DATE

 Returns the current date based on the session time zone.


 Example:
 SELECT CURRENT_DATE FROM DUAL;

Output:

CURRENT_DATE
-------------------
2025-03-19 14:30:45

1.3 ADD_MONTHS()

 Adds a specific number of months to a given date.


 Example:
 SELECT ADD_MONTHS('2025-03-19', 6) AS NEW_DATE FROM DUAL;

Output:

NEW_DATE
-------------------
2025-09-19

1.4 MONTHS_BETWEEN()

 Finds the number of months between two dates.


 Example:
 SELECT MONTHS_BETWEEN('2025-12-01', '2025-03-01') AS MONTH_DIFF FROM
DUAL;

Output:

MONTH_DIFF
----------
9

1.5 NEXT_DAY()

 Returns the next occurrence of the specified day after a given date.
 Example:
 SELECT NEXT_DAY('2025-03-19', 'Friday') AS NEXT_FRIDAY FROM DUAL;

Output:

NEXT_FRIDAY
-------------------
2025-03-21

1.6 LAST_DAY()

 Returns the last day of the month for a given date.


 Example:
 SELECT LAST_DAY('2025-03-19') AS LAST_DAY_OF_MONTH FROM DUAL;
Output:

LAST_DAY_OF_MONTH
-------------------
2025-03-31

1.7 EXTRACT()

 Extracts parts (Year, Month, Day) from a date.


 Example:
 SELECT EXTRACT(YEAR FROM DATE '2025-03-19') AS YEAR FROM DUAL;

Output:

YEAR
----
2025

2. Numeric Functions

These functions are used for arithmetic and mathematical calculations.

2.1 ROUND()

 Rounds a number to the specified decimal places.


 Example:
 SELECT ROUND(123.456, 2) AS ROUNDED FROM DUAL;

Output:

ROUNDED
-------
123.46

2.2 TRUNC()

 Truncates a number to the specified decimal places.


 Example:
 SELECT TRUNC(123.456, 2) AS TRUNCATED FROM DUAL;

Output:

TRUNCATED
---------
123.45

2.3 MOD()

 Returns the remainder of a division.


 Example:
 SELECT MOD(10, 3) AS REMAINDER FROM DUAL;

Output:
REMAINDER
---------
1

2.4 POWER()

 Raises a number to the power of another number.


 Example:
 SELECT POWER(2, 3) AS RESULT FROM DUAL;

Output:

RESULT
------
8

2.5 CEIL()

 Returns the smallest integer greater than or equal to the given number.
 Example:
 SELECT CEIL(12.3) AS CEIL_VALUE FROM DUAL;

Output:

CEIL_VALUE
----------
13

2.6 FLOOR()

 Returns the largest integer less than or equal to the given number.
 Example:
 SELECT FLOOR(12.9) AS FLOOR_VALUE FROM DUAL;

Output:

FLOOR_VALUE
-----------
12

2.7 ABS()

 Returns the absolute value of a number.


 Example:
 SELECT ABS(-15) AS ABSOLUTE FROM DUAL;

Output:

ABSOLUTE
--------
15
3. String Conversion Functions

These functions convert data between different formats (number to string, string to number, date to
string, etc.).

3.1 TO_CHAR()

 Converts a date or number to a string.


 Example (Date to String):
 SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH:MI:SS AM') AS DATE_STR
FROM DUAL;

Output:

DATE_STR
----------------------
19-MAR-2025 02:30:45 PM

 Example (Number to String):


 SELECT TO_CHAR(12345, '99999') AS NUM_STR FROM DUAL;

Output:

NUM_STR
-------
12345

3.2 TO_NUMBER()

 Converts a string to a number.


 Example:
 SELECT TO_NUMBER('12345') + 10 AS SUM_RESULT FROM DUAL;

Output:

SUM_RESULT
----------
12355

3.3 TO_DATE()

 Converts a string to a date.


 Example:
 SELECT TO_DATE('19-03-2025', 'DD-MM-YYYY') AS DATE_VALUE FROM DUAL;

Output:

DATE_VALUE
-------------------
2025-03-19

3.4 CAST()

 Converts one data type to another.


 Example (String to Date):
 SELECT CAST('2025-03-19' AS DATE) AS CAST_DATE FROM DUAL;

Output:

CAST_DATE
-------------------
2025-03-19

CREATING TABLES WITH RELATIONSHIP:

It is important to understand and design relationships among tables in a relational database like
SQL Server. In a relational database, each table is connected to another table using the Primary-
Foreign Key constraints.

Table relationships in SQL Server database are of three types:

1. One-to-One
2. One-to-Many
3. Many-to-Many

One-to-One Relation
In One-to-One relationship, one record of the first table will be linked to zero or one record of
another table. For example, each employee in the Employee table will have a corresponding row
in EmployeeDetails table that stores the current passport details for that particular employee. So,
each employee will have zero or one record in the EmployeeDetails table. This is called zero or
one-to-one relationship.

Below, EmployeeID column is the primary key as well as foreign key column in the
EmloyeeDetails table that linked to EmployeeID of the Employee table. This forms zero or one-
to-one relation.

The following query will display data from both the tables.
SELECT * FROM Employee
SELECT * FROM EmployeeDetails

The following is the result of the above queries that demonstrate how each employee has none or
just one corresponding record in EmployeeDetails table.

One-to-Many Relation

One-to-Many is the most commonly used relationship among tables. A single record from one
table can be linked to zero or more rows in another table.

Let's take an example of the Employee and Address table in the HR database. The Employee
table stores employee records where EmployeeID id the primary key. The Address table holds
the addresses of employees where AddressID is a primary key and EmployeeID is a foreign key.
Each employee will have one record in the Employee table. Each employee can have many
addresses such as Home address, Office Address, Permanent address, etc.

The Employee and Address tables are linked by the key column EmployeeID. It is a foreign key in
the Address table linking to the primary key EmployeeID in the Employee table. Thus, one record of
the Employee table can point to multiple records in the Address table. This is a One-to-Many
relationship.

The following query will display data from both the tables.

SELECT * FROM Employee


SELECT * FROM Address
The following is the result of the above queries to demonstrate how the data is related in one-to-
many relationship.

In the above data, each record in the Employee table associated with zero or more records in
the Address table, e.g. James Bond has zero address, John King has three addresses.

Many-to-Many Relation

Many-to-Many relationship lets you relate each row in one table to many rows in another table
and vice versa. As an example, an employee in the Employee table can have many skills from
the EmployeeSkill table and also, one skill can be associated with one or more employees.

The following figure demonstrates many-to-many relation between Employee and


SkillDescription table using the junction table EmployeeSkill.

Every employee in the Employee table can have one or many skills. Similarly, a skill in
the SkillDescription table can be linked to many employees. This makes a many-to-many
relationship

In the example above, the EmployeeSkill is the junction table that contains EmployeeID and
SkillID foreign key columns to form many-to-many relation between the Employee and
SkillDescription table. Individually, the Employee and EmployeeSkill have a one-to-many
relation and the SkillDescription and the EmployeeSkill tables have one-to-many relation. But,
they form many-to-many relation by using a junction table EmployeeSkill.
The following query will display data from all the tables.

SELECT * FROM Employee


SELECT * FROM EmployeeSkill
SELECT * FROM SkillDescription

The following is the result of the above queries that demonstrate how the data is related in
many-to-many relationship.

Implementation of Key and Integrity Constraints:

When creating tables in SQL, keys and integrity constraints ensure data consistency,
uniqueness, and relationships between tables. Below are different types of constraints with
their implementations.

KEY CONSTRAINTS

There are 3 most important Key constraints one should consider mainly they are

1. PRIMARY KEY

2. FOREIGN KEY

3. UNIQUE

PRIMARY KEY CONSTRAINT:

 It ensures uniqueness and non-null values in a column or combination of columns.


Example: Creating an EMPLOYEES table with a Primary Key

CREATE TABLE EMPLOYEES (

EMPLOYEEID NUMBER PRIMARY KEY

FIRSTNAME VARCHAR2(50),

LASTNAME VARCHAR2(50),

EMAIL VARCHAR2(50) UNIQUE,

PHONE VARCHAR2(15),

HIREDATE DATE

);

 Here, EMPLOYEEID is the Primary Key, and EMAIL has a Unique Constraint.

FOREIGN KEY CONSTRAINT:

 It Ensures a relationship between two tables by linking a column in one table to the
Primary Key in another.

Example: Creating DEPARTMENTS and linking EMPLOYEES to it

CREATE TABLE DEPARTMENTS (

DEPARTMENTID NUMBER PRIMARY KEY,

DEPT_NAME VARCHAR2(50) NOT NULL);

CREATE TABLE EMPLOYEES (

EMPLOYEEID NUMBER PRIMARY KEY,

FIRSTNAME VARCHAR2(50),

LASTNAME VARCHAR2(50),

DEPARTMENTID NUMBER,

CONSTRAINT FK_DEPT FOREIGN KEY (DEPARTMENTID) REFERENCES


DEPARTMENTS(DEPARTMENTID) ON DELETE CASCADE);

 The Foreign Key (DEPARTMENTID) in EMPLOYEES references the Primary Key


(DEPARTMENTID) in DEPARTMENTS.

UNIQUE CONSTRAINT:

 Ensures that values in a column are not duplicated.


Example: Enforcing unique email addresses

CREATE TABLE EMPLOYEES (

EMPLOYEEID NUMBER PRIMARY KEY,

EMAIL VARCHAR2(50) UNIQUE

);

Now, no two employees can have the same email.

INTEGRITY CONSTRAINTS

There are the integrity constraints one should consider mainly they are

1. NOT NULL

2. CHECK

3. DEFAULT

NOT NULL CONSTRAINT:

 Ensures that a column cannot have NULL values.

Example: Making sure names are always provided

CREATE TABLE EMPLOYEES (

EMPLOYEEID NUMBER PRIMARY KEY,

FIRSTNAME VARCHAR2(50) NOT NULL,

LASTNAME VARCHAR2(50) NOT NULL

);

Employees must have both first and last names.

CHECK CONSTRAINT

 Restricts column values to a specific condition.

Example: Ensuring salary is positive

CREATE TABLE EMPLOYEES (

EMPLOYEEID NUMBER PRIMARY KEY,

SALARY NUMBER CHECK (SALARY > 0)


);

This prevents inserting negative or zero salary values.

DEFAULT CONSTRAINT:

 Assigns a default value when no value is provided.

Example: Default hire date to today

CREATE TABLE EMPLOYEES (

EMPLOYEEID NUMBER PRIMARY KEY,

HIREDATE DATE DEFAULT SYSDATE

);

If HIREDATE is not provided, it automatically gets the current date.

An example implementing all constraints:

CREATE TABLE EMPLOYEES (

EMPLOYEEID NUMBER PRIMARY KEY,

FIRSTNAME VARCHAR2(50) NOT NULL,

LASTNAME VARCHAR2(50) NOT NULL,

EMAIL VARCHAR2(50) UNIQUE,

PHONE VARCHAR2(15),

SALARY NUMBER CHECK (SALARY > 0),

HIREDATE DATE DEFAULT SYSDATE,

DEPARTMENTID NUMBER,

CONSTRAINT FK_DEPT FOREIGN KEY (DEPARTMENTID) REFERENCES


DEPARTMENTS(DEPARTMENTID) ON DELETE CASCADE

);

NESTED QUERIES:

• One of the most powerful features of SQL is nested queries.

• A nested query is a query that has another query embedded within it; the embedded
query is called a subquery.
• The embedded query can of course be a nested query itself; thus queries that have very
deeply nested structures are possible.

• A nested query in SQL contains a query inside another query. The outer query will use
the result of the inner query. For instance, a nested query can have
two SELECT statements, one on the inner query and the other on the outer query.

How to Write Nested Query in SQL?

• We can write a nested query in SQL by nesting a SELECT statement within


another SELECT statement. The outer SELECT statement uses the result of the
inner SELECT statement for processing.

• The general syntax of nested queries will be:

SELECT column_name [, column_name ]

FROM table1 [, table2 ]

WHERE column_name OPERATOR

SELECT column_name [, column_name ]

FROM table1 [, table2 ]

[WHERE]

);

Example: Let's create the Employees and Awards tables:


Types of Nested Queries:

• Nested queries in SQL can be classified into two different types:

• Independent Nested Queries

• Co-related Nested Queries

INDEPENDENT NESTED QUERIES: In independent nested queries, the execution order is from
the innermost query to the outer query. An outer query won't be executed until its inner query
completes its execution. The outer query uses the result of the inner query. Operators such
as IN, NOT IN, ALL, and ANY are used to write independent nested queries.
• The IN operator checks if a column value in the outer query's result is present in the inner
query's result. The final result will have rows that satisfy the IN condition.

• The NOT IN operator checks if a column value in the outer query's result is not present in
the inner query's result. The final result will have rows that satisfy the NOT IN condition.

• The ALL operator compares a value of the outer query's result with all the values of the
inner query's result and returns the row if it matches all the values.

• The ANY operator compares a value of the outer query's result with all the inner query's
result values and returns the row if there is a match with any value.

Example 1: IN

• Select all employees who won an award.

• SELECT id, name FROM Employees

WHERE id IN (SELECT employee_id FROM Awards);

Example 2: NOT IN

• Select all employees who never won an award.

• SELECT id, name FROM Employees


WHERE id NOT IN (SELECT employee_id FROM Awards);

• Example 3: ALL

• Select all Developers who earn more than all the Managers

• SELECT * FROM Employees

WHERE role = 'Developer'

AND salary > ALL (

SELECT salary FROM Employees WHERE role = 'Manager'

);

• Example 4: ANY

• Select all Developers who earn more than any Manager

• SELECT * FROM Employees

WHERE role = 'Developer'

AND salary > ANY (

SELECT salary FROM Employees WHERE role = 'Manager'

);
CO-RELATED NESTED QUERIES: In co-related nested queries, the inner query uses the values
from the outer query to execute the inner query for every row processed by the outer query. The co-
related nested queries run slowly because the inner query is executed for every row of the outer
query's result.

• Select all employees whose salary is above the average salary of employees in their role.

• SELECT * FROM Employees emp1

WHERE salary > (

SELECT AVG(salary)

FROM Employees emp2

WHERE emp1.role = emp2.role

);

SUB QUERIES: A subquery is a SQL query nested inside another query (called the main or outer
query). It helps in breaking down complex queries into smaller parts and retrieving results
dynamically. The subquery executes first, and its result is used by the main query.

Where Do You Create Subqueries?

Subqueries can be used in different parts of a SQL query:

• In the WHERE clause → To filter data based on another query's result.


• In the FROM clause → To use a subquery as a temporary table.
• In the SELECT clause → To return a single value for each row.
• In INSERT, UPDATE, and DELETE statements → To perform operations based on
another query's result.

To understand subqueries, break them down step by step:

1. Start with the Subquery Execution First

• The subquery executes first and returns a result.


• The main query then uses this result.

2. Identify Where the Subquery Is Used

• WHERE → Filters data based on the subquery result.


• FROM → Treats the subquery result as a table.
• SELECT → Uses the subquery to calculate values.

3. Check the Number of Rows Returned

• Single-row subquery → Returns one value (use =, >, <, <=, >=, <>).
• Multi-row subquery → Returns multiple values (use IN, ANY, ALL).
• Multi-column subquery → Returns multiple columns (use with IN).

Example 1: Subquery in WHERE Clause

Find students with the highest marks:

SELECT name, marks

FROM student

WHERE marks = (SELECT MAX(marks) FROM student);

Example 2: Subquery in FROM Clause

Find the average marks of students in each department:

SELECT dept, AVG(marks) AS avg_marks

FROM (SELECT dept, marks FROM student) AS temp

GROUP BY dept;

Example 3: Subquery in SELECT Clause

Find employees with their department's average salary:

SELECT name, salary,

(SELECT AVG(salary) FROM employee) AS company_avg_salary

FROM employee;
Aggregation: Aggregate functions in DBMS perform calculations on multiple rows of a column and
return a single value. These are commonly used with the GROUP BY clause.

Common Aggregate Functions

• COUNT() – Returns the number of rows.


• SUM() – Returns the sum of a column’s values.
• AVG() – Returns the average of a column’s values.
• MIN() – Returns the minimum value.
• MAX() – Returns the maximum value.

So we will use the following table to perform this operations

Student_ID Name Department Marks Fees


101 Alice CSE 85 50000
102 Bob ECE 78 48000
103 Charlie CSE 92 52000
104 David ME 68 47000
105 Eva ECE 75 49000

• COUNT() - Counting total students


SELECT COUNT(*) AS Total_Students FROM Student;

Output: 5

• SUM() - Total fees collected


SELECT SUM(Fees) AS Total_Fees FROM Student;

Output: 246000

• AVG() - Average Marks of all students


SELECT AVG(Marks) AS Average_Marks FROM Student;

Output: 79.6

• MIN() - Minimum Marks


SELECT MIN(Marks) AS Min_Marks FROM Student;

Output: 68

• MAX() - Maximum Marks


SELECT MAX(Marks) AS Max_Marks FROM Student;

Output: 92

Grouping:

1. GROUP BY Clause

• The GROUP BY clause is used to group rows that have the same values in specified columns.
• It is typically used with aggregate functions like COUNT(), SUM(), AVG(), MIN(), and
MAX().
• Syntax:

SELECT column_name, aggregate_function(column_name)


FROM table_name
GROUP BY column_name;
• Example: Count the number of students in each department.

SELECT Department, COUNT(Student_ID) AS Student_Count


FROM Student
GROUP BY Department;

Output:
Department Student_count
CSE 2
ECE 2
ME 1

2. HAVING Clause:

• The HAVING clause is used to filter groups based on aggregate function results. It is similar
to WHERE, but WHERE cannot be used with aggregate functions.
• Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;

• Using HAVING to Filter Aggregates (Departments with Average Marks > 75)
• SELECT Department, AVG(Marks) AS Avg_Marks
FROM Student
GROUP BY Department
HAVING AVG(Marks) > 75;
Output:

Department Avg_Marks
Alice 85
Charlie 92

Ordering:

3. ORDER BY Clause

• The ORDER BY clause is used to sort the result set in ascending (ASC) or descending
(DESC) order.
• Syntax:

SELECT column_name
FROM table_name
ORDER BY column_name [ASC|DESC];
• Retrieve student names and marks, sorted by marks in descending order.
SELECT Name, Marks
FROM Student
ORDER BY Marks DESC;
Output:
Name Marks
Charlie 92
Alice 85
Bob 78
Eva 75
David 68

IMPLEMENTATION OF DIFFERENT TYPES OF JOINS:

SQL joins are the foundation of database management systems, enabling the combination of data
from multiple tables based on relationships between columns. Joins allow efficient data retrieval,
which is essential for generating meaningful observations and solving complex business queries.

SQL JOIN:

• SQL JOIN clause is used to query and access data from multiple tables by
establishing logical relationships between them. It can access data from multiple tables
simultaneously using common key values shared across different tables. We can use SQL
JOIN with multiple tables. It can also be paired with other clauses, the most popular use will
be using JOIN with WHERE clause to filter data retrieval.

• A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.

• Consider the two tables, Student and StudentCourse, which share a common
column ROLL_NO. Using SQL JOINS, we can combine data from these tables based on
their relationship, allowing us to retrieve meaningful information like student details along
with their enrolled courses.
• Both these tables are connected by one common key (column) i.e ROLL_NO. We can
perform a JOIN operation using the given SQL query:

• SELECT s.roll_no, s.name, s.address, s.phone, s.age, sc.course_id


FROM Students
JOIN StudentCourse sc ON s.roll_no = sc.roll_no;
Types of JOINS in SQL:

• There are many types of Joins in SQL. Depending on the use case, we can use different type
of SQL JOIN clause. Below, we explain the most commonly used join types with syntax and
examples:

• INNER JOIN

• LEFT JOIN

• RIGHT JOIN

• FULL JOIN

• Natural Join

1. SQL INNER JOIN: The INNER JOIN keyword selects all rows from both the tables as long as
the condition is satisfied. This keyword will create the result-set by combining all rows from both the
tables where the condition satisfies i.e value of the common field will be the same.

• Syntax

• SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;

• Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.

• Example: This query will show the names and age of students enrolled in different courses.
• Query:

• SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student


INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;

2. SQL LEFT JOIN: LEFT JOIN returns all the rows of the table on the left side of the join and
matches rows for the table on the right side of the join. For the rows for which there is no matching
row on the right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER
JOIN.

• Syntax

• SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_colum

• Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same.n =
table2.matching_column;

• In this example, the LEFT JOIN retrieves all rows from the Student table and the matching
rows from the StudentCourse table based on the ROLL_NO column.

• Query:

• SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
3. SQL RIGHT JOIN: RIGHT JOIN returns all the rows of the table on the right side of the
join and matching rows for the table on the left side of the join. It is very similar to LEFT JOIN for
the rows for which there is no matching row on the left side, the result-set will contain null. RIGHT
JOIN is also known as RIGHT OUTER JOIN.

• Syntax

• SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

• Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are the same.

• In this example, the RIGHT JOIN retrieves all rows from the StudentCourse table and the
matching rows from the Student table based on the ROLL_NO column.

• Query:

• SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
4. SQL FULL JOIN: FULL JOIN creates the result-set by combining results of both LEFT
JOIN and RIGHT JOIN. The result-set will contain all the rows from both tables. For the rows for
which there is no matching, the result-set will contain NULL values.

• Syntax

• SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;

• This example demonstrates the use of a FULL JOIN, which combines the results of
both LEFT JOIN and RIGHT JOIN. The query retrieves all rows from
the Student and StudentCourse tables. If a record in one table does not have a matching
record in the other table, the result set will include that record with NULL values for the
missing fields

• Query:

• SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

• Output

NAME COURSE_ID

HARSH 1

PRATIK 2
RIYANKA 2

DEEP 3

SAPTARHI 1

DHANRAJ NULL

ROHIT NULL

NIRAJ NULL

NULL 4

NULL 5

NULL 4

5. SQL Natural Join: Natural join can join tables based on the common columns in the tables being
joined. A natural join returns all rows by matching values in common columns having same name
and data type of columns and that column should be present in both tables.

• Both table must have at least one common column with same column name and same data
type.

• The two table are joined using Cross join.

• DBMS will look for a common column with same name and data type. Tuples having exactly
same values in common columns are kept in result.

• Look at the two tables below- Employee and Department

• SELECT *

FROM table1

NATURAL JOIN table2;


• Find all Employees and their respective departments.

• SELECT *

FROM Employee

NATURAL JOIN Department;

• Output:

VIEWS:

• In SQL, views contain rows and columns similar to a table, however, views don't hold the
actual data.

• You can think of a view as a virtual table environment that's created from one or more tables
so that it's easier to work with data.
Creation and Dropping of Views

• A view is a virtual table in SQL that is based on the result of a SELECT query. It does not
store data physically but provides a way to simplify complex queries.

1. Creating a View

Syntax:
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Creating a View for CSE Students

CREATE VIEW CSE_Students AS


SELECT Student_ID, Name, Marks
FROM Student
WHERE Department = 'CSE';

Selecting Data from the View:

SELECT * FROM CSE_Students;


Output:

Student_ID Name Marks


101 Alice 85
103 Charlie 92
2. Dropping a View

If you no longer need a view, you can remove it using DROP VIEW.

Syntax:
DROP VIEW view_name;

Dropping the CSE_Students View

DROP VIEW CSE_Students;

Types of Views:

SQL views are classified into two types

• Updatable Views
• Non-Updatable Views

Updatable Views: An updatable view allows users to perform INSERT, UPDATE, and DELETE
operations, which reflect changes in the underlying table(s).

• Conditions for Updatable Views

A view can be updated if:

• It is based on a single table.

• It includes a primary key or unique key to identify rows uniquely.

• It does not use aggregate functions (SUM, COUNT, etc.).

• It does not use DISTINCT, GROUP BY, HAVING, UNION, etc.

• Example: Updatable View

• Consider a Customers table:

• CREATE VIEW customer_view AS

SELECT customer_id, first_name, last_name, email

FROM Customers;

• Since this view is based on a single table without any complex operations, we can update
records using:

• UPDATE customer_view

SET email = 'newemail@example.com'

WHERE customer_id = 101;

• This change will be reflected in the Customers table.

Non-Updatable Views: A non-updatable view is a read-only view, meaning we can SELECT data
but cannot perform INSERT, UPDATE, or DELETE operations.
• When is a View Non-Updatable?

• It involves multiple tables (joins).


• It includes aggregate functions (SUM, AVG, etc.).
• It uses DISTINCT, GROUP BY, HAVING, UNION, etc.
• It includes calculated columns (e.g., price * quantity).

• Example: Non-Updatable View (Using JOIN)

• CREATE VIEW order_summary AS

SELECT Customers.first_name, Orders.order_id, Orders.amount

FROM Customers

JOIN Orders ON Customers.customer_id = Orders.customer_id;

• Since this view is based on multiple tables using a JOIN, we cannot update it directly.

• If a view is non-updatable but needs modifications, we can use INSTEAD OF Triggers to


allow updates on it.

• Example:

• CREATE TRIGGER update_order_summary

INSTEAD OF UPDATE ON order_summary

FOR EACH ROW

BEGIN

UPDATE Orders SET amount = NEW.amount WHERE order_id = OLD.order_id;

END;

• This ensures that updates on the view are redirected to the appropriate base table.

Relational Set Operations: Relational Set Operations refer to a group of operations in Relational
Algebra that manipulate relations (tables) based on set theory principles. These operations allow
the combination, comparison, and transformation of relations to retrieve meaningful results. To
perform these operations, the relations must often be union-compatible, meaning they have the
same number of attributes with matching data types. These operations provide fundamental ways
to manipulate relational data and are crucial for query processing in relational databases.

In Relational Algebra, the following set operations are available:

1. Union ( ∪ ): Combines tuples from two relations, removing duplicates.


o Condition: Both relations must be union-compatible (same number of attributes and
same attribute domains).
o Example: R(A,B)={(1,2),(3,4)}
o S(A,B)={(3,4),(5,6)}
o R∪S={(1,2),(3,4),(5,6)}
2. Intersection ( ∩ ): Retrieves tuples that are common to both relations.

o Condition: Both relations must be union compatible.


o Example:
o R∩S={(3,4)}

3. Set-Difference ( − ): Retrieves tuples that are in the first relation but not in the second.

o Condition: Both relations must be union-compatible.


o Example: R−S={(1,2)}R - S = \{(1,2)\}R−S={(1,2)}

4. Cartesian Product ( × ): Pairs every tuple from the first relation with every tuple from the second
relation.

 Condition: No restriction on schema compatibility.


 Example: If R(A)={1,2},S(B)={x,y}
 Then:
 R×S={(1,x),(1,y),(2,x),(2,y)}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy