You are on page 1of 9

Easy Notes: Database MySql Nitin Ruhela

What is the Database?


A database system is basically a computer based record keeping system. A database is an organized collection of
interrelated data stored together to serve applications. It work like a container which may contains the various database
objects.
Relational Database: Most of the databases stores data in the form of Relations (also called Tables). Such Databases are
known as Relational Database. In other words a Relational Database is a collection of one or more tables.
A database management system is a collection of programs that enable users to create and maintain database and control
all the access to the database. The primary goal of the DBMS is to provide an environment that is both convenient and
efficient for the user to store and retrieve information.
RDBMS: Software used to manage Relational database is called RDBMS
(Relational Database Management System). Some commonly used RDBMS
software are-Oracle, MySQL, MS SQL Server, Sybase and Ingress etc.
Database can contain Tables, Queries, Views, Index.

Why Database System is used? (Advantages)


Databases reduce Redundancy: The database system do not maintain separate copies of the same data, rather all the data
are kept at one place and all application that require data refer to be the centrally maintained database. If any change is to
be made it will be made at just one place and the changed information will be available to other applications. Duplication
of the data is known as data redundancy. However in some cases redundancy still exists to improve system performance,
but such redundancy is controlled and kept to minimum.
Database controls Inconsistency: When data inconsistency in not controlled, there may be occasions on which the two
entries of the same data do not agree i.e. when one of them stores the updated version and the other does not. In that case a
database is said to be inconsistent. By controlling the data redundancy, inconsistency is also controlled.

Database facilitates Sharing of Data: In a database system all the users handling different related application refer and
share the same data store data stored in central location.
When a database contains data to be used by many users, it is important to keep integrity to check to insure that data
values satisfy to certain specified rules for example and invalid dates should not be allowed to enter as 31/02/96.
Database ensures Security: Data are protected against accidental or intentional disclosure to unauthorized person or
unauthorized modification.

Data model
Data model is a collection of concepts that can be used to describe the structure of database. Structure of database means
data types, relationships and constraints. In other words Data model describes, how data is organized or stored in the
database. Many data models are used for database management system, these are:
Relational data model
In this model data is organized into relation or table (i.e.
row and column) a row in a table represents a
relationship of data to each other and also called a tuple
or record. A column is called attribute or field. Mr. E.F
Codd of the IBM proposed the relational model. This
model is flexible and it easy to link two or more tables.
Network data model
In this model, data is represented by collection of records
and relationship among data is shown by links.
Hierarchical data model
In this model, records are organized as tree. A record at
top level is called root record and this may contain
multiple directly linked children records.
Object oriented data model
In this model, data is represented as objects. The collection of similar types of object is called class.

1
Easy Notes: Database MySql Nitin Ruhela
RDBMS Terms
Relation/Table: A table refers to a two dimensional representation of data arranged in columns (also called fields or
attributes) and rows (also called records or tuples).

The tables in a database are generally related to each other to facilitate efficient management of the database. Interrelated
tables also reduce the chances of errors in the database.
A relation has following properties.
1. For a row, each column must have one value only.
2. All rows are distinct i.e. no two rows are identical
3. The ordering of row in not necessary
4. For any given column of a table, all values are of same kind.
Domain: it is a pool (collection/set) of possible values from which the actual value for a column is derived. Like 1, ravi,
12500, rohan, etc.
Record/tuple/entity: the row or records of tables are generally related to a tuples. For example the following is a tuple
from the student table
101 asmit ravi raj nagar bandra east 9485364512 78
Attributes: the column or fields of table are generally referred to as attributes. Every column in a table must have a
unique name. in the above given student table AdmNo, LibCardNo are two attribute.

Degree: the number of attributes in a relation id called the degree of a relation. A relation having 3 attribute is said to be
of degree 3. In the above given table students the degree is 4.
Cardinality: the number of tuples in a relation is called cardinality of the relation. In table student the cardinality is 3.

