0% found this document useful (0 votes)
18 views20 pages

Unit 3

The document covers various SQL concepts, including differences between SELECT and PROJECT operations, the use of the WHERE clause, arithmetic and logical operations, and integrity constraints. It explains the GROUP BY clause, types of joins, and relational set operations like UNION, INTERSECT, and EXCEPT, providing examples for each. Additionally, it discusses the creation of tables with relationships, nested queries, and the significance of SQL functions for date, time, numeric, and string data.
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)
18 views20 pages

Unit 3

The document covers various SQL concepts, including differences between SELECT and PROJECT operations, the use of the WHERE clause, arithmetic and logical operations, and integrity constraints. It explains the GROUP BY clause, types of joins, and relational set operations like UNION, INTERSECT, and EXCEPT, providing examples for each. Additionally, it discusses the creation of tables with relationships, nested queries, and the significance of SQL functions for date, time, numeric, and string data.
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/ 20

Starting UNIT 3 – DBMS — clean, simple BEFA style without any extra comments.

First, covering all 2 Marks Questions one-by-one:

1. What is the difference between the SELECT and PROJECT operations in SQL?

 SELECT operation chooses rows based on conditions.

 PROJECT operation chooses columns to display.

📘 Example:

 SELECT → Students where marks > 80

 PROJECT → Only Name and Marks of Students

2. Explain how the WHERE clause is used in SQL queries.

 The WHERE clause is used to filter rows based on conditions.

📘 Example:

SELECT * FROM Student

WHERE Marks > 80;

It retrieves only those students whose marks are greater than 80.

3. What are arithmetic operations in SQL? Provide an example.

 Arithmetic operations in SQL perform calculations like addition (+), subtraction (-),
multiplication (*), division (/).

📘 Example:

SELECT Name, Marks + 5 AS BonusMarks

FROM Student;

Adds 5 bonus marks to each student’s marks.

4. Explain how logical operations (AND, OR, NOT) are used in SQL queries.

 Logical operations combine multiple conditions:


o AND → both conditions must be true

o OR → any one condition is true

o NOT → negates a condition

📘 Example:

SELECT * FROM Student

WHERE Marks > 80 AND Class = '10th';

Fetches students with Marks > 80 and Class 10th.

5. What is the purpose of SQL functions for date and time? Provide an example.

 SQL Date and Time functions are used to extract, modify, or calculate date and time
information.

📘 Example:

SELECT CURRENT_DATE;

Shows today's date.

Another example:

SELECT YEAR(DOB) FROM Student;

Finds the year of birth of students.

6. What are integrity constraints in SQL? Provide examples of primary key and foreign key
constraints.

 Integrity constraints ensure data correctness.

📘 Examples:

 Primary Key → Uniquely identifies a record.

RollNo INT PRIMARY KEY

 Foreign Key → Links tables.

FOREIGN KEY (RollNo) REFERENCES Student(RollNo)


7. What is the GROUP BY clause used for in SQL?

 GROUP BY groups rows that have the same values into summary rows (like totals,
averages).

📘 Example:

SELECT Class, AVG(Marks)

FROM Student

GROUP BY Class;

Finds average marks for each class.

8. Explain how to use ORDER BY in SQL queries.

 ORDER BY sorts the result in ascending (ASC) or descending (DESC) order.

📘 Example:

SELECT * FROM Student

ORDER BY Marks DESC;

Shows students sorted by highest marks first.

9. What are the different types of joins in SQL?

 Types of Joins:

o INNER JOIN → common data

o LEFT JOIN → all left + matching right

o RIGHT JOIN → all right + matching left

o FULL JOIN → all data from both tables

10. What are relational set operations in SQL? Provide an example.

 Relational set operations combine results of two queries:

o UNION → all distinct rows


o INTERSECT → common rows

o EXCEPT → rows in first query but not in second

📘 Example:

SELECT Name FROM Student

UNION

SELECT Name FROM Alumni;

Combines names from Student and Alumni tables.

All 2 Marks of Unit 3 completed.

Now ready to immediately continue with Unit 3 – 10 Marks Questions one-by-one.


Proceeding to next: Q11 ✅

Continuing immediately with Unit 3 – 10 Marks Questions:

📘 11. How Are Arithmetic and Logical Operations Used in SQL Queries? Illustrate with
Examples 🎯

🧠 Arithmetic Operations in SQL

 Arithmetic operations are used to perform calculations on numeric data.

📘 Common Operators:

 Addition (+)

 Subtraction (-)

 Multiplication (*)

 Division (/)

 Modulus (%)

📘 Example 1: Adding bonus marks

SELECT Name, Marks + 5 AS BonusMarks

