0% found this document useful (0 votes)
15 views26 pages

SQL Notes Class XII

The document provides an overview of database concepts, including definitions, components, and the need for databases in modern computing. It covers key concepts such as database management systems, relational databases, SQL commands, and data types, along with constraints and their usage in SQL. Additionally, it explains the importance of data integrity, security, and efficient management in database systems.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views26 pages

SQL Notes Class XII

The document provides an overview of database concepts, including definitions, components, and the need for databases in modern computing. It covers key concepts such as database management systems, relational databases, SQL commands, and data types, along with constraints and their usage in SQL. Additionally, it explains the importance of data integrity, security, and efficient management in database systems.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Youtube link : [Link]

v=zyrUM4s1PiU
Unit III Notes: Database Management Class 12 Classroomcode

 Introduction to Database Concepts and Their Need


Databases are essential components of modern computing that store, manage, and
retrieve data efficiently. Here’s an overview of what databases are, their key
concepts, and why they are important.

 What is a Database?
Definition: A database is an organized collection of data stored electronically. It
allows for easy access, management, and updating of data. Databases can range
from simple lists to complex systems handling large volumes of information.

 Components:
 Tables: The basic building blocks where data is stored. Each table consists of rows
(records) and columns (fields).
 Records: Individual entries in a table, representing a specific data instance (e.g., a
single customer's details).
 Fields: the columns in a table, defining the type of data stored (e.g., name, email,
address).
 Tuple: – A Tuple in DBMS refers to a single row in a relational table.

 Key Database Concepts (Database Management System (DBMS):

Definition: Software that manages and controls access to databases. It allows users
to create, update, and query databases.
Examples: MySQL, PostgreSQL, Oracle, Microsoft SQL Server.

 Schema:
Definition: A Database Schema defines the structure of a database, outlining how
data is organized and stored
Example: A schema might define tables for customers, orders, and products, and
specify how these tables are related.

 Architecture of DBMS : Query Language:


Definition: A language used to interact with a database, primarily to retrieve,
update, or manipulate data.
Examples: SQL (Structured Query Language) is the most common language used for
querying databases.

Need for Databases:

 Efficient Data Management:


Need: Organizes large amounts of data systematically, making it easier to retrieve,
update, and manage information.
Benefit: Reduces time and effort required to handle and process data.

 Data Integrity:
 Need: Ensures that data is accurate, consistent, and reliable.
 Benefit: Minimizes errors and maintains the quality of data over time.

 Data Security:
 Need: Protects sensitive data from unauthorized access and breaches.
 Benefit: Safeguards confidential information and complies with legal and regulatory
requirements.

 Concurrent Access:
 Need: Allows multiple users to access and work with the database simultaneously
without conflicts.
 Benefit: Facilitates teamwork and collaboration in real-time.

 Scalability:
 Need: Supports the growth of data and the increasing complexity of data
management needs.
 Benefit: Ensures that the database can handle expanding amounts of information
and user demands.

Relational Database Management System


The relational data model is a way of structuring data using relations (tables). It is
fundamental to relational databases and organizes data into tables with rows and
columns. Here’s a breakdown of key concepts in the relational data model:

1. Relation:
Definition: A relation, or table, is a collection of tuples (rows) that share the same
attributes (columns). It represents a specific type of entity or relationship in the
database.
Example: A table called Students that includes information about students, where
each row represents a student.

2. Attribute:
Definition: An attribute is a column in a table that represents a specific property or
characteristic of the entity described by the table. Each attribute has a name and a
data type.
Example: In the Students table, attributes might include StudentID, Name, and
DateOfBirth.
3. Tuple:
Definition: A tuple is a single row in a table. It represents a specific instance of the
entity or relationship described by the table.
Example: In the Students table, a tuple might be (123, 'Alice Smith', '2005-05-15'),
representing a specific student.

4. Domain:
Definition: A domain is the set of permissible values that an attribute can take. It
defines the type of data that can be stored in a column, such as integer, string, or
date.
Example: For the attribute DateOfBirth, the domain might be all valid date values.

5. Degree:
Definition: The degree of a relation (table) is the number of attributes (columns) it
has. It indicates the number of different pieces of information stored for each tuple.
 Example: If the Students table has three attributes (StudentID, Name, DateOfBirth),
its degree is 3.

6. Cardinality:
Definition: The cardinality of a relation (table) is the number of tuples (rows) it
contains. It represents the size of the table and the number of instances of the
entity.
 Example: If the Students table has 100 rows, its cardinality is 100.

 Keys in Relational Databases


Keys are fundamental to relational databases as they uniquely identify rows within a
table and establish relationships between tables. Here’s an overview of different
types of keys:

1. Candidate Key
A candidate key is an attribute or a set of attributes that can uniquely identify each
tuple (row) in a table. A table can have multiple candidate keys, but each one is a
potential primary key.
Characteristics:
 Must be unique for each row.
 Cannot contain null values.
Example: In a Student table, StudentID and Email might both be candidate keys if each
is unique for every student.

2. Primary Key
The primary key is a specific candidate key chosen to uniquely identify each tuple in
a table. It ensures that each row is unique and not null.
Characteristics:
 Uniquely identifies each record in the table.
 Cannot have null values.
 Each table can have only one primary key.
Example: In the Students table, StudentID might be selected as the primary key.

Relation between Primary Key, Candidate Key, and Super Key

3. Alternate Key:
An alternate key is any candidate key that is not chosen as the primary key. It is still
a unique identifier for tuples but is not used as the main key for the table.
Characteristics:
 Each alternate key could potentially serve as a primary key.
 Used for ensuring uniqueness in case the primary key is not suitable.
Example: If StudentID is chosen as the primary key, then Email (if unique) becomes an
alternate key.
4. Foreign Key
A foreign key is an attribute or a set of attributes in one table that refers to the
primary key of another table. It establishes and enforces a link between the data in
the two tables.
Characteristics:
 Ensures referential integrity by enforcing that the value in the foreign key column
matches a value in the primary key column of the related table.
 Can contain duplicate values and nulls if allowed.
Example: In an department_info table, dept_id might be a foreign key that refers to
the dept_id primary key in the department_info Students table.

Structured Query Language


 Introduction to SQL
Structured Query Language (SQL) is the standard language used to interact
with relational databases.
 Mainly used to manage data. Whether you want to create, delete,
update or read data, SQL provides commands to perform these
operations.
 SQL COMMANDS/Statements

 Data Definition Language (DDL)


Data Definition Language (DDL) is a subset of SQL used for defining and managing
database structures. It includes commands that define, alter, and drop database
objects such as tables, indexes, and schemas.
Common DDL Commands:
 CREATE ,ALTER,DROP,TRUNCATE

 Data Manipulation Language (DML)


Data Manipulation Language (DML) is a subset of SQL used for manipulating and
querying the data stored in the database. It includes commands to insert, update,
delete, and retrieve data.
Common DML Commands:
 INSERT,UPDATE,DELETE

 DQL – Data Query Language :


DQL is used to fetch data from the database. The main command is SELECT, which
retrieves records based on the query.
Common DQL commands:
 SELECT, FROM , WHERE, GROUPBY ,HAVING , DISTINCT, ORDERBY

 DCL - Data Control Language


DCL (Data Control Language) includes commands such as GRANT and REVOKE which
mainly deal with the rights, permissions and other controls of the database system.
Common DML Commands:
GRANT ,REVOKE

 Data Types in SQL :


SQL data types define the kind of data that can be stored in a database
column. Constraints are rules applied to columns to ensure data integrity and
enforce specific data conditions.

1. CHAR(n)
 Definition: A fixed-length character string. If the data stored is shorter than n
characters, it is padded with spaces.
 Usage: Useful for storing data with a consistent length, such as country codes or
status codes.
 Example: CHAR (10) will store exactly 10 characters; "ABC" becomes "ABC " (with
padding).

2. VARCHAR(n)
 Definition: A variable-length character string. Only the actual number of characters
is stored, up to n characters.
 Usage: Ideal for storing text data of varying lengths, such as names or addresses.
 Example: VARCHAR (50) will store up to 50 characters. "John" will use only 4
characters of space.

3. INT (integer)
 Definition: A whole number. It can store both positive and negative integers.
 Usage: Commonly used for numerical data like IDs or counts.
 Example: INT can store values like 1, -42, or 1000.

4. FLOAT (FLOATING POINT NUMBER)


 Definition: A floating-point number, which can store decimal values. It’s used for
precise calculations and measurements.
 Usage: Suitable for storing values with decimals, such as prices or scientific
measurements.
 Example: FLOAT can store values like 3.14 or -0.001.

5. DATE
 Definition: A date value in the format YYYY-MM-DD. It stores calendar dates.
 Usage: Used for storing dates of events, birthdays, or deadlines.
 Example: DATE can store values like 2024-08-01.

Constraints in sql:
Constraints are the rules that we can apply on the type of data in a table. That is, we
can specify the limit on the type of data that can be stored in a particular column in
a table using constraints.

We can specify constraints at the time of creating the table using CREATE TABLE
statement. We can also specify the constraints after creating a table using ALTER
TABLE statement.
Syntax:
Below is the syntax to create constraints using CREATE TABLE statement at the time
of creating the table.
CREATE TABLE sample_table
(
column1 data_type(size) constraint name,
column2 data_type(size) constraint name,
column3 data_type(size) constraint name,
....
);

sample_table: Name of the table to be created.


data_type: Type of data that can be stored in the field.
Constraint name: Name of the constraint. For example- NOT NULL, UNIQUE,
PRIMARY KEY etc.

1. NOT NULL
 Definition: Ensures that a column cannot have null (empty) values. Every record
must have a value for this column.
Usage: Used when a field is required for every record, such as a user’s email address.
Example: Email VARCHAR(100) NOT NULL means every student must have an email
address.
CREATE TABLE Student
(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
ADDRESS varchar(20)
);

2. UNIQUE
 Definition: Ensures that all values in a column are distinct. No two records can have
the same value for this column.
Usage: Used to enforce uniqueness, like in a column for social security numbers or
usernames.
Example: Username VARCHAR(50) UNIQUE ensures no two users can have the same
username.
CREATE TABLE Student
(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20)
);

[Link] KEY
 Definition: A combination of NOT NULL and UNIQUE. It uniquely identifies each row
in a table and cannot be null.
Usage: Used to uniquely identify records, such as in an ID column or a student
number.
Example: StudentID INT PRIMARY KEY means each student will have a unique
StudentID that cannot be duplicated or null.

CREATE TABLE Student


(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20),
PRIMARY KEY(ID)
);