Introduction to MySQL
MySQL is Open Source, Fast and Reliable Relational Database Management System (RDBMS) software like Oracle,
Sybase, MS SQL Server etc. It was developed by Michael Widenius and AKA Monty and is alternative to many of the
commercial RDBMS.
The main features of MySQL are-
 Open Source & Free of Cost: It is Open Source and available at free of cost.
 Portability: It can be installed and run on any types of Hardware and OS like Linux, MS Windows or Mac etc.
 Security: It creates secured database protected with password.
 Connectivity: It may connect various types of Network client using different protocols and Programming
Languages .
 Query Language It uses SQL (Structured Query Language) for handling database.

MySQL & SQL


In order to access data from the MySQL database, all program and user must use SQL (Structured Query Language). SQL
is a set of commands that are recognized by all the RDBMSs and has become a standard language for database handling.
SQL is a language that enable s you to create and manage a relational database, in which all the information are kept in
tables.
There are numerous version of SQL. The original version was developed at IBM’s San Jose Research Laboratory with a
name of Sequel , as a part of System R project in 1970s. It was standardized by ANSI in 1986 by the name of SQL.
SQL is a Standard Query language whereas MySQL is a DBMS Software based on SQL.

2
Easy Notes: Database MySql Nitin Ruhela
Data types
The data types are the characteristics of data stored in the tables. Data types allow you to specify the type of information
that can be stored in a particular column of a table. For example, you can specify whether a column should consist of
numeric value or alphanumeric string. Defining a data type for each column in a table helps to prevent incorrect data from
entering in a database. The various data types that a column can hold in MySql are:
MySql uses many different data types, divided into three categories.
Data type Description
Integer or Int You can specify a width up to 11 digits (signed or unsigned). If signed,
the range is from -2147483648 to +2147483647. If unsigned, the range
from 0 to 4294967295.
Tinyint You can specify a width up to 4 digits (signed or unsigned). If signed, the
range is from -128 to +127. If unsigned, the range from 0 to 255.
Smallint You can specify a width up to 5 digits (signed or unsigned). If signed, the
range is from -32768 to +32767. If unsigned, the range from 0 to 65535.
Float(M,D) Stores real numbers up to M digits length(including .) with D decimal
Numeric places. A floating point number that cannot be unsigned. Decimal
precision can go to 24 places for a Float.
Double(M,D) Stores real numbers up to M digits length(including .) with D decimal
places. A floating point number that cannot be unsigned. Decimal
precision can go to 53 places for a Double.
Decimal It can represent number with or without the fractional part (like 17.32,
345). The maximum number of digits may be specified in the size
parameter. The maximum number of digits to the right of the decimal
point is specified in the d parameter
Char(size) A fixed-length string from 1 to 255 characters in length right-padded
with spaces to the specified length when stored (default is 1).
String /text Varchar(size) A variable-length string from 1 to 255 characters in length; for example
VARCHAR(25).
Date and Time date It stores date in YYYY-MM-DD format. Like, '2009-07-02'
time It stores time in HH:MM:SS format. Note: The supported range is from
'-838:59:59' to '838:59:59'
Char, varchar, date and time values should be enclosed in single quotes (‘ ’) or double quotes (“ ”). Like, 'Computer'
"Me and u", '2009-07-02', “2014-12-04” etc.

UNSIGNED is an attribute which can be added to many types. You mark the unsigned with the keyword unsigned. So,
when making a table for an example:
CREATE TABLE `example_table` ( `example_col` tinyint(3) unsigned );
If you specify ZEROFILL for a numeric column, MySQL automatically adds the UNSIGNED attribute to the column.
Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by
default, so the SIGNED attribute has no effect.

AUTO_INCREMENT
Mysql allows you to set AUTO_INCREMENT to a column. Doing so will increase the value of that column by 1
automatically, each time a new record is added.

