0% found this document useful (0 votes)
20 views

12 Computer Science Unit 3

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

12 Computer Science Unit 3

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Unit III Notes: Database Management

 Database concepts: introduction to database concepts and its need


 Relational data model: relation, attribute, tuple, domain, degree, cardinality, keys
(candidate key, primary key, alternate key, foreign key)
 Structured Query Language: introduction, Data Definition Language and Data
Manipulation Language, data type (char(n), varchar(n), int, float, date), constraints (not
null, unique, primary key), create database, use database, show databases, drop
database, show tables, create table, describe table, alter table (add and remove an
attribute, add and remove primary key), drop table, insert, delete, select, operators
(mathematical, relational and logical), aliasing, distinct clause, where clause, in, between,
order by, meaning of null, is null, is not null, like, update command, delete command,
aggregate functions (max, min, avg, sum, count), group by, having clause, joins: cartesian
product on two tables, equi-join and natural join
 Interface of python with an SQL database: connecting SQL with Python, performing
insert, update, delete queries using cursor, display data by using connect( ), cursor( ),
execute( ), commit( ), fetchone( ), fetchall( ), rowcount, creating database connectivity
applications, use of %s format specifier or format( ) to perform queries.

Table of Content
 Database Concepts
 Relational Data Model
 Keys (candidate key, primary key, alternate key, foreign key)
 Structured Query Language
 Interface of Python with an SQL Database
 CBSE Class 12th Computer Science Unit III Notes: Marks Distribution

Database Concepts
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).

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: The structure or blueprint of a database, defining how data is organized and
how relationships between data are handled. It includes definitions of tables, fields, and
their relationships.
 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.

Normalization:
 Definition: The process of organizing data in a database to reduce redundancy and
improve data integrity. It involves dividing large tables into smaller, related tables.
 Example: Separating customer information from order details to avoid duplication of
customer data.

Indexing:
 Definition: A technique used to speed up data retrieval operations by creating indexes on
database columns.
 Example: Creating an index on the "email" column in a customer table to quickly find
records by email address.

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 Data Model


Relational Data Model
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.
Relational Data Model
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 (candidate key, primary key, alternate key, foreign key)


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
Definition: 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
Definition: 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
Definition: 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
Definition: 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 Enrollments table, StudentID might be a foreign key that refers to the
StudentID primary key in the Students table.

Structured Query Language


Introduction to SQL
Structured Query Language (SQL) is a standardized programming language used for
managing and manipulating relational databases. SQL allows users to create, modify, and
query databases effectively. It provides a way to interact with data stored in relational
database management systems (RDBMS).
 Purpose: SQL is designed to handle tasks such as querying data, updating records, and
managing database structures. It provides a straightforward syntax for interacting with
relational databases.
 Components: SQL is divided into several categories based on the type of operations it
supports.

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: Used to create new database objects, such as tables, indexes, and views
o Example: CREATE TABLE Students (StudentID INT PRIMARY KEY, Name
VARCHAR(50), DateOfBirth DATE)

 ALTER: Used to modify existing database objects, such as adding or deleting columns in a
table.
o Example: ALTER TABLE Students ADD Email VARCHAR(100)

 DROP: Used to delete database objects, such as tables or indexes.


o Example: DROP TABLE Students

 TRUNCATE: Used to remove all records from a table without deleting the table structure.
o Example: TRUNCATE TABLE Students;

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:
 SELECT: Retrieves data from one or more tables. It can include conditions, sorting, and
grouping
o Example: SELECT Name, DateOfBirth FROM Students WHERE StudentID = 1

 INSERT: Adds new records to a table.


o Example: INSERT INTO Students (StudentID, Name, DateOfBirth) VALUES (1,
'Alice Smith', '2005-05-15')

 UPDATE: Modifies existing records in a table.


o Example: UPDATE Students SET Email = '[email protected]' WHERE
StudentID = 1

 DELETE: Removes records from a table based on specified conditions.


o Example: DELETE FROM Students WHERE StudentID = 1

Summary
 SQL: A language used to interact with relational databases, allowing for the creation,
modification, and querying of database structures and data.
 Data Definition Language (DDL): Includes commands for defining and managing
database objects (CREATE, ALTER, DROP, TRUNCATE).
 Data Manipulation Language (DML): Includes commands for manipulating and querying
