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

DATABASE CONCEPT and SQL For NCERT CS

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

DATABASE CONCEPT and SQL For NCERT CS

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

DATABASE CONCEPTS

Information is processed, organized, or structured data that is meaningful and useful for
decision-making or understanding. In other words, information is derived from data by
interpreting it in a context that makes it valuable for specific purposes.

Difference Between Data and Information:


• Data: Raw, unprocessed facts or figures. It can be numbers, characters, images, or
any other type of data that has no meaning by itself.
• Information: Data that has been processed and given meaning through context,
relevance, and interpretation.
Example:
1. Data:
o 85, 90, 78
o These are just numbers (marks in exams) without context. They are raw data.
2. Information:
o "John scored 85 in Math, 90 in Science, and 78 in English."
o This is information because the raw data (marks) is now placed in a context
(subjects and the person who scored them), making it meaningful and useful.

Transformation from Data to Information:


• Data is collected and then processed or analyzed.
• After processing, data becomes information that helps in drawing conclusions,
making decisions, or understanding a situation.
For example, in a business context:
• Data: Sales figures for different products.
• Information: A report that shows the best-selling products over the past quarter,
indicating trends and helping management make decisions.
Thus, information is essentially data that has been processed in a way that gives it meaning,
relevance, and value for the user.
Data is information that can be interpreted and used by computers, and a database is a
collection of related data. Data can be quantitative or qualitative, and it's typically stored
electronically in a database or file.
A database is an organized collection of structured information or data, typically stored
electronically in a computer system. A Database Management System (DBMS) allows users
to store, retrieve, and manipulate this data efficiently.

Need for Databases:


• Data Organization: A database organizes data systematically to facilitate easy access,
management, and updating.
• Data Integrity: Enforces constraints to ensure that the data remains accurate and
consistent.
• Data Security: Controls access to data and ensures that only authorized users can
perform operations on the data.
• Data Sharing: Multiple users can access the data simultaneously in a controlled manner.
• Redundancy Control: Databases reduce data duplication, ensuring that storage is
optimized.
• Data Independence: The structure of the database can be changed without affecting
the data access.

Relational Data Model:


A relational database is a type of database that stores data in the form of tables (also
known as relations). Each table consists of rows (tuples) and columns (attributes).

In the context of a School Database, data is stored in the form of tables (relations). Each
table consists of rows (tuples) representing individual records, and columns (attributes)
representing the characteristics of those records.
Example: ‘Students’ Table

StudentID Name Age Class Email

1 Angavai 15 10 [email protected]

2 Malimizhi 16 11 [email protected]

3 Kuzhali 14 9 [email protected]
• Relation (Table): A table in a relational database that stores data in rows and columns.
The table Students is a relation in the school database. It stores information about
students, such as their ID, name, age, class, and email.

• Attribute (Column): A column in a table that represents the property or characteristic of


the data.
Each column in the Students table (like StudentID, Name, Age, Class, Email) is
an attribute. These represent different properties or characteristics of the student data.

• Tuple (Row): A single row in a table, representing a record.


Each row in the table is a tuple. For example, the row (1, Angavai, 15, 10,
[email protected]) represents one student’s data.

• Domain: A set of allowable values for an attribute.


The domain defines the set of allowable values for a particular attribute. For example:
• Age has a domain of positive integers, typically between 5 and 18 in a school context.

• Email has a domain of valid email formats.

• Degree: The number of attributes (columns) in a relation.


The degree of the table is the number of attributes (columns) in the relation. In this case,
the Students table has 5 attributes (StudentID, Name, Age, Class, Email), so its
degree is 5.

• Cardinality: The number of tuples (rows) in a relation.


The cardinality of the table is the number of tuples (rows). In this example, the Students
table has 3 rows, so its cardinality is 3.

Keys:
Keys are crucial for identifying unique records in a table and establishing relationships
between tables.
Example: ‘Classes’ Table

ClassID ClassTeacher RoomNumber