1. Create table student(roll_number int primary key AUTO_INCREMENT, name varchar(25));


2. Insert into student values(null,’sachin’);
3. Select * from student;
4. And check the value of roll_number column will update with value 1 automatically.

3
Easy Notes: Database MySql Nitin Ruhela
Key:
A column or a combination of columns which can be used to identify one or more rows (tuples) in a table is called a key
of the table. In other words, keys refer to the column (or group of columns) which specify how rows of a relation are
distinct from each other.
Primary Key: The group of one or more columns used to uniquely identify each row of a relation is called its Primary
Key.
Candidate Key: A column or a group of columns which can be used as the primary key of a relation is called a candidate
key because it is one of the candidates available to be the primary key of the relation
Alternate Key: A candidate key of a table which is not made its primary key is called its Alternate Key.
Composite Key: in certain tables, a single attribute cannot be used to identify rows uniquely and combination of two or
more attribute is used as primary. Such keys are called Composite Key.

Think of the functioning of a computerised school library.


In a school library, there are books which are issued to the students and the staff. These books are also returned after a
certain period of time. For proper functioning of this system the librarian maintains a database (an organised collection of
data) which contains the relevant data of books, students, and staff. In a relational database, this data may be organised as
a collection of the following tables:

These three related tables collectively form the Library database.


Using the data stored in these tables the librarian can find out any type of relevant information regarding the books at any
time. For example, He/she can find out:
 The list of books in the library which are published by any specific publisher or author.
 The list of books with price in a specified range.
 Admission numbers of the students who have not returned the books issued to them.
 The names of books issued to a particular staff member or student.

4
Easy Notes: Database MySql Nitin Ruhela
For the above tables the primary keys may be set as follows:

In the STUDENTS table LibCardNo can also be the primary key (Why?). It means that there are two columns in the table
STUDENTS that are unique for each row and can be set as the primary key of the table. These two columns are candidate
keys as they are the candidates for primary key. Out of these two candidate keys we have chosen AdmNo as the primary
key. The other candidate key, i.e., LibCardNo, becomes the Alternate Key of the table. Had we chose LibCardNo as the
primary key, AdmNo would have been called the alternate key of the table.

SQL Commands and its Types


A database system requires a query language that enables the user to manipulate the database. Structured query language,
the user has to specify “WHAT” information is required from that database giving simple command. It has reduced the
need for lengthy programming to access data. SQL provides a set of predefined commands that help the user to
manipulate and access data from tables. The SQL commands use the following conventions.

 Every SQL commands starts with the Keywords/Reserve words and clause. Keywords/Reserve words are terms that
have a special meaning and that gives the additional information which are required to execute the command.
 Every SQL statement in MySql ends with a semicolon (;).
 SQL commands are not case sensitive i.e. you can write SQL statements both in upper and lower case.

These SQL commands can be categorized as -


1. DDL (Data Definition Language): This is a category of SQL commands. These SQL commands are used to create,
alter and delete database objects like table, views, index etc. Example: CREATE, ALTER, DROP etc.
2. DML (Data Manipulation Language): these commands are used to insert, delete, update and retrieve the stored
records from the table. Ex. SELECT...., INSERT..., DELETE..., UPDATE.... etc.
3. DCL (Data Control Language): All the commands which are used to control the access to databases and tables fall
under this category. Examples of DCL commands are - GRANT, REVOKE.
4. TCL (Transaction Control Language): these commands are used to control the transaction. Ex. COMMIT,
ROLLBACK, SAVEPOINT etc.

Database handling commands in MySql


1. Creating a database Create database employee;
2. Opening/Accessing a database Use employee;
3. Getting Listings of database and tables Show databases; Show tables;
4. Show the currently open database Select database ();
5. Creating simple tables
Create table <table name>(<column name> <data type> [(size)] [constraints], ……..);
Create table stud (roll integer, name varchar(25), address varchar(30), marks float (3,2) );

stud
roll name address Marks

