SQL Class 12 Notes | CBSE Computer Science –
techtipnow
https://techtipnow.in/sql-class-12-notes/
SQL Class 12 Notes is prepared for the students learning Computer
Science Class 12. This SQL Class 12 Notes covers all the topics of Chapter 8
of NCERT textbook of Computer Science Class 12. It includes all DDL and
DML Commands, Aggregate functions, Group By, Joins with many
different examples.
What is SQL?
SQL stands for Structured Query Language. It is developed to manage
database. SQL enable us to create database, insert data, and update data as
per requirement and retrieve data.
What are the Categories of SQL Commands?
All SQL commands are categorized in two types:
Data Definition Language (DDL)
Data Manipulation language (DML)
Data Definition Language (DDL)
DDL is used to define structure and constraints of data
It also defines key constraints, relationships between tables, and other data
validation constraints.
Example of DDL commands are:
CREATE DATABASE – creates a new database
CREATE TABLE – creates a new table
ALTER TABLE – modifies a table
DROP TABLE – deletes a table
Data Manipulation language (DML)
DML is used to insert, modify and delete data in a database.
Example of DML commands are:
SELECT – extracts data from a table
UPDATE – updates data in a table
DELETE – deletes data from a table
INSERT INTO – inserts new data into a table
What is MySQL?
MySQL is one of the most popular Relational Database Management System
(RDBMS).
MySQL was originally founded and developed in Sweden by David Axmark,
Allan Larsson and Michael Widenius, who had worked together since the
1980s.
Characteristics of MySQL
It is free and Open Source software which does not require to pay for its
usage.
It is easy to use, quick and reliable.
It is platform independent software which works on many operating
systems like
Windows, UNIX, LINUX etc.
It is compatible with many programming languages including JAVA, C++,
PHP, PERL, etc.
It can handle large amount of data very efficiently and accurately.
What are the Datatypes used in MySQL?
Given table shows data types commonly used in SQL.
Data type Use Example
Char(n) Fixed length character string. n denotes max no of Char(6) : sanjay,
characters. harish
Varchar(n) Variable length character string. n denotes max no of Varchar(10): ram,
characters. arjun
Date Date as YYYY-MM-DD ‘2022-07-23’
Integer Whole number 45, 4539
Decimal(3,2): 34.89
Decimal(m,d) Fixed point number. M denotes no of digits stored for
values and d denotes no of decimal points. Decimal(4): 2813
Float Real number 456.23
Creating a Database
To create a database we will give CREATE DATABASE command.
Syntax
CREATE DATABASE <database name>;
Example:
Using a database
To open the database to work USE statements is used.
Syntax
USE <databasename>;
Example:
Viewing the current database
To view the name of current database we can use SELECT DATABASE();
command.
Syntax
SELECT DATABASE();
Drop Database
To delete a database we can use DROP DATABASE command.
Syntax:
DROP DATABASE <database name>;
Show tables
To display list of tables stored in a database we can use SHOW TABLES
command.
Syntax:
SHOW TABLES;
Create Table command
This command is used to create a new table or relation.
Syntax:
CREATE TABLE<table name>
(
<column 1><data type> [constraint] ,
<column 2><data type>[constraint],
<column 3><data type>[constraint]
);
Note: [Constraint] is optional
Example:
CREATE TABLE Item
(
Itemno char(5) primary key,
Itemname varchar(20),
Rate float NOT NULL,
Qty int
);
What are types of Database Constraints?
Database enforces 5 types of constraints mentioned hereunder:
Not Null
Sometimes an attribute may not be allowed to leave blank. Hence Not Null
constraints can be associated in this case.
Example:
CREATE TABLE TEACHER
(
Teacher_ID INTEGER,
First_NameVARCHAR(20) NOT NULL,
Last_NameVARCHAR(20),
Gender CHAR(1),
Date_of_Birth DATE,
Salary FLOAT,
);
Default
To make a value bydefault for an attribute Default constraint can be used.
CREATE TABLE TEACHER
(
Teacher_ID INTEGER,
First_NameVARCHAR(20) NOT NULL,
Last_NameVARCHAR(20),
Gender CHAR(1),
Date_of_Birth DATE,
Salary FLOAT DEFAULT 20000,
);
Primary Key
it ensures followings when applied:
Duplicate data is not allowed in the attribute.
Attribute can not be left blank
A relation can have only primary key
Example:
Foreign Key
it ensures relationship between relations. The main purpose of this constraint
is to check that data entered in one relation is consistent with the data entered
in another relation.
Example:
Consider the following tables:
Item (Itemno, Iname, rate)
Order (Ono, Odate, Ino, qty, total)
Here in this example Ino is the foreign key that references Ino of Item table
which is Primary key.
The SQL command for making Ino to foreign key in Order table is as follows:
Create Order
(
Ono int Primary Key,
Odate date,
Itemno int,
Qty int,
Total int,
FOREIGN KEY (Itemno) REFERENCES Item (Itemno)
);
Screen Shot:
Unique Key
it ensures followings when applied:
Duplicate data is not allowed in the attribute.
A relation can have multiple unique keys
Example:
CREATE TABLE EMPLOYEE
(
Emp_ID INTEGER PRIMARY KEY,
Emp_NameVARCHAR(20) NOT NULL,
Gender CHAR(1),
Date_of_Birth DATE,
Salary FLOAT,
Dept varchar(20) UNIQUE
);
Viewing Structure of table | DESCRIBE command
We can use DESCRIBE or DESC command to view the structure of a table as
mentioned in CREATE TABLE command.
It display table structure including attributes, data types and constraints .
Syntax:
DESCRIBE <table name>;
Or
DESC <table name>;
Example:
Drop table
This command is used to delete a table completely from database. It deletes
structure and data both of table from database.
Syntax:
DROP TABLE <table name>;
Example:
DROP TABLE Orders;
How to modify structure of table?
Alter table
It is used to modify structure of a table. Following are the alteration can be
done using this command:
Adding a column
we can add a new column in existing table.
Example:
ALTER TABLE Item ADD date_of_purchase date NOT NULL;
Dropping a column
A column can be dropped using alter table command as given below:
Example:
ALTER TABLE Item DROP qty;
Modifying a table:
A column can also be modified using Alter Table command as given below:
ALTER TABLE item MODIFY qty SET DEFAULT 100;
How to add Primary Key?
ALTER TABLE item ADD PRIMARY KEY ino;
How to drop primary key?
ALTER TABLE Item DROP Primary key;
DML
Insert command
This command is used to insert a tuple in a relation. We must specify the
name of the relation in which tuple is to be inserted and the values. The
values must be in the same order as specified during the Create Table
command.
Syntax:
INSERT INTO <tablename> VALUES (<values >);
Example: Inserting values in table Item (Ino, Iname, Rate, Qty)
INSERT INTO Item Values (1, ‘soap’,44,120);
Screenshot:
Update command
Update command is used to modify the attribute values of one or more tuples
in a table.
Syntax:
UPDATE <tablename>
SET <expression>
WHERE <criteria>
Example:
UPDATE Item
SET Rate = 30
WHERE itemno = ‘i0001’;
Screenshot:
Delete command
To delete one or more tuples (rows) in a realtion DELETE command is used.
Syntax:
DELETE FROM <tablename>
WHERE <criteria>;
Example:
DELETE FROM item WHERE itemno = ‘i0002’;
Screenshot:
Select command
Select command is used to access or retrieve specific or complete set of
records from database.
Syntax:
SELECT <attribute list> FROM <table name>;
Query1: Display all records from Item table.
Query2: Display itemname with its rate from item table.
Screenshot:
Query3: display name of items which rate is more than 100.
Screenshot:
Query4: display item records which name begins with s.
Code:
Select * from item where itemname like ‘s%’;
Screenshot:
Query5: retrieve item details which rate is less than 100 and qty is more
than 100.
Screenshot:
DISTINCT Command
DISTINCT command is used to eliminate repeated data of a column when
display using SELECT command
Syntax:
SELECT DISTINCT(field that contains repeated data) FROM <table name>
WHERE <criteria>;
Example
SELECT DISTINCT(dept) FROM employee;
WHERE clause
WHERE clause act as a Filter while manipulate records in SQL.
Where clause is used to define Criteria for the records to be retrieved.
It can be used with any DML command such as SELECT, DELETE and
UPDATE.
To define criteria various operators like Arithmetic, Range or Comparison
operators are used in WHERE clause.
Syntax:
SELECT <field(s)> FROM <table name>
WHERE <criteria>;
Example:
Operators used with WHERE clause
Arithmetic operators
Relation operators
Logical operators
BETWEEN operators
IN operators
LIKE operators
Arithmetic operators
We can use arithmetic operators to define expressions in DML SQL
commands.
Arithmetic operators are used with numeric values.
Following table depicts various arithmetic operators:
Arithmetic Operator Description
+ For adding values
– For subtracting values
* For multiplying values
/ For dividing values
% For finding remainders
Relational operators
We can use Relational operators to compare values in SQL.
Mostly used to define criteria in WHERE clause to filter records.
Following table depicts various Relational operators:
Relational Operator Description
= Equal to
> Greater than
< Lesser than
>= Greater than equal to
<= Lesser than equal to
!= or <> Not equal to
Logical operators
Logical operators are used to combine multiple criteria/expression in DML
SQL commands
Mostly used to combine criteria in WHERE clause to filter records.
Following table depicts various Logical operators:
Logical Operator Description
AND Returns true when all criteria/expressions are true
OR Returns true when at least a criteria/expression is true
NOT Negates the result
BETWEEN operator
It is used to define range of values for a particular field in WHERE clause.
It can be used to define range of numerical or chronological values
It includes upper and lower bound given in the range.
IN operator
It is used to set multiple text comparison for a particular field in WHERE
clause.
It can only be used for text comparision.
LIKE operator
It is used to define string expressions (pattern matching) in WHERE clause.
It uses different wildcards (described in image given below) to define string
expression.
Wildcard Description
% Used to match the occurrence of set of characters of any length
_ Underscore used to match occurrence of any single character
Order by clause
Used to display records in sequential manner in data resultset retrieved by
WHERE clause.
Bydefault displays records in ascending order.
Keyword ASC (Ascending) or DESC (descending) can be used with order by
to arrange the data resultset.
Example:
SELECT * FROM item ORDER BY iname;
SELECT * FROM item OREDER BY iname DESC;
What is NULL Value?
NULL represents a missing or unknown value in SQL.
NULL is different from 0 (zero).
Any arithmetic operation performed with NULL value give NULL.
To check for NULL value in a column we use IS NULL operator.
Example
Aggregate function
Are also known as Multiple Row Functions.
It works on Multiple rows together rather single row
It helps to summarize large volume of data
It returns single value for entire table or set of rows
Only one column can be specified within parenthesis of aggregate function.
Multiple aggregate functions can be used together in a SQL Query by
separating them using comma.
Function Description Example
Sum(field) Returns sum of all rows of specified field Select sum(qty_sold) from order;
Output: 10230
Avg(field) Returns average or mean value of all rows of Select avg(qty_sold) from order;
specified field Output: 780
Max(field) Returns largest value among all rows of Select max(qty_sold) from order;
specified field Output: 1460
Min(field) Returns smallest value among all rows of Select min(qty_sold) from order;
specified field Output: 470
count(field) Counts and return total rows of specified Select count(qty_sold) from order;
field Output: 72
Group By
The Group By clause helps to summarize large volume of records. It combines
all those records that have identical values in a particular field or a group of
fields and produces one summary record per group.
We can use aggregate functions to work on the grouped values.
Syntax:
SELECT <field(s)>, <aggregate function(s)>
FROM <table name>
WHERE <condition>
GROUP By <field(s)>
Example:
Having clause
Helps to filter summarized result produced after grouping.
It is like post filter which retrieves records from resultset produced after
group by query.
It can include aggregate functions to set the filter criteria
Syntax:
SELECT <field(s)>, <aggregate function(s)>
FROM <table name>
WHERE <condition>
GROUP By <field(s)>
HAVING <expression>
ORDER BY <field(s)> ASC/DESC
Joins
A Join ia an operation which is used to combine tuples from one or more
tables based on one or more common field between them.
In another way we can say that it is query written to retrieves data from two
or more tables as per given condition.
Different types of joins are:
Cartesian product
Equi join
Natural join
Inner Join
PAGE UNDER CONSTRUCTION