1 Mr. Karikalan 101

2 Ms. Raayan 102

3 Mr. Varman 103

1. Candidate Key: A set of attributes that can uniquely identify a tuple in a table.

• In the Students table, potential candidate keys could be StudentID, Email, or


a combination of Name and Email. Each of these attributes (or combination)
can uniquely identify a student.
• For the Classes table, the ClassID can be a candidate key because it uniquely
identifies each class.
2. Primary Key: A candidate key that is chosen to uniquely identify each record in a table.
It cannot be null.

• In the Students table, we can select StudentID as the primary key because it
uniquely identifies each student. A primary key cannot be null, so each student
must have a unique StudentID.
• In the Classes table, ClassID is chosen as the primary key because it uniquely
identifies each class.
3. Alternate Key: Other candidate keys that were not selected as the primary key.

• In the Students table, both Email and the combination of Name and Email
could be alternate keys, as they can also uniquely identify a student. However,
since StudentID is the primary key, these alternate keys are not used as the
main unique identifier.
4. Foreign Key: An attribute or a set of attributes that refers to the primary key of another
table to establish a relationship.

• Suppose we have another table called Enrollments that records which students
are enrolled in which classes:

EnrollmentID StudentID ClassID

1 1 1

2 2 2

3 3 1
• Here, StudentID is a foreign key that refers to the StudentID in the Students
table, establishing a relationship between the Enrollments and Students
tables.
• Similarly, ClassID is a foreign key that refers to the ClassID in the Classes
table, linking Enrollments to Classes.

Putting It Together:
In this school database example:
• The Students table stores the student records.
• The Classes table stores the class information.
• The Enrollments table links students to classes using foreign keys (StudentID and
ClassID).

Keys such as primary keys and foreign keys help ensure the uniqueness of records and
establish relationships between tables, allowing efficient organization and retrieval of data.

Structured Query Language (SQL):


SQL is the standard language for managing and manipulating relational databases. It consists
of various commands categorized into:

1. Data Definition Language (DDL):


Data Definition Language (DDL) is a subset of SQL that's used to create, modify, and
delete database objects
• Create Database: Creates a new database.
CREATE DATABASE Studentdb;

• Use Database: Selects the database for further operations.


USE Studentdb;

• Show Databases: Lists all the databases.


SHOW DATABASES;

• Drop Database: Deletes an existing database.


DROP DATABASE Studentdb;

• Create Table: Defines a new table with attributes and data types.
CREATE TABLE Students (ID INT PRIMARY KEY, Name VARCHAR(50), Age
INT, Email VARCHAR(100));
• Describe Table: Shows the structure of the table.
DESCRIBE Students;

• Alter Table:
o Add Attribute:
ALTER TABLE Students ADD Phone VARCHAR(15);

o Remove Attribute:
ALTER TABLE Students DROP COLUMN Phone;

o Add Primary Key:


ALTER TABLE Students ADD PRIMARY KEY(ID);

o Remove Primary Key:


ALTER TABLE Students DROP PRIMARY KEY;

• Drop Table: Deletes a table.


DROP TABLE Students;

2. Data Manipulation Language (DML):


Data Manipulation Language (DML) is a set of commands used to manipulate (add,
delete, and modify) data in a database.
• Insert Data:
INSERT INTO Students (ID, Name, Age, Email) VALUES (1, ‘Angavai’,
15, ‘[email protected]’);

• Delete Data:
DELETE FROM Students WHERE ID = 1;

• Select Data:
SELECT * FROM Students;

Operators in SQL:
• Mathematical Operators: +, -, *, /
• Relational Operators: =, !=, <, >, <=, >=
• Logical Operators: AND, OR, NOT

Clauses in SQL:
• Alias: Used to give a temporary name to a table or column.
SELECT Name AS StudentName FROM Students;

• Distinct Clause: Removes duplicate records.


SELECT DISTINCT Age FROM Students;