6. Creating tables from existing table


Syntax:- Create table <table name> as (<select query>);

5
Easy Notes: Database MySql Nitin Ruhela
Create table result (select roll, name, marks from stud);
Create table result as (select * from stud);

7. Creating tables with constraints

MySQL Constraints
Many times it is not possible to keep a manual check on the data that is going into the tables using INSERT or UPDATE
commands. The data entered may be invalid. MySQL provides some rules, called Constraints, which help us, to some
extent, ensure validity of the data. These constraints are:

Domain integrity constraint


Domain or column level constraint being a part of the column definition can be imposed only on the column on which it is
defined. The null and check constraints can be given only at column and not table level.
Entity integrity constraint
Each row(or tuple) in a relation (or table) must be uniquely identified. Hence we have the primary key or unique key that
must have a unique non-null value for each row.
Referential integrity constraint
Referential integrity is a system of rules that a DBMS uses to ensure that relationships between records in related tables
are valid, and that users don’t accidentally delete or change related data. Referential integrity is ensured through Foreign
Key constraint.
Sno. Constraint Purpose
1 PRIMARY KEY Sets a column or a group of columns as the Primary Key of a table. Therefore,
NULLs and Duplicate values in this column are not accepted.
2 NOT NULL Makes sure that NULLs are not accepted in the specified column.
3 FOREIGN KEY Data will be accepted in this column, if same data value exists in a column in
another related table. This other related table name and column name are specified
while creating the foreign key constraint.
4 UNIQUE Makes sure that duplicate values in the specified column are not accepted. But
null value is allowed.
5 CHECK Makes sure that all values in a column satisfy certain criteria
6 DEFAULT The default constraint provides a default value to a column when the INSERT
INTO statement does not provide a specific value.
a. MySql Not Null Constraint

Create table customer


( ID integer NOT NULL,
Name varchar(30) NOT NULL,
Address varchar(30)
);
b. MySql Default Constraint

Create table student


( Roll integer ,
Name varchar(30) ,
Address varchar(30)
Marks integer default 80
);
c. MySql Unique Constraint

Create table student


( Roll integer (3) unique,
Name varchar(30) ,

6
Easy Notes: Database MySql Nitin Ruhela
Address varchar(30)
);
d. MySql Check Constraint

Create table student


( Roll integer (3) Check(Roll>0),
Name varchar(30) ,
Address varchar(30)
);
In case of check constraint whenever you insert the values in table, you will find that your query is executed without
checking the condition specified through check constraint. The reason being MySql ignores check constraint internally.

e. MySql Primary Key Constraint

Create table student


( Roll integer (3) Primary Key,
Name varchar(30) ,
Address varchar(30)
);

The latter way is useful if you want to specify a composite primary key (when multiple fields or columns are used as a
primary key, they are called a composite key)

Create table student


( Roll_no integer (3) not null,
Admin_no integer not null,
Name varchar(30) ,
Address varchar(30)
primary key (Roll_no,Admin_no)
);
Combination of fields Roll_no and Admin_no is the composite key of the table student.

f. MySql Foreign Key Constraint

If we have two tables having structures as given below:

Customer Table Order Table


Column name Constraints Column name Constraints
ID Primary key Order_ID Primary key
Name Order_Date
Address Customer_Sid Foreign Key
Amount

In the above example, the customer_SID column in the Order tableis a foreign key pointing to the SID column in the
Customer Table.
Create table Customer Create table Order
( ID integer (3) Primary Key, ( Order_ID integer (3) Primary Key,
Name varchar(30) , Order_Date date ,
Address varchar(30) Customer_SID integer (3)
); Amount integer
Foreign key (Customer_SID) references Customer(SID)
);

8. Viewing table structure :-To show the details of a particular table which is given by you at the time of table
creation, the following command is used Describe employee;