data (SELECT, INSERT, UPDATE, DELETE).

Data Type (char(n), varchar(n), int, float, date), constraints (not null, unique, primary
key)

SQL Data Types and Constraints


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.

Data Types

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).

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.

INT
 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.

FLOAT
 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.
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
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.

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)
);

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)
);

PRIMARY 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)
);

Summary

Data Types:
 CHAR(n): Fixed-length text.
 VARCHAR(n): Variable-length text.
 INT: Whole numbers.
 FLOAT: Decimal numbers.
 DATE: Calendar dates.

Constraints:
 NOT NULL: Column must have a value.
 UNIQUE: Values in the column must be distinct.
 PRIMARY KEY: Unique identifier for each row, combining NOT NULL and UNIQUE.

Create Database, Use Database, Show Databases, Drop Database

SQL Commands for Database Management


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:
sql
CREATE DATABASE database_name;
Example: To create a database named SchoolDB, you would use:
sql
CREATE DATABASE GeeksForGeeks;
Output:
Creating a new database

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:
sql
USE database_name;
Example: To switch to the SchoolDB database, you would use:
sql
USE SchoolDB;

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:
sql
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:
sql
DROP DATABASE database_name;
Example: To delete the SchoolDB database, you would use:
sql
DROP DATABASE SchoolDB;

Show Tables, Create Table, Describe Table, Alter Table (add and remove an attribute,
add and remove primary key), Drop Table, Insert, Delete

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:
sql
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:
sql
CREATE TABLE table_name ( column1 datatype constraints, column2
datatype constraints, ...);

Example: To create a table named Students with columns StudentID, Name, and
DateOfBirth:
sql
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:
sql
DESCRIBE table_name;
Example: To view the structure of the Students table:
sql
DESCRIBE Students;

4. ALTER TABLE
 Definition: Modifies the structure of an existing table, such as adding or removing columns
and constraints.

 Add an Attribute:
Syntax:
sql
ALTER TABLE table_name
ADD column_name datatype constraints;
Example: To add an Email column to the Students table:
sq
ALTER TABLE Students
ADD Email VARCHAR(100);

 Remove an Attribute:
Syntax:
sql
ALTER TABLE table_name
DROP COLUMN column_name;
Example: To remove the Email column from the Students table:
sql
ALTER TABLE Students
DROP COLUMN Email;

 Add a Primary Key:


Syntax:
sql
ALTER TABLE table_name
ADD PRIMARY KEY (column_name);
Example: To add a primary key constraint to the StudentID column:
sql
ALTER TABLE Students
ADD PRIMARY KEY (StudentID);
 Remove a Primary Key:
Syntax:
sql
ALTER TABLE table_name
DROP PRIMARY KEY;
Example: To remove the primary key constraint:
sql
ALTER TABLE Students
DROP PRIMARY KEY;

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

6. INSERT
 Definition: Adds new rows of data into a table.