• Where Clause: Filters records based on conditions.


SELECT * FROM Students WHERE Age > 18;

• In Clause: Specifies multiple possible values.


SELECT * FROM Students WHERE Age IN (18, 19, 20);

• Between Clause: Selects values within a range.


SELECT * FROM Students WHERE Age BETWEEN 18 AND 25;

• Order By Clause: Sorts the result set.


SELECT * FROM Students ORDER BY Name ASC;

• Meaning of Null: Represents the absence of a value.


• Is Null / Is Not Null: Checks for null values.
SELECT * FROM Students WHERE Email IS NULL;

Update Command:
• Update Data:
UPDATE Students SET Email = '[email protected]' WHERE ID = 1;

Aggregate Functions:
• Max: Finds the maximum value.
SELECT MAX(Age) FROM Students;

• Min: Finds the minimum value.


SELECT MIN(Age) FROM Students;

• Avg: Finds the average value.


SELECT AVG(Age) FROM Students;

• Sum: Calculates the sum.


SELECT SUM(Age) FROM Students;

• Count: Counts the number of rows.


SELECT COUNT(*) FROM Students;
Group By Clause:
• Groups records with the same values in specified columns.
SELECT Age, COUNT(*) FROM Students GROUP BY Age;

Having Clause:
• Used to filter groups based on conditions.
SELECT Age, COUNT(*) FROM Students GROUP BY Age HAVING COUNT(*) > 1;

Joins:
• Cartesian Product: Produces all combinations of rows.
SELECT * FROM Students, Courses;

• Equi-Join: Joins tables using equality conditions. Also called as Inner-Join


SELECT Students.Name, Courses.CourseName FROM Students JOIN Courses ON
Students.ID = Courses.StudentID;
- This joins Students and Courses based on StudentID.
• Natural Join: Joins tables automatically based on common attributes.
SELECT * FROM Students NATURAL JOIN Courses;

- Joins tables automatically on common attributes.


• Left Join:
SELECT Students.Name, Courses.CourseName

FROM Students

LEFT JOIN Courses ON Students.StudentID = Courses.StudentID;

- Retrieves all records from Students even if there are no matching records in
Courses.

• Right Join:
SELECT Students.Name, Courses.CourseName

FROM Students

RIGHT JOIN Courses ON Students.StudentID = Courses.StudentID;

- Retrieves all records from Courses even if there are no matching records in
Students.

• Full Join:
SELECT Students.Name, Courses.CourseName

FROM Students

FULL OUTER JOIN Courses ON Students.StudentID = Courses.StudentID;

- Retrieves all records when there is a match in either Students or Courses.

Interface of Python with an SQL Database:


Python can be integrated with SQL databases using libraries like mysql.connector, allowing
developers to perform database operations directly through Python scripts.

Connecting SQL with Python:


import mysql.connector #Establish connection

conn = mysql.connector.connect(

host="localhost",

user="root",

password="mypass",

database="Studentdb"

#Create a cursor

cursor = conn.cursor()

Executing Queries:
• Insert Data:
cursor.execute("INSERT INTO Students (ID, Name, Age) VALUES (%s, %s,
%s)", (1, 'John', 20))

conn.commit() # Save changes

• Update Data:
cursor.execute("UPDATE Students SET Age = 21 WHERE ID = 1")

conn.commit()

• Delete Data:
cursor.execute("DELETE FROM Students WHERE ID = 1")

conn.commit()
Fetching Data:
• Fetch One Record:
cursor.execute("SELECT * FROM Students")

row = cursor.fetchone()

print(row)

• Fetch All Records:


rows = cursor.fetchall()

for row in rows:

print(row)

Row Count:
cursor.execute("SELECT * FROM Students")

print("Number of rows:", cursor.rowcount)

Using Format Specifier:


cursor.execute("INSERT INTO Students (ID, Name, Age) VALUES (%s, %s, %s)",
(2, 'Jane', 22))

You might also like