4. FOREIGN KEY Constraint


The FOREIGN KEY (REFERENCES in some databases) constraint in a column is used to
reference a record that exists in another table.
For example: CREATE TABLE Orders (
order_id INT PRIMARY KEY,
customer_id int REFERENCES Customers(id)
);
5. CHECK Constraint:
The CHECK constraint checks the condition before allowing values in a table.
For example: CREATE TABLE Orders (
Order_id INT PRIMARY KEY,
amount int CHECK (amount >= 100)
);

6. Default : The DEFAULT constraint is used to set the default value if we try to
store NULL in a column.
For example :
CREATE TABLE College (
college_id INT PRIMARY KEY,
college_code VARCHAR(20),
college_country VARCHAR(20) DEFAULT 'US'
);

SQL (Structure Query Language )

SQL Commands for DATA DEFINITION LANGUAGE:


Managing databases involves creating, selecting, and deleting databases. Here are the
essential SQL commands for these tasks:

1. CREATE DATABASE
Definition: Creates a new database. This command sets up a new database
environment where tables, views, and other objects can be created.
Syntax:
>>> CREATE DATABASE database_name;

Example: To create a database named dps. –

>>> CREATE DATABASE dps;


Output:

2. USE DATABASE
Definition: Select the database to use for subsequent SQL commands. Once a
database is selected, any operations (such as creating tables or querying data) will
be performed on that database.
Syntax:
>>>USE database name;