Syntax:
sql
INSERT INTO table_name (column1, column2, ...)VALUES (value1, value2,
...);
Example: To insert a new student into the Students table:
sql
INSERT INTO Students (StudentID, Name, DateOfBirth)VALUES (1, 'Alice
Smith', '2005-05-15');

7. DELETE
 Definition: Removes existing rows from a table based on a specified condition.
Syntax:
sql
DELETE FROM table_name
WHERE condition;Example: To delete a student with StudentID 1 from
the Students table:
sql
DELETE FROM Students
WHERE StudentID = 1;

Select, Operators (mathematical, relational, Check and logical)

SQL SELECT and Operators


1. SELECT Statement
The SELECT statement is used to query and retrieve data from a database. It is one of the
most commonly used SQL commands.
Basic Syntax:
sql
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example: To retrieve the Name and DateOfBirth of students from the Students table:
sql
SELECT Name, DateOfBirth
FROM Students;
 Select All Columns: Use * to select all columns.
In this example, we will retrieve all records from the “employee” table where the “emp_city”
column does not start with the letter ‘A’.

Query:
sql
SELECT * FROM employee WHERE emp_city NOT LIKE 'A%';
Output:

SELECT Statement

 With Conditions: Use the WHERE clause to filter records.


In this example, we will retrieve all records from the “MATHS” table where the value in the
“MARKS” column is equal to 50.

Query:
sql
SELECT * FROM MATHS WHERE MARKS=50;
Output:

SELECT Statement With Conditions

2. Operators in SQL
SQL operators are used to perform operations on data in queries. They can be categorized
into mathematical, relational, and logical operators.

Mathematical Operators
Definition: Used to perform arithmetic operations.

Common Operators:
 Addition (+): Adds two values.
o Example: SELECT Price + Tax AS Total FROM Products

 Subtraction (-): Subtracts one value from another.


o Example: SELECT Price - Discount AS FinalPrice FROM Products

 Multiplication (*): Multiplies two values.


o Example: SELECT Quantity * Price AS TotalCost FROM Orders
 Division (/): Divides one value by another.
o Example: SELECT TotalAmount / NumberOfItems AS AveragePrice FROM
Orders

Relational Operators
Definition: Used to compare values and return a boolean result.

Common Operators:
 Equal To (=): Checks if two values are equal.
o Example: SELECT * FROM Students WHERE StudentID = 1

 Not Equal To (<> or !=): Checks if two values are not equal.
o Example: SELECT * FROM Students WHERE Status <> 'Inactive'

 Greater Than (>): Checks if a value is greater than another.


o Example: SELECT * FROM Products WHERE Price > 100

 Less Than (<): Check if a value is less than another.


o Example: SELECT * FROM Products WHERE Price < 50

 Greater Than or Equal To (>=): Checks if a value is greater than or equal to another.
o Example: SELECT * FROM Products WHERE Price >= 100

 Less Than or Equal To (<=): Check if a value is less than or equal to another.
o Example: SELECT * FROM Products WHERE Price <= 50

Logical Operators
Definition: Used to combine multiple conditions in queries.

Common Operators:
 AND: Returns true if both conditions are true.
o Example: SELECT * FROM Students WHERE Grade = 'A' AND Age > 18

 OR: Returns true if at least one of the conditions is true.


o Example: SELECT * FROM Students WHERE Grade = 'A' OR Grade = 'B'

 NOT: Returns true if the condition is false.


o Example: SELECT * FROM Students WHERE NOT Grade = 'F'

 BETWEEN: Checks if a value is within a range.


o Example: SELECT * FROM Products WHERE Price BETWEEN 10 AND 50

 LIKE: Searches for a specified pattern.


o Example: SELECT * FROM Customers WHERE Name LIKE 'J%'; (Finds names
starting with 'J')

 IN: Checks if a value matches any value in a list.


o Example: SELECT * FROM Students WHERE Grade IN ('A', 'B')

SQL Logical Operators Example


In this example, retrieve all records from the “employee” table where the “emp_city” column is
equal to ‘Allahabad’ and the “emp_country” column is equal to ‘India’.
SELECT * FROM employee
WHERE emp_city = 'Allahabad'
AND emp_country = 'India';

Output:
Use of Logical Operator

Aliasing, Distinct Clause, where Clause, in, Between, Order by

SQL Query Enhancements


1. Aliasing
 Definition: Aliasing is used to create temporary names for tables or columns in a query to
make them more readable or to simplify complex queries.
Syntax:
sql
SELECT column_name AS alias_name
FROM table_name AS alias_name;
Example: To create a shorter name for the Students table and a column
alias for DateOfBirth:
sql
SELECT Name AS StudentName, DateOfBirth AS DOB
FROM Students AS S;

2. DISTINCT Clause
Definition: The DISTINCT clause removes duplicate rows from the result set, showing only
unique values.
Syntax:
sql
SELECT DISTINCT column_name
FROM table_name;
Example: To find unique Grade values in the Students table:
sql
SELECT DISTINCT Grade
FROM Students;

3. WHERE Clause
Definition: The WHERE clause filters records to include only those that meet a specified
condition.
Syntax:
sql
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example: To select students older than 18:
sql
SELECT Name, Age
FROM Students
WHERE Age > 18;

4. IN Operator
Definition: The IN operator checks if a value matches any value in a specified list.
Syntax:
sql
SELECT column_name
FROM table_name
WHERE column_name IN (value1, value2, ...);
Example: To select students with grades 'A' or 'B':
sql
SELECT Name
FROM Students
WHERE Grade IN ('A', 'B');

5. BETWEEN Operator
Definition: The BETWEEN operator filters records within a specified range (inclusive).
Syntax:
sql
SELECT column_name
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Example: To find products with prices between 10 and 50:
sql
SELECT ProductName
FROM Products
WHERE Price BETWEEN 10 AND 50;

6. ORDER BY Clause
Definition: The ORDER BY clause sorts the result set by one or more columns. You can sort
in ascending (default) or descending order.
Syntax:
sql
SELECT column1, column2, ...
FROM table_name
ORDER BY column_name [ASC|DESC];
Example: To select students and sort them by age in ascending order:
sql
SELECT Name, Age
FROM Students
ORDER BY Age ASC;

Example: To sort products by price in descending order:


sql
SELECT ProductName, Price
FROM Products
ORDER BY Price DESC;

Meaning of null, is null, is not null, like, update command, delete command
Principles of NULL values
 Setting a NULL value is appropriate when the actual value is unknown, or when a value is
not meaningful.
 A NULL value is not equivalent to a value of ZERO if the data type is a number and is not
equivalent to spaces if the data type is a character.
 A NULL value can be inserted into columns of any data type.
 A NULL value will evaluate NULL in any expression.
 Suppose if any column has a NULL value, then UNIQUE, FOREIGN Key, and CHECK
constraints will ignore by SQL.
Use of AND Logical Expression

Use of OR Logical Expression


In general, each NULL value is considered to be different from every other NULL in the
database. When a NULL is involved in a comparison operation, the result is considered to be
UNKNOWN. Hence, SQL uses a three-valued logic with values True, False, and Unknown. It
is, therefore, necessary to define the results of three-valued logical expressions when the
logical connectives AND, OR, and NOT are used.

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.
 Example: In a Students table, a Graduation Date column might be NULL if the student
hasn't graduated yet.

2. IS NULL
 Definition: The IS NULL condition is used to check if a column contains a NULL value.
Syntax:
sql
SELECT column_name
FROM table_name
WHERE column_name IS NULL;
Example: To find students without a specified GraduationDate:
sql
SELECT NameFROM Students
WHERE GraduationDate IS NULL;

3. IS NOT NULL
Definition: The IS NOT NULL condition is used to check if a column does not contain a NULL
value.
Syntax:
sql
SELECT column_name
FROM table_name
WHERE column_name IS NOT NULL;
Example: To find students with a specified GraduationDate:
sql

SELECT NameFROM Students


WHERE GraduationDate IS NOT NULL;

4. LIKE Operator
Definition: The LIKE operator is used for pattern matching in a WHERE clause. It allows you
to search for a specified pattern in a column.
Syntax:
sql
SELECT column_name
FROM table_name
WHERE column_name LIKE pattern;
Pattern Matching:
 %: Represents zero or more characters.
 _: Represents a single character.
Examples:
To find names starting with 'J':
sql
SELECT NameFROM Students
WHERE Name LIKE 'J%';
To find names with exactly 4 characters:
sql
SELECT NameFROM Students
WHERE Name LIKE '____';

5. UPDATE Command
Definition: The UPDATE command is used to modify existing records in a table.
Syntax:
sql
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example: To update the Grade of a student with StudentID 1:
sql
UPDATE StudentsSET Grade = 'A'
WHERE StudentID = 1;

6. DELETE Command
Definition: The DELETE command removes existing records from a table based on a
specified condition.
Syntax:
sql
DELETE FROM table_name
WHERE condition;
Example: To delete a student with StudentID 1:
sql
DELETE FROM Students
WHERE StudentID = 1;

Aggregate Functions (max, min, avg, sum, count), group by, having clause

SQL Aggregate Functions and Grouping

1. Aggregate Functions
Aggregate functions perform calculations on a set of values and return a single result. They
are often used with the GROUP BY clause to summarize data.
 MAX( ): Returns the maximum value in a set.
Syntax:
sql
SELECT MAX(column_name)
FROM table_name;
Example: To find the highest price in the Products table:
sql
Copy code
SELECT MAX(Price) AS MaxPrice
FROM Products;

 MIN( ): Returns the minimum value in a set.


Syntax:
sql
SELECT MIN(column_name)
FROM table_name;
Example: To find the lowest price in the Products table:
sql
SELECT MIN(Price) AS MinPrice
FROM Products;
 AVG( ): Returns the average value of a set.
Syntax:
sql
SELECT AVG(column_name)
FROM table_name;
Example: To find the average price of products:
sql
SELECT AVG(Price) AS AveragePrice
FROM Products;

 SUM( ): Returns the total sum of a set of values.


Syntax:
sql
SELECT SUM(column_name)
FROM table_name;
Example: To calculate the total sales amount:
sql
SELECT SUM(SalesAmount) AS TotalSales
FROM Sales;

 COUNT( ): Returns the number of rows in a set.


Syntax:
sql
SELECT COUNT(column_name)
FROM table_name;
Example: To count the number of students:
sql
SELECT COUNT(StudentID) AS NumberOfStudents
FROM Students;

2. GROUP BY Clause
 Definition: The GROUP BY clause groups rows that have the same values into summary
rows. It is commonly used with aggregate functions to perform operations on each group.
Syntax:
sql
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name;
Example: To find the average price of products for each category:
sql
SELECT Category, AVG(Price) AS AveragePrice
FROM Products
GROUP BY Category;
3. HAVING Clause
 Definition: The HAVING clause filters groups of rows based on a specified condition,
similar to the WHERE clause but used for groups.
Syntax:
sql
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;
Example: To find categories where the average price is more than 50:
sql
SELECT Category, AVG(Price) AS AveragePrice
FROM Products
GROUP BY Category
HAVING AVG(Price) > 50;

Joins: Cartesian Product on two tables, equi-join and natural join

SQL Joins
Joins are used to combine rows from two or more tables based on a related column. 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.

SQL JOIN Example


Consider the two tables below as follows:
Student:

Stude
nt Table
Student Course:
Student Course Table
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 Student s
JOIN StudentCourse sc ON s.roll_no = sc.roll_no;
Output:

ROLL_NO NAME ADDRESS PHONE AGE COURSE_ID

1 HARSH DELHI XXXXXXXXXX 18 1

2 PRATIK BIHAR XXXXXXXXXX 19 2

3 RIYANKA SILGURI XXXXXXXXXX 20 2

4 DEEP RAMNAGAR XXXXXXXXXX 18 3

5 SAPTARHI KOLKATA XXXXXXXXXX 19 1

Here's a breakdown of different types of joins:

1. Cartesian Product
 Definition: The Cartesian product (also known as a cross join) returns all possible
combinations of rows from two tables. Each row from the first table is paired with every row
from the second table.
Syntax:
sql
SELECT *
FROM table1, table2;
Example: If Students has 3 rows and Courses has 4 rows, the Cartesian
product will produce 12 rows.
sql
SELECT *FROM Students, Courses;
 Note: Cartesian products can generate a large number of rows, so use them with caution.
2. Equi-Join
 Definition: An equi-join (also known as an inner join) combines rows from two tables
based on matching values in specified columns. It retrieves rows where the specified
columns have equal values.
Syntax:
sql
SELECT table1.column1, table2.column2, ...
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;

Example: To find students and their enrolled courses:


sql
SELECT Students.Name, Courses.CourseName
FROM Students
INNER JOIN Enrollments
ON Students.StudentID = Enrollments.StudentID
INNER JOIN Courses
ON Enrollments.CourseID = Courses.CourseID;

3. Natural Join
 Definition: A natural join automatically joins tables based on columns with the same name
and data type in both tables. It selects rows where the values in these common columns
are equal.
Syntax:
sql
SELECT *
FROM table1
NATURAL JOIN table2;
Example: To automatically join Students and Enrollments on the common
column StudentID:
sql
SELECT *FROM Students
NATURAL JOIN Enrollments;
 Note: Be careful with natural joins, as they rely on column names and types being identical
in both tables, which might lead to unintended results if there are columns with the same
names but different meanings.

Summary
 Cartesian Product: Produces all possible combinations of rows from two tables. (SELECT
* FROM table1, table2;)
 Equi-Join: Combines rows based on matching column values (INNER JOIN ... ON ...).
 Natural Join: Joins tables based on columns with the same names and data types
(NATURAL JOIN).

Interface of Python with an SQL Database


Connecting Python with an SQL Database
To interact with an SQL database from Python, you typically use libraries that provide
database connectivity and operations. Here’s a guide on how to connect Python with an SQL
database, specifically focusing on popular libraries like sqlite3, mysql-connector-python, and
psycopg2.
SQL connection with Python

1. Using sqlite3 for SQLite


SQLite is a lightweight, disk-based database that's built into Python's standard library. It's
great for small to medium-sized applications.
Steps:
 Import the library.
 Create a connection to the SQLite database.
 Create a cursor to execute SQL commands.
 Execute SQL commands.
 Commit the transaction (if making changes).
 Close the connection.

Example:
python
import sqlite3
# Connect to the database (or create it if it doesn't exist)
conn = sqlite3.connect('example.db')

# Create a cursor object


cursor = conn.cursor( )

# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS students
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')

# Insert a record
cursor.execute("INSERT INTO students (name, age) VALUES ('Alice', 21)")

# Commit the changes


conn.commit( )

# Query the database


cursor.execute("SELECT * FROM students")
rows = cursor.fetchall( )
for row in rows:
print(row)

# Close the connection


conn.close( )
2. Using mysql-connector-python for MySQL
To connect to a MySQL database, you can use the mysql-connector-python library. You need
to install it via pip if you haven't already.
Installation:
bash
pip install mysql-connector-python

Example:
python
import mysql.connector
# Connect to the MySQL database
conn = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)