7
Easy Notes: Database MySql Nitin Ruhela
9. Inserting Data into table :-You can insert record in the table by using the following DML command
Syntax :- Insert into <table name> [<column list>] values <list of values>

Suppose a table named student has been created with the following structure.

Field name Data type Constraint


Admin_No Integer Primary key
Roll_No Integer Unique key
Name Varchar(30) Not null
Address Varchar(30)
Marks Integer Default 50

We can insert records as follow-

Insert into student values(1,1,’ankit’,’kaka nagar shamli’,75);


Insert into student values(2,2,’ankit’,null,89);
Insert into student (Admin_No,Roll_No,Name) values(3,3,’ankit’);

10. Inserting records from other table:- You can insert all or selected record(s) in the table from another table
by using select command in place of values. Suppose a table named new_student has been created and records to
be inserted from student table having the same structure of column.

Insert into new_student values (select * from student);


Insert into new_student values (select * from student where address=’shamli’);
Insert into new_student (Admin_No,Roll_No,name) values (select Admin_No,Roll_No,name from student where
marks>90);
11. Deleting data from tables you can delete all or selected record(s) from the table by using the following DML
command.

Delete from <table name> [where <condition>]


Delete from student; (this command will delete all records)
Delete from student where marks <50;
Delete from student where address=’kaka nagar shamli’;
After deletion if you want to recall or undelete the deleted records, you can give the rollback command
Rollback;
Or
After deletion if you want to makes the changes permanently, you can give the commit command
Commit:

12. Dropping tables or databases

The drop database command of MySql lets you drop a database.


Drop database mydatabase;
The drop table command of MySql lets you drop a table from the database.
Drop table student;
The If Exists clause of drop table first check whether the given table exists in the database or not. If it does, then it drop
the mentioned table from the database.
Drop table if exists student;

13. Modifying table structure (using alter command):- The alter table command is used to change definition
or structure of existing tables. Usually, In general, MySql alter command is used

8
Easy Notes: Database MySql Nitin Ruhela
 To add a column:- for instance to add a new column contact of type integer in table student. For this you can use
add clause of alter table, you may give:
Alter table student add (contact integer (10));
 To delete a column:- drop column is used to remove a column from a given table this also removes all data from
the column
Alter table student drop column marks;
 To redefine a column (data type, size, default values):-To modify column name of table student to have new
width of 30 characters. For this you can use modify clause of alter table, you may give:
Alter table student modify (name varchar (25));
 To Change the column name:- Some time you may need to change the name of one of your column. For this you
can use change clause of alter table command
Alter table student change name first_name carchar(25);
 To add an integrity constraint:-
Alter table student add constraint A_no Primary Key (Amin_Nno);
 Remove a integrity constraint:-
Alter table student add primary key(roll_number);

14. Modifying table data (using Update command)


This command is used to change the value in the table. The UPDATE command is used to update rows and we
can also use WHERE clause with UPDATE command.
Update table name set column name =value [where column=value]
Update student set marks=100 where roll_number=5

15. Select clause


Sometimes it is convenient to display the contents of all the columns of a table. This can be particularly useful
when you first encounter a new database and want to get a quick understanding of its structure and the data it
contains.
Select * from student

16. Selecting specified columns


If you do not want to see entire rows of your table, just name the columns in which you are interested, separated
by commas.
Select name, class, marks from student
17. Where clause
The where clause specifies the search condition used to determine the data that will appear in the result table. That
is, the where clause is used to specify the rows you want to retrieve.
Select * from student where marks=78;
Or
Select name, roll_number from student where marks=100;
18. Relational operator
The mathematical operators which are used to perform certain type of compression between two variables are
called relational operators. =, >, <, >=, <=, are examples of relational operators.
Select * from student where marks<40;
19. Boolean/ logical operator
Boolean operators are the ones which are either true or false. They are used to combine one or more conditions.
AND, OR and NOT are examples of Boolean operators.
Select * from student where marks>50 AND marks<100;

You might also like