FROM Student;
Adds 5 marks to each student.

📘 Example 2: Calculating half salary

SELECT EmployeeName, Salary / 2 AS HalfSalary

FROM Employee;

🧠 Logical Operations in SQL

 Logical operations combine multiple conditions in WHERE clause.

📘 Common Operators:

 AND

 OR

 NOT

📘 Example 1: AND

SELECT * FROM Student

WHERE Marks > 80 AND Class = '10th';

Fetch students with Marks > 80 and Class 10th.

📘 Example 2: OR

SELECT * FROM Student

WHERE Marks > 90 OR Class = '12th';

Fetch students who either have marks above 90 or are in class 12th.

📘 Example 3: NOT

SELECT * FROM Student

WHERE NOT Class = '9th';

Fetch students not from Class 9th.

📘 Quick Summary Table:


Operation Type Example SQL

Arithmetic (+, -, *, /) Update Marks or Salary

Logical (AND, OR, NOT) Filter data based on multiple conditions

✅ Conclusion:

Arithmetic and logical operations make SQL queries powerful by allowing calculations and
filtering based on multiple conditions.

Continuing immediately with next:

Starting Q12 now! ✅

Continuing immediately with the next 10-mark question:

📘 12. Discuss Different Types of SQL Functions (Date and Time, Numeric, String Conversion).
Provide Examples for Each Type 🎯

🧠 What Are SQL Functions?

SQL functions are predefined operations that perform tasks like calculations, formatting, and
processing data.

Functions are very useful for simplifying queries.

🔹 Types of SQL Functions:

1. Date and Time Functions 📅

 Used to work with dates and times.

📘 Examples:

 CURRENT_DATE → Gets today's date.

SELECT CURRENT_DATE;
 YEAR() → Extracts year from a date.

SELECT YEAR(DOB) FROM Student;

 NOW() → Current date and time.

SELECT NOW();

2. Numeric Functions 🔢

 Perform calculations on numeric values.

📘 Examples:

 ROUND() → Rounds a number.

SELECT ROUND(123.456, 2);

Result: 123.46

 ABS() → Absolute value.

SELECT ABS(-10);

Result: 10

 POWER() → Raise a number to a power.

SELECT POWER(2, 3);

Result: 8

3. String Functions 📝

 Work with text data.

📘 Examples:

 UPPER() → Converts text to uppercase.

SELECT UPPER(Name) FROM Student;

Result: JOHN, MARY

 LOWER() → Converts text to lowercase.

SELECT LOWER(Name) FROM Student;


 CONCAT() → Joins two strings.

SELECT CONCAT(FirstName, ' ', LastName) AS FullName

FROM Employee;

📘 Quick Table:

Function Type Example Usage

Date and Time CURRENT_DATE(), YEAR(), NOW()

Numeric ROUND(), ABS(), POWER()

String UPPER(), LOWER(), CONCAT()

✅ Conclusion:

SQL functions save time and reduce query complexity by performing common operations
directly inside SQL commands.

Continuing immediately with next:

Starting Q13 now! ✅

Continuing immediately with the next 10-mark question:

📘 13. Explain the Process of Creating Tables with Relationships. How Are Keys (Primary and
Foreign) and Integrity Constraints Implemented in SQL? Provide an Example 🎯

🧠 Creating Tables with Relationships

In relational databases, relationships between tables are created using Primary Keys and
Foreign Keys.

 Primary Key uniquely identifies a record inside a table.

 Foreign Key connects two tables by referencing the Primary Key of another table.
Integrity constraints like NOT NULL, UNIQUE, CHECK, etc., ensure that the data stored is correct
and consistent.

🔹 Steps to Create Tables with Relationships:

1. Create a Main Table (with Primary Key)

📘 Example: Create a Student table

CREATE TABLE Student (

RollNo INT PRIMARY KEY,

Name VARCHAR(50) NOT NULL,

Class VARCHAR(20)

);

 Here, RollNo is the Primary Key.

 Name cannot be NULL.

2. Create a Related Table (with Foreign Key)

📘 Example: Create a Marks table that refers to Student

CREATE TABLE Marks (

MarkID INT PRIMARY KEY,

RollNo INT,

Subject VARCHAR(50),

Score INT CHECK (Score >= 0 AND Score <= 100),

FOREIGN KEY (RollNo) REFERENCES Student(RollNo)

);

 RollNo in Marks table is a Foreign Key.

 CHECK constraint ensures Score is between 0 and 100.


📘 Real-World Example:

In a Library System:

 Books table (BookID as Primary Key)

 Borrowers table (BorrowerID as Primary Key)

 Borrow table (BookID and BorrowerID as Foreign Keys)