# Create a cursor object


cursor = conn.cursor()

# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS students
(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age
INT)''')

# Insert a record
cursor.execute("INSERT INTO students (name, age) VALUES (%s, %s)", ('Bob', 22))

# Commit the changes


conn.commit()

# Query the database


cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
for row in rows:
print(row)

# Close the connection


conn.close()

3. Using psycopg2 for PostgreSQL


To connect to a PostgreSQL database, you can use the psycopg2 library. Install it via pip if
needed.
Installation:
bash
pip install psycopg2

Example:
python
import psycopg2
# Connect to the PostgreSQL database
conn = psycopg2.connect(
dbname="yourdatabase",
user="yourusername",
password="yourpassword",
host="localhost"
)

# Create a cursor object


cursor = conn.cursor()

# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS students
(id SERIAL PRIMARY KEY, name VARCHAR(100), age INTEGER)''')

# Insert a record
cursor.execute("INSERT INTO students (name, age) VALUES (%s, %s)", ('Charlie', 23))

# Commit the changes


conn.commit()

# Query the database


cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
for row in rows:
print(row)

# Close the connection


conn.close()

Performing Insert, Update, Delete Queries Using Cursor

Performing SQL Operations with Python's Cursor


Using a cursor object, you can execute SQL queries to perform operations like inserting,
updating, and deleting data in a database. Here's how to use the cursor for these operations
in Python, with examples for SQLite, MySQL, and PostgreSQL.