Example: To switch to the DPS database.

>>>USE DPS;

3. SHOW DATABASES
Definition: Lists all databases available in the database management system (DBMS).
This command helps you view all existing databases and check their names.
Syntax:
>>>SHOW DATABASES;

Example: Running this command will display a list of all databases. including
SchoolDB, if it exists.

Database successfully created

4. DROP DATABASE
 Definition: Deletes an existing database and all of its contents, including tables,
data, and other objects. This command is irreversible, so be cautious when using it.
Syntax:
>>>DROP DATABASE database_name;

Example: To delete the dps database.


>>>DROP DATABASE dps;

SQL Commands for Table Management

Managing tables involves creating, modifying, and deleting tables, as well as inserting
and deleting data. Here’s a guide to essential SQL commands for these tasks:
1. SHOW TABLES
Definition: Lists all the tables in the currently selected database. Useful for viewing
existing tables and verifying their names.
Syntax:
>>> SHOW TABLES;
Example: Running this command will display a list of tables in the selected database.

2. CREATE TABLE
Definition: Creates a new table in the database with specified columns and their data
types.
Syntax:
CREATE TABLE table_name ( column1 datatype constraints, column2 datatype
constraints, ...);

Example: To create a table named Students with columns StudentID, Name, and
DateOfBirth:
Syntax :
CREATE TABLE Students ( StudentID INT PRIMARY KEY, Name VARCHAR(50) NOT
NULL, DateOfBirth DATE);