These links ensure that a Borrow record cannot exist unless both the Book and Borrower exist.

📘 Quick Summary Table:

Key Type Purpose Example

Primary Key Unique identification RollNo in Student

Foreign Key Create link between tables RollNo in Marks refers to Student

✅ Conclusion:

Creating tables with proper Primary and Foreign keys and integrity constraints ensures that the
database is accurate, consistent, and logically connected.

Continuing immediately with next:

Starting Q14 now! ✅

Continuing immediately with the next 10-mark question:

📘 14. Explain Nested Queries and Subqueries in SQL. How Do They Differ? Provide Examples
to Demonstrate Their Usage 🎯

🧠 What are Subqueries and Nested Queries?

 Subquery: A query inside another query.

 Nested Query: Another name for a subquery (both are same).


They help in solving complex problems step-by-step.

📘 Real-life example:
First find the highest scorer (subquery), then find their details (main query).

🔹 How They Work:

 Subquery is written inside parentheses ( ).

 It is used in WHERE, FROM, or SELECT clause.

 The main query uses the result of the subquery.

🔹 Types of Subqueries:

1. Single-Row Subquery

Returns only one value.

📘 Example: Find students whose marks are greater than the average marks.

SELECT Name

FROM Student

WHERE Marks > (SELECT AVG(Marks) FROM Student);

2. Multi-Row Subquery

Returns multiple values.

📘 Example: Find students enrolled in courses offered by a certain department.

SELECT Name

FROM Student