1. Inserting Data
 Definition: Insert new records into a table.

Example:
python
import sqlite3
#Connect to the database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()

# Insert a record
cursor.execute("INSERT INTO students (name, age) VALUES (?, ?)", ('John Doe', 25))

# Commit the changes


conn.commit()

# Close the connection


conn.close()

2. Updating Data
 Definition: Modify existing records in a table .

Example:
python
import mysql.connector
# Connect to the database
conn = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
cursor = conn.cursor()

# Update a record
cursor.execute("UPDATE students SET age = %s WHERE name = %s", (26, 'John Doe'))

# Commit the changes


conn.commit( )

# Close the connection


conn.close( )

3. Deleting Data
 Definition: Remove records from a table .

Example:
python
import psycopg2
# Connect to the database
conn = psycopg2.connect(
dbname="yourdatabase",
user="yourusername",
password="yourpassword",
host="localhost"
)
cursor = conn.cursor( )

# Delete a record
cursor.execute("DELETE FROM students WHERE name = %s", ('John Doe',))

# Commit the changes


conn.commit( )

# Close the connection


conn.close( )

Display Data by using connect( ), cursor( ), execute( ), commit( ), fetchone( ), fetchall( ),


rowcount

Displaying Data with Python's SQL Libraries


When working with SQL databases in Python, you typically use methods like connect( ),
cursor( ), execute( ), commit( ), fetchone( ), fetchall( ), and rowcount to interact with and
display data. Here’s how you can use these methods effectively with examples.