3. DESCRIBE TABLE
Definition: Displays the structure of a table, including column names, data types, and
constraints.
Syntax:
>>> DESCRIBE table_name;
Example: To view the structure of the Students table.
>>>DESCRIBE Students;
 DROP TABLE: The DROP TABLE statement is used to drop an existing table in a
database.
Syntax: DROP TABLE table_name;
Drop table students;

SQL ALTER TABLE

1. ALTER TABLE
Definition: Modifies the structure of an existing table, such as adding or removing
columns and constraints.
Add an Attribute:
Syntax:
>>> ALTER TABLE table_name ADD column_name datatype constraints;

Example: To add an Email column to the Students table:


>>>ALTER TABLE Students ADD Email VARCHAR (100);

[Link] an Attribute:
Syntax:
>>>ALTER TABLE table_name DROP COLUMN column_name;
Example: To remove the Email column from the Students table:

>>>ALTER TABLE Students DROP COLUMN Email;

3. Add a Primary Key:


Syntax:
>>> ALTER TABLE table_name ADD PRIMARY KEY (column_name);
Example: To add a primary key constraint to the StudentID column:

>>>ALTER TABLE Students ADD PRIMARY KEY (StudentID);


[Link] a Primary Key:
Syntax:
>>> ALTER TABLE table_name DROP PRIMARY KEY;
Example: To remove the primary key constraint:
>>> ALTER TABLE Students DROP PRIMARY KEY;

5. DROP TABLE
 Definition: Deletes an existing table and all of its data. This action is irreversible.
Syntax: >>>DROP TABLE table_name;
Example: To delete the Students table:

>>>DROP TABLE Students;

DATA MANIPULATION COMMANDS :

6. INSERT STATEMENT : Definition: Adds new rows of data into a table.


Syntax:
>>>INSERT INTO table name (column1, column2, ...)VALUES (value1, value2, ...);

