MYSQL NOTES 2024 XII
MYSQL NOTES 2024 XII
MYSQL NOTES 2024 XII
E-CONTENT
CLASS : XII
SUBJECT : COMPUTER SCIENCE PYTHON
TOPIC : DATABASE & ITS CONCEPTS
# Introduction:-
Database may be defined as collection of interrelated data stored together in order to
serve multiple applications.
It is basically a computerized record keeping system . Database contains information about
one particular enterprise
Note:-
In the traditional file processing system , permanent records are stored in various files . A
number of different applications programs are written to extract records from and add records
to the appropriate files. But this scheme has number of disadvantages such as Data
Redundancy , Data inconsistency ,Insecure data , Incorrect Data. So solution to all problem is
DataBase Management System.
Note :
Data Redundancy refers to duplication of data
Data Inconsistency refers to multiple mismatching copies of data.
# What is DBMS?
It stands for Database Management System. It refers to the software that is responsible for
storing , maintaining and utilizing databases. It is used to manage database effectively
and efficiently.
# RELATIONAL DATA MODEL:-
It is the model in which data is organized into tables. i.e. in form of rows and columns. Since
a rows in a table represents relationships among set of values and table is collection of such
relationships therefore table is also called Relation.
Rows of relation are called Tuples.
Columns of the tables are called Attributes.
# COMPONENTS OF TABLE:
1. Byte:
It is group of 8 bits and is used to store a character.
2. Data Item:
Page | 1
It is the smallest unit of the named data. It represents one type of information and is called
as field.
3. Record:
It is the named collection of data items which represents a complete unit of information.
4. Table:
It is the named collection of all occurrences of given type of logical record.
Examples of RDBMS:
Oracle
Microsoft SQL Server
MySQL
Postgre SQL
IBM DB2
SQLite
Page | 2
Domain:-
It is a pool of values from which the actual values appearing in the given column are drawn. A
domain is said to be atomic if the elements of the domain are considered to be indivisible units.
DEGREE OF A RELATION:
The number of attributes in a relation is called degree of relation.
CARDINALITY OF A RELATION:
The number of rows in a relation is called cardinality of relation.
In the given figure , degree ( no of columns ) = 3 , cardinality ( no. of rows/records ) =4
# CANDIDATE KEY:-
Each table has only a single primary key. Each relation may have one or more candidate key.
One of these candidate key is called Primary Key. Each candidate key qualifies for Primary Key.
Therefore candidates for Primary Key is called Candidate Key.
Candidate key can be a single column or combination of more than one column. A minimal
super key is called a candidate key.
Example
EmployeeID and EmployeeEmail, both can be a Primary key; therefore both are candidate
keys. Select any of the as Primary Key for your table, since a table can have only a single
Primary Key.
Page | 3
Student_ID Student_Enroll Student_Name Student_Email
Above, Student_ID, Student_Enroll and Student_Email are the candidate keys. They are
considered candidate keys since they can uniquely identify the student record.
# PRIMARY KEY:-
A primary key is a field in a table which uniquely identifies each row/record in a database
table. Primary keys must contain unique values. A primary key column cannot have NULL
values.
A table can have only one primary key, which may consist of single or multiple fields. When
multiple fields are used as a primary key, they are called a composite key.
If a table has a primary key defined on any field(s), then you cannot have two records having
the same value of that field(s).
Here is the syntax to define the ID attribute as a primary key in a CUSTOMERS table.
CREATE TABLE CUSTOMERS
(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
# ALTERNATE KEY:-
Alternate Key or Secondary Key is the key that has not been selected to be the primary key,
but are candidate keys. However, it is considered a candidate key for the primary key.
A candidate key not selected as a primary key is called alternate or secondary key.
Let us see an example −
Page | 4
Student_ID Student_Enroll Student_Name Student_Email
Student_ID, Student_Enroll and Student_Email are the candidate keys. Select any one
of the candidate key as the primary. Rest of the two keys would be Alternate or Secondary
Key.
Suppose you select Student_ID as primary key, then ,
Student_Enroll and Student_Email will be Alternate Key (candidates of primary key).
# FOREIGN KEY:-
The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in
another table.
The table with the foreign key is called the child table, and the table with the primary key is
called the referenced or parent table.
Persons Table
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
Page | 5
Orders Table
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the
"Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the parent table.
It is a system of rules that a DBMS uses to ensure that relationships among records in related
tables are valid. and user don’t accidentally delete or change the related data. When Referential
Integrity is enforced following rules must be observed.
1. You cannot enter a value in foreign key field of related table that doesn’t exists in the
primary key of primary table.
2. You cannot delete a record from primary key table if matching record exists in related table.
3. You cannot change a primary key value in the primary table , if that record has related
records.
# What is MySQL?
It is freely available open source RDBMS that uses Structured Query Language. It is
downloadable from site www.mysql.org. In this information is stored in form of tables. A
single MySQL database can contain many tables at once & store thousands of records. It
Page | 6
provides secure environment for storing , maintaining and accessing data. It is fast , reliable
and scalable .
# FEATURES OF MySQL:
1. fast speed
2. Free of cost
3. Ease of use
4. Query language support
5. Portability
6. flexible and secure.
7. Can handle large databases
8. Connectivity
These commands are used to update the database schema that's why they come under Data
definition language.
DML stands for Data Manipulation Language. It is used for accessing and manipulating data
in a database. It handles user requests.
Page | 7
3. Data Control Language
o DCL stands for Data Control Language. It is used to retrieve the stored or saved data.
o The DCL execution is transactional. It also has rollback parameters.
There are the following operations which have the authorization of Revoke:
TCL is used to run the changes made by the DML statement. TCL can be grouped into a logical
transaction.
# DATA TYPES:-
MySQL uses many different data types broken into three categories −
Numeric
Date and Time
String Types.
The following list shows the common numeric data types and their descriptions −
INT − A normal-sized integer that can be signed or unsigned. If signed, the allowable
range is from -2147483648 to 2147483647. If unsigned, the allowable range is from 0
to 4294967295. You can specify a width of up to 11 digits.
TINYINT − A very small integer that can be signed or unsigned. If signed, the
allowable range is from -128 to 127. If unsigned, the allowable range is from 0 to 255.
You can specify a width of up to 4 digits.
SMALLINT − A small integer that can be signed or unsigned. If signed, the allowable
range is from -32768 to 32767. If unsigned, the allowable range is from 0 to 65535.
You can specify a width of up to 5 digits.
Page | 8
MEDIUMINT − A medium-sized integer that can be signed or unsigned. If signed, the
allowable range is from -8388608 to 8388607. If unsigned, the allowable range is from
0 to 16777215. You can specify a width of up to 9 digits.
BIGINT − A large integer that can be signed or unsigned. If signed, the allowable
range is from -9223372036854775808 to 9223372036854775807. If unsigned, the
allowable range is from 0 to 18446744073709551615. You can specify a width of up
to 20 digits.
FLOAT(M,D) − A floating-point number that cannot be unsigned. You can define the
display length (M) and the number of decimals (D). This is not required and will default
to 10,2, where 2 is the number of decimals and 10 is the total number of digits
(including decimals). Decimal precision can go to 24 places for a FLOAT.
DOUBLE(M,D) − A double precision floating-point number that cannot be unsigned.
You can define the display length (M) and the number of decimals (D). This is not
required and will default to 16,4, where 4 is the number of decimals. Decimal precision
can go to 53 places for a DOUBLE. REAL is a synonym for DOUBLE.
String Types
Although the numeric and date types are fun, most data you'll store will be in a string format.
This list describes the common string datatypes in MySQL.
CHAR(M) − A fixed-length string between 1 and 255 characters in length (for example
CHAR(5)), right-padded with spaces to the specified length when stored. Defining a
length is not required, but the default is 1.
VARCHAR(M) − A variable-length string between 1 and 255 characters in length. For
example, VARCHAR(25). You must define a length when creating a VARCHAR field.
Page | 9
Difference between CHAR and VARCHAR data type:
The CHAR data type specifies a fixed length character string . When any column is
given a datatype as CHAR(n) , then MySQL ensures that all values stored in that column have
the length ‘n’ bytes. If value of column is less than ‘n’ bytes then blank spaces are added.
, but size of value remains ‘n’ bytes.
On the other hand ,VARCHAR data type specifies a variable length field. When a column
is given a datatype VARCHAR(n) then maximum size a value in this column can have is ‘n’
bytes. Each value in the column stores exactly as user specifies. i.e. no blank spaces are
added in case the length is shorter than the maximum length ‘n’. But if user exceeds
the length beyond ‘n’ , error message comes.
# NULL VALUES:-
If a column in a row has no value , then column is said to be NULL. NULL value can appear in
any column of any data type but the only condition is that column should not be restricted by
NOT NULL or Primary key constraint. Basically we use NULL value when actual value is not
known or the value is not meaningful.
# CONSTRAINTS IN MYSQL:-
The constraint in MySQL is used to specify the rule that allows or restricts what values/data
will be stored in the table. They provide a suitable method to ensure data accuracy and integrity
inside the table. It also helps to limit the type of data that will be inserted inside the table. If
any interruption occurs between the constraint and data action, the action is failed.
1. Column Level Constraints: These constraints are applied only to the single column that
limits the type of particular column data.
2. Table Level Constraints: These constraints are applied to the entire table that limits the
type of data for the whole table.
This constraint specifies that the column cannot have NULL or empty values. The below
statement creates a table with NOT NULL constraint.
Page | 10
mysql> CREATE TABLE Student
( Id INTEGER,
LastName TEXT NOT NULL,
FirstName TEXT NOT NULL,
City VARCHAR(35) );
The second command given above will indicate an error because the column LastName has
NOT NULL constraint and user is trying to enter NULL value in the column which is not allowed
by MSQL.
UNIQUE CONSTRAINT:-
This constraint ensures that no two rows have the same value in specified column. for example:
Create table employee
( ecode integer UNIQUE,
enamechar(10),
grade char(1),
gross float
);
As per the above example UNIQUE constraint has been applied on the ecode field of employee
table. It means that no two rows can have same ecode.
NOTE:-
But the column having UNIQUE constraint allows NULL value and there can be multiple UNIQUE
key constraints in a table.
Page | 11
MYSQL COMMANDS
1. CREATE DATABASE:
This command is used to create database in MySQL.
Syntax:-
create database EMP_DATA;
2. SHOW DATABASES:
The SHOW DATABASES statement lists all databases in the MySQL database server. This
command is used to check the database that you’ve created or to see all the databases on
the database server before you create a new database, for example:
show databases ;
3. USE DATABASE:-
Before working with a particular database, you must tell MySQL which database you want
to work with by using the USE statement.
example:
use EMP_DATA;
4. DROP DATABASE
Removing/ dropping database means deleting all the tables contained in the database and
the database itself permanently. Therefore, it is very important to execute this query with
extra cautions.
example:-
5. CREATE TABLE:
The Create table command allows the user to create table in the database. When table is
created , its columns are named , datatypes and sizes are supplied for each column .
Syntax:
Create table <tablename>
( <columnname> <datatype> [<size>] ,
<columnname> <datatype> [<size>],
………..
………… );
6. DESCRIBE TABLES:-
Page | 12
Once you execute the CREATE TABLE statement to create the desired table, you can view
its structure by using the DESCRIBE statement:
example:
DESC employee;
7. SHOW TABLES:
This command is used to check all the tables names in the database.
example:
SHOW TABLES;
8. ALTER TABLE
The Alter Table command is used to change the definitions of existing table like adding new
column , modifying existing columns , add or removing constraint.
example:
ALTER TABLE EMPLOYEE ADD GROSS FLOAT;
example:
ALTER TABLE EMPLOYEE DROP COLUMN GROSS;
example :
syntax
ALTER TABLE <TABLENAME> CHANGE <OLDNAME><NEWNAME>;
example:
ALTER TABLE EMPLOYEE CHANGE ENAME EMPNAME;
syntax
Alter Table <Tablename> Modify Column <Newdatatype><Newsize>;
Page | 13
example:
ALTER TABLE EMPLOYEE MODIFY ENAME char(30);
example :
9. DROP TABLE
This command is used to drop / remove the table but before dropping the table it must be
empty i.e. all rows inside the table must be removed. A table with rows cannot be deleted.
example:
DROP TABLE EMPLOYEE;
example:
insert into employee values(1, ‘Arun’ , 34000, ‘A’);
alternate way:
The columns that are not listed in the insert command will have their default value , if it is
defined for them , otherwise NULL value
11. SELECT :-
This command enables the user to make queries on the database. A query is a command
that is given to produce certain specified information from the database table.
Syntax:
SELECT <columnname>,<columnname2>…… from <tablename>;
example:
SELECT * FROM EMPLOYEE;
The above command will display all the records of the table employee.
SELECT ENAME,ESALARY FROM EMPLOYEE;
12. DISTINCT:-
By default , data is selected from all rows of the table , even if the data appearing in the
result gets duplicated. The Distinct keyword eliminates duplicate rows from the result of
select statement.
example:
select distinct ename from employee;
Page | 14
13. ALL KEYWORD:-
14.
If in place of distinct user gives ALL keyword then the result will retain the duplicate output
rows.
example:
SELECT ALL ENAME FROM EMPLOYEE;
example:
select ename , egross from employee where egrade= ‘E2’ or egrade= ‘E4’ ;
select ename , egross from employee where egrade= ‘E2’ and ecode=101;
select ename , egross from employee where NOT egrade=’A’;
Page | 15
example:
select ename , salary from employee where ecode=111;
20. IN OPERATOR:
To specify a list of values IN operator is used as it selects values that match any value in
given list .
example:
select * from employee where salary IN(20000,30000);
In between operator both lower limit and upper limit of the range are inclusive.
When you use the SELECT statement to query data from a table, the result set is not sorted.
It means that the rows in the result set can be in any order.
To sort the result set, you add the ORDER BY clause to the SELECT statement. The following
illustrates the syntax of the ORDER BY clause:
In this syntax, you specify the one or more columns which you want to sort after the ORDER
BY clause.
The ASC stands for ascending and the DESC stands for descending. You use ASC to sort
the result set in ascending order and DESC to sort the result set in descending
order.
Page | 16
ORDER BY column1 ASC;
And this ORDER BY clause sorts the result set in descending order:
By default, the ORDER BY clause uses ASC if you don’t explicitly specify any option.
27. IFNULL ( )
If the user want to substitute null with a value in the output then , use IF NULL( ) function
example:
select ename , salary , IFNULL(ecity, “Delhi”) from employee;
The LIKE operator is used in the WHERE clause of the SELECT , DELETE,
and UPDATE statements to filter data based on patterns.
MySQL provides two wildcard characters for constructing patterns: percentage % and
underscore _
Page | 17
Some of the aggregate functions are :-
example:
select sum(salary) from employee;
select avg(salary) from employee;
select count(*) from employee;
select max(ecode) from employee;
select min(ecode) from employee;
Syntax
SELECT column_name(s)
FROM table_name GROUP BY column_name(s);
example:
select count(*) , ecity from employee group by ecity;
31. HAVING CLAUSE:
The having clause is used with group by clause to place condition because the where
keyword could not be used with aggregate functions.
example:-
select ename , sum(esalary) from employee group by ename having count(*)
>1;
Note: Be careful when updating records in a table! Notice the WHERE clause in
the UPDATE statement. The WHERE clause specifies which record(s) that should be updated.
If you omit the WHERE clause, all records in the table will be updated!
example:
update employee set esalary=esalary+1000;
update employee set esalary=esalary+1000 where ecode>102;
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!
A non equi join is a query that specifies some relationships other than equality between
the columns .
The join in which only one of the identical columns exists is called Natural Join.
examples:-
select last_name , first_name , orderno from persons , orders where
person.p_id=orders.p_id;
Page | 19