Computer Science Class 12 - SQL
Computer Science Class 12 - SQL
2
-
2
2
0
2
DBMS-DATABASE MANAGEMENT SYSTEM
DBMS:
A database management system (DBMS) is a collection of interrelated data and a set of
programs to access those data. The collection of data, usually referred to as the
database, contains information relevant to an enterprise. The DBMS provides a way to
store and retrieve database information that is both convenient and efficient.
Keeping organizational information in a file- processing system has a number of major
disadvantages like:
a) Data redundancy and inconsistency
b) Difficulty in accessing data
c) Data isolation
d) Integrity problems
e) Atomicity problems
f) Concurrent access anomalies
g) Security problems
These difficulties among others, prompted the development of database systems.
● Database systems are designed to manage large bodies of information.
● Management of data involves both defining structures for storage of information
and providing mechanisms for the manipulation of information.
● The database system also must ensure the safety of the information stored,
despite system crashes or attempts at unauthorized access. If data are to be
shared among several users, the system must avoid possible anomalous results.
● DBMS lets users to create a database, store, manage, update/modify and retrieve
data from that database by users or application programs.
Some examples of open source and commercial DBMS include MySQL, Oracle,
PostgreSQL, SQL Server, Microsoft Access, MongoDB.
Database systems are widely used. Some representative applications are :
a) Banking
b) Airlines
c) Universities
d) Telecommunications
e) Sales
f) Finance, etc.
A data model describes the structure of the database, including how data are defined
and represented, relationships among data, and the constraints.
Database schema: Database Schema is the design of a database. It is the skeleton of the
database that represents the structure (table names and their fields/columns), the type
of data each column can hold, constraints on the data to be stored (if any), and the
relationships among the tables.
Database schema is also called the visual or logical architecture as it tells us how the data
are organized in a database.
Data constraint: Restrictions or limitations are put on the type of data that can be inserted
in one or more columns of a table to ensure accuracy and reliability of data in the
database.
Meta – Data or Dictionary: A database catalog or dictionary that has data about data.
Database instance: The state of database at any time, after loading of data. A database
schema can have different instances at different times.
Query: A query is a request to a database for obtaining information in a desired way.
Data Manipulation: Modification of database consists of three operations viz. Insertion,
Deletion or Update.
Database engine: Database engine is the underlying component or set of programs used
by a DBMS to create database and handle various queries for data retrieval and
manipulation.
Relational model:
The relational model uses a collection of tables to represent both data and the
relationships among those data.
Each table has multiple columns, and each column has a unique name. The relational
model is an example of a record – based model.
Record- based models are so named because the database is structured in fixed- format
records of several types. Each table contains records of particular type. Each record type
defines a fixed number of fields/attributes.
The columns of the table correspond to the attributes of the record type.
A row in a table represents a relationship among a set of values. The relational data model
is the most widely used data model.
Other types of data models include object-oriented data model, entity-relationship data
model, document model and hierarchical data model.
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 175
Relation: A Relation is logically related data organized in the form of tables.
Attribute/ Field: Column of a table is called Attribute or Field.
Tuple/ Entity/ Record: Rows of a table is called Tuple or Record.
Domain: It is collection of values from which the value is derived for a column.
Degree - Number of columns (attributes) in a table.
Cardinality - Number of rows (Records) in a table.
Candidate Key –It is an attribute or a set of attributes or keys participating for Primary
Key, to uniquely identify each record in that table.
Alternate Key – Out of all candidate keys, only one gets selected as primary key,
remaining keys are known as alternate or secondary keys.
Foreign Key – Foreign keys are the columns of a table that points to the primary key of
another table.
STRUCTURED QUERY LANGUAGE(SQL)
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.
⮚ Unique Constraint :-This ensures that no rows have the same value in the
specified column(s)
Syntax:
Create table EMP (ecode integer unique, ename char(20),sex char(1),grade
char(2));
Unique constraint applied on ecode of EMP table ensures that no rows have the same
ecode value
⮚ Primary key Constraint:- This declares a column as the primary key of the table
This is similar to unique constraint except that one column (or one group of
columns)can be applied in this constraint .
The primary key cannot allow NULL values but Unique key allows NULL values.
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table
is created:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255), Age int, PRIMARY KEY (ID));
⮚ SHOW DATABASES
You can see list of existing databases by running following SQL command.
Syntax: mysql>SHOW DATABASES;
⮚ USE
You can use SQL command USE to select a particular database.
Syntax: mysql>USE database_name;
⮚ DROP DATABASE
The DROP DATABASE statement is used to drop an existing SQL database.
Syntax :mysql>DROP DATABASE database_name;
CREATE TABLE
The CREATE TABLE statement is used to create a new table in a database.
Syntax: CREATE TABLE table_name ( column1 datatype, column2
datatype, column3 datatype, ...... );
Example: The following example creates a table called "Persons" that contains five
columns:
PersonID, LastName, FirstName, Address, and City:
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
⮚ SHOW TABLES;
We can get the number of table information of a database using the following
statement:
mysql> SHOW TABLES;
⮚ DESCRIBE TABLE
Use the DESCRIBE command to show the structure of the table, such as column names,
constraints on column names, etc. The DESC command is a short form of the DESCRIBE
command. Both DESCRIBE and DESC commands are equivalent.
Syntax The following are the syntax to display the table structure:
mysql> DESCRIBE | DESC table_name;
ALTER TABLE - ADD Column/Attribute To add a column in a table, use the following
syntax:
To create a PRIMARY KEY constraint on the "ID" column when the table is already
created, use the following SQL:
ALTER TABLE table_name ADD PRIMARY KEY (Column_name);
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2,
value3, ...);
2. If you are adding values for all the columns of the table, you do not need to specify
the column names in the SQL query. However, make sure the order of the values is in
the same order as the columns in the table. Here, the INSERT INTO syntax would be as
follows:
DELETE Syntax:
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in the
DELETE statement. The WHERE clause specifies which record(s) should be deleted. If you
omit the WHERE clause, all records in the table will be deleted!
The following SQL statement deletes all rows in the "Customers" table, without deleting
the table:
Here, column1, column2, ... are the field names of the table you want to select data
from. If you want to select all the fields available in the table, use the following syntax:
Operator Description
= Equal
The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
● The AND operator displays a record if all the conditions separated by AND are TRUE.
● The OR operator displays a record if any of the conditions separated by OR is TRUE.
AND Syntax
FROM table_name
OR Syntax
FROM table_name
NOT Syntax
FROM table_name
IN Syntax
SELECT column_name(s)
FROM table_name
or:
SELECT column_name(s)
FROM table_name
The BETWEEN operator selects values within a given range. The values can be numbers,
text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.
ORDER BY Syntax
FROM table_name
Example
ORDER BY Country;
The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
The following SQL statement selects all customers from the "Customers" table, sorted by
the "Country" and the "CustomerName" column. This means that it orders by Country,
but if some rows have the same Country, it orders them by CustomerName:
SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.
Alias Table
UPDATE Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ...
WHERE condition;
UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new
contact person and a new city.
UPDATE Customers
WHERE CustomerID = 1;
The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only
want to list the different (distinct) values.
The following SQL statement selects all (including the duplicates) values from the
"Country" column in the "Customers" table:
The following SQL statement selects only the DISTINCT values from the "Country"
column in the "Customers" table:
SELECT DISTINCT Country FROM Customers;
The following SQL statement lists the number of different (distinct) customer countries:
The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
There are two wildcards often used in conjunction with the LIKE operator:
The percent sign and the underscore can also be used in combinations!
LIKE Syntax
FROM table_name
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second
position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at
least 2 characters in length
WHERE CustomerName LIKE 'a %' Finds any values that start with "a" and are at
least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with
"o"
What is a NULL Value?
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
We will have to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntax
SELECT column_names
FROM table_name
SELECT column_names
FROM table_name
The IS NULL operator is used to test for empty values (NULL values).
The following SQL lists all customers with a NULL value in the "Address" field:
FROM Customers
The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).
The following SQL lists all customers with a value in the "Address" field:
SELECT CustomerName, ContactName, Address
FROM Customers
Function Description
Count() function
Count () has got three formats:
Count(*)
This function returns the number of rows in the table that satisfy the criteria of select
statement.
In its counting, it includes duplicate rows and rows with NULL values in any of the
column
Example:
Q: Count the number of employees in the employee table.
Count(<col name>)
● This function returns the number of not null values in the specified column, but
includes duplicate values in counting
Example
Q; count the number of grades of employees in the employee table.
To divide the rows in a table into smaller groups of information, group by clause
is used.
It combines all identical rows in a group of fields.
A column name is used for grouping
Syntax;-
SELECT [DISTINCT] <COL LIST> FROM <TABLE NAME>
[WHERE <CONDITION>]
[GROUP BY < GROUP BY EXPR>]
[HAVING <CONDITION>]
[ORDER BY <COL NAME>/<EXPR> ASC/DESC];
NOTE -
● Group by expression specifies the columns whose values determine the basics for
grouping rows
● WHERE clause is always before GROUP BY if required.
Example
Q. Display the no of employees in each zone.
Q. Display the no of employees in each zone whose salary is greater than 32000
Having clause
● This clause is used to restrict rows resulting after grouping.
● Steps followed in execution of select with group by and having clause-
1. Rows are grouped according to the columns in the group by clause.
2. Then the group function is applied.
3. Groups matching with Having clauses are displayed.
Example
Q. Display only whose departments with sum of salaries whose total salary is greater
than 70000
Joins in MySQL
● A join is used when data from two or more tables is required.
● Rows in one table can be joined to the rows in another table based on the
common values existing in corresponding columns of two tables.
● Joins are used to retrieve data from tables related to each other with primary-
foreign key relationships.
● There are many types of join
Equi join
● Specified columns from the joining tables are checked for equality.
● Values from joining tables are retrieved only if the condition in where clause is
satisfied.
SYNTAX:-
SELECT <column_name (s)>
FROM <table_name1>, <table_name2>, .... , <table_nameN>
WHERE <table_name1>.<column_name> = <table_name2>.<column_name>;
Natural Join
This clause is based on all the columns in the two tables that have the same name.
It selects the rows from two tables that have equal values in the matched columns.
SYNTAX:-
SELECT [column_names | *]
FROM table_name1
NATURAL JOIN table_name2;
Note-No need to specify the column names to join. Works with same column name in
both the tables. The Resulting table has unique columns.
Interface Python with SQL database
Contents:
Connecting SQL with Python
Creating database connectivity applications
Performing insert, delete, update,delete queries
Display data by using fetchone(), fetchall(), fetchmany (),
rowcount()
Database connectivity
Database connectivity refers to connection and communication between an application
and a database system.
The term “front-end” refers to the user interface, while “back-end” means the server,
application and database that work behind the scenes to deliver information to the user.
Mysql.connector- Library or package to connect from python to MySQL.
Before we connect the program with mysql , we need to install connectivity package named
mysql-connector- python
Command to install connectivity package:- pip install mysql-connector-python
Command to import connector:- import mysql.connector
Steps for python MySQL connectivity
1 . Install Python
2. Install MySQL
3. Open Command prompt
4. Switch on internet connection
5. Type pip install mysql-connector-python and execute
6. Open python IDLE
7. import mysql.connector
1. Start Python- start python editor to create our own python script.
The connect statement creates a connection to the mysql server and returns a
MySQL connection object.
Syntax:
con=mysql.connector.connect(host=”localhost”,user=”root”, passwd=” “)
Syntax:
<cursor object>=<connectionobject>.cursor()
Eg: cursor=con.cursor()
The above code will execute the sql query and store the retrieved records
(resultset) in the cursor object(cursor).
Result set refers to a logical set of records that are fetched from the database
by executing an sql query and made available in the program.
The records retrieved from the database using SQL select query has to be
extracted as record from the result set. We can extract data from the result set
using the following fetch () function.
fetchall()
fetchone()
fetchmany()
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
")
mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE SCHOOL")
# SHOW DATABASE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system")
mycursor=mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print (x)
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="s
ystem",database="student")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE FEES (ROLLNO INT,NAME
VARCHAR(20),AMOUNT INT);")
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="student")
mycursor=mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
#TO DESCRIBE TABLE STRUCTURE USING PYTHON INTERFACE
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system"
,database="student")
mycursor=mydb.cursor()
mycursor.execute("DESC STUDENT")
for x in mycursor:
print(x)
# TO EXECUTE SELECT QUERY USING A PYTHON INTERFACE
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",passwd="12345
",database="student")
c=conn.cursor()
c.execute("select * from student")
r=c.fetchone()
while r is not None:
print(r)
r=c.fetchone()
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="syste
m",database="student")
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE STUDENT MODIFY GRADE CHAR(3)")
commit( ): After executing insert or update query we must commit our
transaction using commit method of connection object.
Eg: mycon.commit()
rollback( ): mysqlConnection.rollback() reverts the changes made by the
current transaction.
rowcount: This attribute returns the number of rows that were affected
by an execute()