>>>INSERT INTO Students (Student, Name, DateOfBirth)VALUES (1, 'Alice Smith', '2005-
05-15');

Insert Multiple values in a table :


>>> INSERT INTO Student (ROLL_NO, NAME, ADDRESS, PHONE, AGE)
VALUES (1, 'Liam', 'New York', 'xxxxxxxxxx', 18),
(2, 'Sophia', 'Berlin', 'xxxxxxxxxx', 18),
(3, 'Akira', 'Tokyo', 'xxxxxxxxxx', 20),
(4, 'Carlos', 'Tokyo', 'xxxxxxxxxx', 18);
Inserting data in a specific column:–

Syntax : INSERT INTO table name (column1, column2, column3, ...)


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

>>>INSERT INTO Student (ROLL_NO, NAME, AGE) VALUES (6, 'Hiroshi', 19);

7. UPDATE STATEMENT: The UPDATE statement in SQL is used to modify existing


records in a table without deleting them. It allows updating one or multiple columns,
with or without conditions, to keep data accurate and consistent.
 Change specific column values in selected rows
 Apply targeted updates using WHERE
 Update single or multiple columns at once
Syntax:
>>>UPDATE table_name
SET column1 = value1, column2 = value2,...
WHERE condition;

 Example 1: Update Single Column Using UPDATE Statement.


We have a STUDENT table and we want to update the studentname where the Age
is 22.

>>>UPDATE STUDENT
SET Studentname = 'ram'
WHERE Age = 22;

Explanation: Only the rows where Age is 22 will be updated, and the
studentname will be set TO ‘ram’.

 Example 2: Updating Multiple Columns using UPDATE Statement.


We need to update both the STUDENTNAME and CITY for a specific rollno.

>>>UPDATE student
SET studentname = 'Satyam',
city = ‘sitapur'
WHERE rollno = 14;

8. SQL DELETE Statement: The SQL DELETE statement is used to remove specific rows
from a table while keeping the table structure intact. It is different from DROP, which
deletes the entire table.
 Removes rows based on conditions.
 Retains table schema, constraints, and indexes.
 Can delete a single row or all rows.
Syntax:
>>> DELETE FROM table_name
WHERE some_condition;
 Example 1: Deleting Single Record.
>>> DELETE FROM student
WHERE NAME = 'Ritu';

 Example 2: Deleting Multiple Records.


>>>DELETE FROM student
WHERE STREAM =’arts’;

 SQL SELECT Query


SQL SELECT is used to retrieve data from one or more tables, either all records
or specific results based on conditions. It returns output in a tabular format of
rows and columns.
 Extracts data from tables.
 Targets specific or all columns (*).

Syntax
>>> SELECT column1, column2.... FROM table_name;

 Example 1: Select Specific Columns.


>>> SELECT firstname, lastname FROM student;

 Example 2: Select All Columns.


In this example, we will fetch all the fields from table Customer:
>>>SELECT * FROM Customer;

 Example 3: SELECT Statement with WHERE Clause.


>>>SELECT studentname
FROM student
where Age = '21';

 SQL ORDER BY : The ORDER BY clause in SQL is used to sort query results
based on one or more columns in either ascending (ASC) or descending
(DESC) order.
 By default, it sorts in ascending order (lowest to highest).
 To sort in descending order, use the DESC keyword.
Example 1: Sort by a Single Column.

Syntax:
SELECT * FROM table_name ORDER BY column name ASC | DESC;

>>> SELECT * FROM students ORDER BY ROLL_NO DESC;

Example 2 : Sort by Multiple Columns.

SELECT * FROM students ORDER BY age DESC , name ASC;

 SQL Distinct Clause: The SELECT DISTINCT statement is used to return only
distinct (different) values. (Removes duplicate rows)

Syntax:
SELECT DISTINCT column1, column2
FROM table_name

 Example 1: Fetch Unique Names from the NAME Field.


Query:
SELECT DISTINCT NAME FROM students;

 Example 2: Fetching Unique Combinations of Multiple Columns.

SELECT DISTINCT NAME, AGE FROM students;

 Example 3: Using DISTINCT with the ORDER BY Clause.

SELECT DISTINCT AGE FROM students ORDER BY AGE;

 Example 4: Using DISTINCT with Aggregate Functions (e.g., COUNT()).

SELECT COUNT(DISTINCT ROLL_NO) FROM Students ;

 AS Clause in SQL
 The AS command is used to rename a column or table with an alias.

Syntax :
 Alias for Columns
>>>SELECT column_name AS alias_name
FROM table_name;

 Alias for Tables


>>>SELECT column_name
FROM table_name AS alias_name;
(alias_name: The temporary name assigned to the table.)

WHERE Clause : The WHERE clause is used to filter records. It is used to extract
only those records that fulfill a specified condition.

Syntax:
>>> SELECT column1, column2
FROM table_name
WHERE column_name operator value;
Example 1: Where Clause with Logical Operators
To fetch records of student with age equal to 24.
Query:
>>> SELECT * FROM student WHERE Age=24;

 SQL Aggregate functions: An aggregate function is a function that performs a


calculation on a set of values, and returns a single value.
 Aggregate functions are often used with the GROUP BY clause of
the SELECT statement. The GROUP BY clause splits the result-set into groups of
values and the aggregate function can be used to return a single value for each
group.
The most commonly used SQL aggregate functions are:
 MIN() - returns the smallest value within the selected column
 MAX() - returns the largest value within the selected column
 COUNT() - returns the number of rows in a set
 SUM() - returns the total sum of a numerical column
 AVG() - returns the average value of a numerical column
Aggregate functions ignore null values (except for COUNT(*)).

 Commonly Used SQL Aggregate Functions :

Count() : The COUNT() function returns the number of rows based on a given
condition.

 COUNT(*) – Counts all rows, including those with NULLs.


 COUNT(column_name) – Counts only non-NULL values in the specified
column.
 COUNT(DISTINCT column_name) – Counts unique non-NULL values in the
column.

 Total number of rows in Employee table


SELECT COUNT (*) FROM Employee;

 Count of non-NULL salaries


SELECT COUNT (Salary) FROM Employee;

 Count of unique non-NULL salaries


SELECT COUNT (DISTINCT Salary) FROM Employee;

 SUM() Function Summary:


The SUM() function returns the total of all values in a numeric column.
 SUM(column_name) – Adds all non-NULL values.
 SUM(DISTINCT column_name) – Adds only unique non-NULL values.
-- Total of all salaries
>>>SELECT SUM(Salary) AS TotalSalary FROM Employee;

 AVG() Function Summary:


The AVG() function calculates the average (mean) of values in a numeric column.
 AVG(column_name) – Calculates the average of all non-NULL values.
 AVG(DISTINCT column_name) – Calculates the average of unique non-NULL
values.

 Average salary:
SELECT AVG(Salary) AS AverageSalary FROM Employee;

 Average of distinct salaries:


SELECT AVG(DISTINCT Salary) AS DistinctAvgSalary FROM Employee;

 MIN() and MAX() Function Summary:


 MIN(column_name) – Returns the smallest non-NULL value in a column.
 MAX(column_name) – Returns the largest non-NULL value in a column.

 Lowest price in the Products table


>>>SELECT MIN (Price) FROM Products;
 Highest price in the Products table
>>>SELECT MAX (Price) FROM Products;

Operators in SQL :
 Logical Operators

 IN Operator :
 Purpose: Checks if a value matches any value in a specified list.
 Use case: Simplifies multiple OR conditions
.Example : Get employees from the HR, IT, or Finance departments
>>> SELECT *FROM Employee WHERE Department IN ('HR', 'IT', 'Finance');

 BETWEEN Operator :
 Purpose: Filters records within a specified range, including the boundary values.
 Note: Works with numbers, dates, and text (based on sorting).

Example: -- Get employees with salary between 30,000 and 60,000


SELECT *FROM Employee
WHERE Salary BETWEEN 30000 AND 60000;

SQL NULL VALUES AND COMMON COMMANDS


1. Meaning of NULL :
 Definition: NULL represents the absence of a value or unknown data in a database.
It is not the same as an empty string or zero. It signifies that the value is missing or
not applicable.
>>>SELECT column_name
FROM table_name
WHERE column_name IS NULL;

2. NOT NULL:
 NOT NULL is a constraint applied to a column during table creation or
modification. It ensures that the column cannot contain NULL values.
Syntax:
CREATE TABLE Employees (
EmployeeID INT NOT NULL,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50),
Email VARCHAR(100) UNIQUE
);