1. Connect to the Database


Definition: Establish a connection to the SQL database using connect( ).

Example:
import sqlite3
# Connect to the SQLite database
conn = sqlite3.connect('example.db')

2. Create a Cursor Object


Definition: Create a cursor object using cursor(). The cursor allows you to execute SQL
commands.
Example:
cursor = conn.cursor()

3. Execute SQL Queries


Definition: Use execute() to run SQL commands.
Example:
cursor.execute("SELECT * FROM students")

4. Fetch Data
Definition: Retrieve data from the executed query.
Methods:
 fetchone( ): Fetches the next row of a query result set, returning a single sequence or
None.
Example:
row = cursor.fetchone()
print(row)

 fetchall( ): Fetches all (remaining) rows of a query result, returning a list of tuples.
Example:
rows = cursor.fetchall()for row in rows:
print(row)

5. Get the Number of Affected Rows


 Definition: Use rowcount to get the number of rows affected by the last operation.
Example:
Python
cursor.execute("DELETE FROM students WHERE age < 20")
print(f"Number of rows deleted: {cursor.rowcount}")

6. Commit the Transaction


 Definition: Use commit( ) to save changes made during the transaction.
Example:
python
conn.commit()

7. Close the Connection


 Definition: Use close( ) to close the cursor and database connection.