WHERE Department IN (SELECT Department FROM Courses WHERE CourseName = 'Computer


Science');

🔹 Difference between Subquery and Nested Query


Subquery Nested Query

A query inside another query Same as Subquery (just another name)

Used in SELECT, FROM, WHERE Used in SELECT, FROM, WHERE

There is no real difference — both mean the same thing.

📘 Quick Notes:

 Subquery always runs first, main query uses its result.

 Subqueries make complex SQL problems easier.

 Can be correlated (depends on outer query) or independent.

✅ Conclusion:

Subqueries (Nested Queries) help to break down complex queries and solve them step-by-step.
They are a powerful tool to simplify difficult SQL operations.

Continuing immediately with next:

Starting Q15 now! ✅

Continuing immediately with the next 10-mark question:

📘 15. Explain How the GROUP BY Clause is Used in SQL. Discuss Its Significance in Aggregation
Operations. Provide an Example with Aggregate Functions Like COUNT, SUM, AVG 🎯

🧠 What is GROUP BY in SQL?

 GROUP BY is used to arrange identical data into groups.

 It is mostly used with aggregate functions like COUNT, SUM, AVG, MAX, MIN.

📘 Real-life example:
Find the total marks obtained by students class-wise.
🔹 Why is GROUP BY Important?

 It summarizes data.

 Helps in generating reports like sales per region, marks per class, total salary per
department.

🔹 Aggregate Functions Used with GROUP BY:

Function Use

COUNT() Number of records

SUM() Total value

AVG() Average value

MAX() Maximum value

MIN() Minimum value

📘 Example Query:

Find the average marks of students class-wise:

SELECT Class, AVG(Marks) AS AverageMarks

FROM Student

GROUP BY Class;

 Here, students are grouped by Class.

 AVG(Marks) is calculated for each class separately.

📘 Another Example:

Find the number of students in each class:

SELECT Class, COUNT(RollNo) AS TotalStudents

FROM Student

GROUP BY Class;
 COUNT() gives how many students are there in each class.

📘 Quick Rules of GROUP BY:

 SELECT columns must appear in GROUP BY if they are not used in aggregate functions.

 GROUP BY must come after WHERE and before ORDER BY in SQL query structure.

✅ Conclusion:

GROUP BY is used to summarize and analyze large amounts of data by grouping rows based on
one or more columns and applying aggregate functions to each group.

Continuing immediately with next:

Starting Q16 now! ✅

Continuing immediately with the next 10-mark question:

📘 16. Write an SQL Query That Uses the GROUP BY Clause to Find the Total Sales for Each
Product Category 🎯

🧠 Problem Description:

We need to calculate the total sales amount for each product category.
This is a typical use case of GROUP BY with SUM() function.

📘 Step-by-Step SQL Query:

Assume we have a table called Sales:

SaleID ProductCategory Amount

1 Electronics 5000

2 Furniture 3000

3 Electronics 4500
SaleID ProductCategory Amount

4 Clothing 1500

5 Furniture 2000

SQL Query to find total sales per product category:

SELECT ProductCategory, SUM(Amount) AS TotalSales

FROM Sales

GROUP BY ProductCategory;

📘 Output:

ProductCategory TotalSales

Electronics 9500

Furniture 5000

Clothing 1500

📘 Explanation:

 ProductCategory groups the records.

 SUM(Amount) adds the sales amounts for each group.

 GROUP BY ensures that totals are calculated separately for Electronics, Furniture, and
Clothing.

✅ Conclusion:

Using GROUP BY with SUM() allows you to summarize sales data and analyze business
performance by product categories or any other grouping factors.
Continuing immediately with next:

Starting Q17 now! ✅

Continuing immediately with the next 10-mark question:

📘 17. Discuss the Different Types of Joins in SQL (INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL
JOIN) with Examples 🎯

🧠 What Are Joins?

 Joins are used in SQL to combine data from two or more tables based on related
columns.

📘 Real-life example:
In a school database, you can join the Student table and Marks table using the RollNo field to
get complete information about each student.

🔹 Types of Joins:

1. INNER JOIN 🔗

 Returns only matching rows from both tables.

📘 Example:

SELECT Student.Name, Marks.Score

FROM Student

INNER JOIN Marks

ON Student.RollNo = Marks.RollNo;

Shows only students who have matching records in both Student and Marks tables.

2. LEFT JOIN 🔗

 Returns all rows from the left table and matching rows from the right table.
 If no match, NULL is shown for right table columns.

📘 Example:

SELECT Student.Name, Marks.Score

FROM Student

LEFT JOIN Marks

ON Student.RollNo = Marks.RollNo;

Shows all students, even if some have no marks.

3. RIGHT JOIN 🔗

 Returns all rows from the right table and matching rows from the left table.

 If no match, NULL is shown for left table columns.

📘 Example:

SELECT Student.Name, Marks.Score

FROM Student

RIGHT JOIN Marks

ON Student.RollNo = Marks.RollNo;

Shows all marks records, even if some students' information is missing.

4. FULL JOIN 🔗

 Returns all rows from both tables.

 NULLs are filled where there is no match.

📘 Example:

SELECT Student.Name, Marks.Score

FROM Student

FULL JOIN Marks

ON Student.RollNo = Marks.RollNo;
Shows all students and all marks, whether or not they match.

📘 Quick Table Summary:

Type of Join Result

INNER JOIN Only matching rows

LEFT JOIN All left rows + matching right rows

RIGHT JOIN All right rows + matching left rows

FULL JOIN All rows from both tables

✅ Conclusion:

Joins allow you to combine data from multiple tables to create complete, meaningful reports
based on relationships between tables.

Continuing immediately with next:

Starting Q18 now! ✅

Continuing immediately with the next 10-mark question:

📘 18. What Are Relational Set Operations in SQL? Explain UNION, INTERSECT, and EXCEPT
Operations with Examples 🎯

🧠 What Are Relational Set Operations?

 Set operations combine results from two or more SQL queries.

 The queries must have the same number of columns with compatible data types.

📘 Real-life example:
Combining lists of students from two different classes into one list without duplicates.

🔹 Types of Set Operations:


1. UNION ➕

 Combines the results of two queries.

 Removes duplicates automatically.

📘 Example:

SELECT Name FROM Class10

UNION

SELECT Name FROM Class12;

Shows all unique student names from Class10 and Class12.

2. INTERSECT ➗

 Returns only common rows present in both queries.

📘 Example:

SELECT Name FROM Class10

INTERSECT

SELECT Name FROM SportsTeam;

Shows names of students who are both in Class10 and SportsTeam.

3. EXCEPT (or MINUS) ➖

 Returns rows from the first query that are not in the second query.

📘 Example:

SELECT Name FROM Class10

EXCEPT

SELECT Name FROM SportsTeam;

Shows names of students who are in Class10 but not in SportsTeam.


📘 Important Notes:

 Column order and data types must match between the two queries.

 UNION removes duplicates by default.


(If you want all including duplicates, use UNION ALL.)

📘 Quick Table:

Set Operation Purpose Example Outcome

UNION Combine and remove duplicates All unique students from two classes

Common rows between two Students common to Class10 and


INTERSECT
queries SportsTeam

EXCEPT Rows in first query, not in second Students in Class10 but not in SportsTeam

✅ Conclusion:

Relational set operations like UNION, INTERSECT, and EXCEPT are powerful tools to combine,
compare, and filter results from multiple queries easily.

✅✅✅
Now all Unit 3 — 2 Marks and 10 Marks questions completed fully and properly!

If ready, I can immediately start Unit 4 — 2 Marks Questions in the same style.
Say Start Unit 4 ✅ if you want to continue!

You might also like