SELECT column_name
FROM table_name
WHERE column_name IS NOT NULL;

4. LIKE Operator

 Purpose: Used for pattern matching in WHERE clauses.


 Commonly used with wildcards:
o ‘%’ → Matches any number of characters
o ‘_‘ → Matches a single character

 GROUP BY statement groups rows that have the same values in one or more
columns. It is commonly used to create summaries, such as total sales by
region or number of users by age group.
Its main features include:
 Used with the SELECT statement.
 Groups rows after filtering with WHERE.
 Can be combined with aggregate functions like SUM (), COUNT (), AVG (), etc.
 Filter grouped results using the HAVING clause.
 Comes after WHERE but before HAVING and ORDER BY.

Syntax : >>>SELECTS column1,


aggregate function (column2)
FROM table_name
GROUP BY column1;

>>>SELECT Product, SUM(Amount) AS TotalSales


FROM Sales
GROUP BY Product;

 HAVING Clause in GROUP BY Clause

 Purpose: Filters groups created by GROUP BY based on a condition.


 Unlike WHERE, which filters rows before grouping, HAVING filters after
the aggregation.
 Usually used with aggregate functions (COUNT(), SUM(), AVG(), etc.).

Syntax :

>>> SELECT column1, aggregate_function(column2)


FROM table_name
GROUP BY column1
HAVING aggregate_function(column2) condition;

Example :
SELECT Product, SUM(Amount) AS TotalSales
FROM Sales
GROUP BY Product
HAVING SUM(Amount) > 1000;
Joins In SQL

SQL joins are fundamental tools for combining data from multiple tables in
relational databases.

 For example, consider two tables where one table (say Student) has student
information with id as a key and other table (say Marks) has information
about marks of every student id. Now to display the marks of every student
with name, we need to join the two tables.

 Natural Join :
 Automatically joins tables using columns with the same names and compatible
data types in both tables.
 Removes duplicate columns from the result.

Syntax: SELECT *
FROM Table A
NATURAL JOIN Table B;
Example:
If both Employees and Departments have a column DeptID, then:
>>> SELECT *
FROM Employees
NATURAL JOIN Departments;

 Cartesian Join (Cross Join):


 Returns the Cartesian product of two tables — every row from the first
table combined with every row from the second table.
 No condition is used.

Syntax: SELECT *
FROM Table A
CROSS JOIN Table B;
Example:
SELECT *
FROM Products
CROSS JOIN Categories;

If Products has 4 rows and Categories has 3 rows, result will have 4 × 3 = 12
rows.

 Equi Join:
 A join that uses a comparison operator (=) to match rows based on
column values.
Syntax :
SELECT A.column1, B.column2
FROM Table A A
JOIN Table B B
ON A.common_column = B.common_column;
Example :
>>> SELECT [Link], [Link]
FROM Employees
JOIN Departments
ON [Link] = [Link];

You might also like