Example:
python
cursor.close()
conn.close()

Complete Example
Here’s a complete example that demonstrates connecting to a SQLite database, executing a
query, fetching data, and displaying it:

python
import sqlite3
# Connect to the SQLite database
conn = sqlite3.connect('example.db')

# Create a cursor object


cursor = conn.cursor( )

# Execute a query
cursor.execute("SELECT * FROM students")

# Fetch all rows from the result of the query


rows = cursor.fetchall( )

# Display each row


for row in rows:
print(row)

# Fetch the number of rows returned


print(f"Number of rows fetched: {len(rows)}")

# Close the cursor and connection


cursor.close( )
conn.close( )

Creating database connectivity applications


Creating database connectivity applications in Python involves several key steps. Here’s a
comprehensive guide to help you build applications that connect to, query, and manipulate
databases using popular SQL libraries.

1. Setting Up Your Environment


 Install Required Libraries: Depending on the database you're working with; you may
need to install specific Python libraries. Here’s how to install some of the most commonly
used libraries:
 SQLite (comes with Python, no installation needed)
MySQL:
bash
pip install mysql-connector-python
PostgreSQL:
bash
pip install psycopg2

2. Connecting to the Database


Establishing a connection is the first step in database connectivity. Below are examples for
SQLite, MySQL, and PostgreSQL.

SQLite

import sqlite3
# Connect to an SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('mydatabase.db')

MySQL

import mysql.connector
# Connect to a MySQL database
conn = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)

PostgreSQL

import psycopg2
# Connect to a PostgreSQL database
conn = psycopg2.connect(
dbname="yourdatabase",
user="yourusername",
password="yourpassword",
host="localhost"
)

3. Creating a Cursor Object


The cursor object allows you to execute SQL queries and fetch results.
python
cursor = conn.cursor()

4. Executing SQL Queries


You can execute various SQL queries such as creating tables, inserting data, updating
records, and more.

Create Table
python
cursor.execute('''CREATE TABLE IF NOT EXISTS students
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')

Insert Data
python
cursor.execute("INSERT INTO students (name, age) VALUES (?, ?)", ('Alice', 22))

Update Data
python
cursor.execute("UPDATE students SET age = ? WHERE name = ?", (23, 'Alice'))

Delete Data
python
cursor.execute("DELETE FROM students WHERE name = ?", ('Alice',))

5. Fetching Data
Retrieve data from the database using methods like fetchone( ), fetchall( ), or fetchmany(size).

Fetch All Data


cursor.execute("SELECT * FROM students")
rows = cursor.fetchall( )
for row in rows:
print(row)

Fetch One Row


cursor.execute("SELECT * FROM students LIMIT 1")
row = cursor.fetchone( )
print(row)

6. Committing Transactions
For operations that modify the database, use commit( ) to save changes.
python
conn.commit( )

7. Closing the Connection


Always close the cursor and connection to free up resources.
python
cursor.close( )
conn.close( )

Complete Example Application


Here’s a complete example that demonstrates a simple Python application with database
connectivity. This example uses SQLite for simplicity, but the approach is similar for MySQL
and PostgreSQL.

python
import sqlite3
def create_table(conn):
cursor = conn.cursor( )
cursor.execute('''CREATE TABLE IF NOT EXISTS students
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
conn.commit( )

def insert_student(conn, name, age):


cursor = conn.cursor( )
cursor.execute("INSERT INTO students (name, age) VALUES (?, ?)", (name, age))
conn.commit( )

def fetch_students(conn):
cursor = conn.cursor( )
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall( )
for row in rows:
print(row)

def main( ):

# Connect to the SQLite database


conn = sqlite3.connect('mydatabase.db')

# Create table
create_table(conn)

# Insert a new student


insert_student(conn, 'John Doe', 21)

# Fetch and display all students


fetch_students(conn)

# Close the connection


conn.close( )
if __name__ == "__main__":
main( )

Using %s Format Specifier and format( ) to Perform SQL Queries in Python


When executing SQL queries in Python, you often need to pass parameters to queries. There
are different ways to do this, such as using the %s format specifier or the format( ) method. It's
important to use the correct approach to ensure that your queries are both functional and
secure.

1. Using %s Format Specifier


The %s format specifier is commonly used with libraries like sqlite3, mysql-connector-python,
and psycopg2. This method is generally preferred because it helps prevent SQL injection
attacks by automatically escaping special characters.

Example with SQLite


python
import sqlite3

# Connect to the database


conn = sqlite3.connect('example.db')
cursor = conn.cursor( )

# Use %s format specifier for parameterized queries


cursor.execute("INSERT INTO students (name, age) VALUES (?, ?)", ('John Doe', 25))
conn.commit( )

# Fetch and display data


cursor.execute("SELECT * FROM students WHERE name = ?", ('John Doe',))
print(cursor.fetchone( ))

# Close the connection


cursor.close( )
conn.close( )

Example with MySQL


python
import mysql.connector
# Connect to the database
conn = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
cursor = conn.cursor( )

# Use %s format specifier for parameterized queries


cursor.execute("INSERT INTO students (name, age) VALUES (%s, %s)", ('Jane Smith', 30))
conn.commit( )

# Fetch and display data


cursor.execute("SELECT * FROM students WHERE name = %s", ('Jane Smith',))
print(cursor.fetchone( ))

# Close the connection


cursor.close( )
conn.close( )

Example with PostgreSQL


python
import psycopg2
# Connect to the database
conn = psycopg2.connect(
dbname="yourdatabase",
user="yourusername",
password="yourpassword",
host="localhost"
)
cursor = conn.cursor( )

# Use %s format specifier for parameterized queries


cursor.execute("INSERT INTO students (name, age) VALUES (%s, %s)", ('Alice Johnson',
28))
conn.commit( )

# Fetch and display data


cursor.execute("SELECT * FROM students WHERE name = %s", ('Alice Johnson',))
print(cursor.fetchone( ))

# Close the connection


cursor.close( )
conn.close( )

2. Using format( ) Method


While you can use the format( ) method to construct queries, it is generally not recommended
due to security concerns like SQL injection. Direct string interpolation should be avoided in
favour of parameterized queries.

Example (Not Recommended for Security Reasons)


python
import sqlite3
# Connect to the database
conn = sqlite3.connect('example.db')
cursor = conn.cursor( )

# Unsafe way: using format( ) for query construction


name = 'John Doe'
age = 25
cursor.execute("INSERT INTO students (name, age) VALUES ('{}', {})".format(name, age))
conn.commit( )
# Fetch and display data
cursor.execute("SELECT * FROM students WHERE name = '{}'".format(name))
print(cursor.fetchone( ))

# Close the connection


cursor.close( )
conn.close( )

Summary
 %s Format Specifier: Preferred method for parameterized queries. It ensures proper
escaping of parameters, thus helping to prevent SQL injection. Use ? for SQLite and %s
for MySQL and PostgreSQL.
 format( ) Method: While possible, it is not recommended for constructing SQL queries due
to security risks. Directly inserting user inputs into queries can make your application
vulnerable to SQL injection attacks.

CBSE Class 12th Computer Science Unit III Notes: Marks Distribution
Here is the complete marks distribution of computer science class 12th with marks distribution
are as follow:
Topic Marks

Database concepts 3-5 marks

Relational data model 5-7 marks


Topic Marks

Structured Query Language 8-12 marks

Interface of Python with an SQL databases 8-12 marks

You might also like