Professional Documents
Culture Documents
MySQL For Beginners - Ganesh Bagaria PDF
MySQL For Beginners - Ganesh Bagaria PDF
for Beginners
(1 st Edition)
By Ganesh Bagaria
About the Author
Ganesh Bagaria was born on December 15, 1997 in Nawalgarh City,
Rajasthan, India. He is a student, authon,owner of
http://worldfreeapps.com website. This is his first book.
Ganesh has made website http://worldfreeapps.com for downloading apps
and games for Android, Iphone, Windows Phone, for downloading Songs
and for Playing Online Games for free.
You can connect to Ganesh Bagaria via Twitter at
https://twitter.com/@ganeshbagaria , via LinkedIn
https://in.linkedin.com/in/ganeshbagaria.
This is Ganesh Bagaria’s first book so sorry for any mistakes.
Contents
▬▬▬▬▬▬▬▬▬▬▬▬▬▬
Introduction ……………………………………………………
1
Part 1: Creating Databases, Tables ……………… 3
Create Database
Create Table
Set Primary Key in Table Creation
Set Foreign Key in Table Creation
Set default value in create table
Part 2: Accessing Databases ………………………… 7
Use Database
Part 3: Inserting data into Table ……………… 8
Insert data into Table
Insert Null Values
Part 4: Altering Table …………………………… 10
Add Column, Primary Key
Delete Column, Primary Key, Row, Table, Database
Modify Table
Part 5: Select Queries ……………………………… 14
Format of Select Query
Select Queries
Part 6: MySQL Functions ………………………… 20
String Functions
Numeric Functions
Part 7: MySQL Join ……………………………… 26
MySQL Join
Different MySQL Joins
Part 8: MySQL Create Index ………………… 29
Create Index
Create Unique Index
Delete Index
Part 9: MySQL Auto Increment a field … 31
Add Auto Increment in a field in Table
Part 10: MySQL View ……………………………… 32
Create View
Replace View
Drop View
Part 11: MySQL Reference ……………………… 34
Part 12: About MySQL ………………………… 38
Introduction
MySQL is (as of July 2013) the world’s second most[a] widely used
relational database management system (RDBMS) and most widely used
open-source RDBMS. It is named after co-founder Michael Widenius’s
daughter, My. The SQL acronym stands for Structured Query Language.
The MySQL development project has made its source code available under the
terms of the GNU General Public License, as well as under a variety of
proprietary agreements. MySQL was owned and sponsored by a single for-
profit firm, the Swedish company MySQL AB, now owned by Oracle
Corporation. For proprietary use, several paid editions are available, and offer
additional functionality.
MySQL is a popular choice of database for use in web applications, and is a
central component of the widely used LAMP open source web application
software stack (and other ‘AMP’ stacks). LAMP is an acronym for “Linux,
Apache, MySQL, Perl/PHP/Python.” Free-software-open source projects that
require a full-featured database management system often use MySQL.
Applications which use MySQL databases include: TYPO3, MODx, Joomla,
WordPress, phpBB, MyBB, Drupal and other software. MySQL is also used
in many high-profile, large-scale
2
websites, including Google (though not for searches), Facebook, Twitter,
Flickr, and YouTube.
MySQL ships with no GUI tools to administer MySQL databases or manage
data contained within the databases. Users may use the included command line
tools, or use MySQL “front-ends”, desktop software and web applications that
create and manage MySQL databases, build database structures, back up data,
inspect status, and work with data records. The official set of MySQL front-
end tools, MySQL Workbench is actively developed by Oracle, and is freely
available for use.
MySQL works on many system platforms, including AIX, BSDi, FreeBSD,
HP-UX, eComStation, i5/OS, IRIX, Linux, OS X, Microsoft Windows,
NetBSD, Novell NetWare, OpenBSD, OpenSolaris, OS/2 Warp, QNX, Oracle
Solaris, Symbian, SunOS, SCO OpenServer, SCO UnixWare, Sanos and
Tru64. A port of MySQL to OpenVMS also exists.
3
Part: 1
Creating Databases, Tables
________________________________________________________
In this Part
Create Database
Create Table
Set Primary Key in Table Creation
Set Foreign Key in Table Creation
Set default value in create table
; (Semicolon) is a necessary symbol at end of all MySQL Structure.
Create Database:
Create a database in MySQL
The CREATE DATABASE statement is used to create a database.
Syntax: - Create database <database name>;
Example: - Create database mywebsite;
Create table:
4
Create tables in MySQL
The CREATE TABLE statement is used to create a table in a database.
Tables are organized into rows and columns; and each table must have a name.
1. Create table query
Syntax: - Create table <table name> (<column name><datatype>(size),<column
name><datatype>(size),………)
The column name parameters specify the names of the columns of the table.
The data type parameter specifies what type of data the column can hold (e.g.
varchar, integer, decimal, date, etc.).
The size parameter specifies the maximum length of the column of the table.
Example: - Create table worldfreeapps (Sr integer(5),Appstore char(20),Song
char(20),Game char(30));
2. Set not null value on default position in table create
The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. This means
that you cannot insert a new record, or update a record without adding a value to
this field.
5
Example: - Create table worldfreeapps (Sr integer(5)not null,Appstore char(20)not
null,Song char(20));
3. Set default value in Create table
The DEFAULT constraint is used to insert a default value into a column.
The default value will be added to all new records, if no other value is specified.
Example: - Create table worldfreeapps (Sr integer(5)default,Appstore
char(20),Song char(20));
4. Check default condition in table create
The CHECK constraint is used to limit the value range that can be placed in a
column.
If you define a CHECK constraint on a single column it allows only certain values
for this column.
If you define a CHECK constraint on a table it can limit the values in certain
columns based on values in other columns in the row.
Example: - Create table worldfreeapps (Sr integer (5)check(Sr>2),Appstore
char(20),Song char(20));
5. Set Primary Key in table creation
The PRIMARY KEY constraint uniquely identifies each record in a database
table.
6
Primary keys must contain UNIQUE values.
A primary key column cannot contain NULL values.
Most tables should have a primary key, and each table can have only ONE primary
key.
Example: - Create table worldfreeapps (Sr integer(5)primary key,Appstore
char(20),Song char(20));
Or
Example: - Create table worldfreeapps (Sr integer(5),Appstore char(20),Song char
(20), primary key (Sr));
6. Set Foreign Key in table creation
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
Example: - Create table worldfreeapps (Sr integer(5),Appstore char(20),Song
char(20),Game char(20), foreign key (Sr) references world(Sr));
7
Part: 2
Accessing Databases
____________________________________________________
In this Part
Use Database
Use Database:
With USE DATABASE Statement you can access any of databases in MySQL
Syntax: - Use <database name>;
Example: - use mywebsite;
8
Part: 3
Inserting Data into Table
____________________________________________________
In this Part
Insert Data into Table
Insert Null Values
Inserting Data into Table:
The INSERT INTO statement is used to insert new records in a
table.
1. Insert Data into Table
Syntax: - Insert into <table name> values(<value>,<value>,……);
Example: - insert into worldfreeapps values (1,’Android’,’Music’);
Or
Syntax: - Insert into <table name> (<column 1>,<column 2>,….) values
(<value 1>,<value 2>,…..);
Example: - insert into worldfreeapps (Sr,Appstore,Song) values
(1,’Android’,’Music’);
9
2. Insert Null Values
Syntax: - Insert into <table name> (<column 1>,<column 2>,….) values
(<value 1>,<value 2>,…..);
Example: - insert into worldfreeapps (Sr,Appstore,Song) values
(1,’Android’,NULL);
10
Part: 4
Altering Table
__________________________________________________
In this Part
Add Column, Primary Key
Delete Column, Primary Key, Row, Table, Database
Modify Table
The ALTER TABLE statement is used to add, delete, or modify
columns in an existing table.
Add Column, Primary Key:
1. Add new Column
Syntax: - alter table <table name> add (<column name> <data type>
(<size>));
Example: - alter table worldfreeapps add (About char(30));
2. Add Primary Key
11
Syntax: - alter table <table name> add primary key (<column name>);
Example: - alter table worldfreeapps add primary key (Sr);
Delete Column, Primary Key, Row, Table,
Database:
1. Delete Column
Syntax: - alter table <table name> drop <column name>;
Example: - alter table worldfreeapps drop About;
2. Delete Primary Key
Syntax: - alter table <table name> drop primary key;
Example: - alter table worldfreeapps drop primary key;
3. Delete Row
Syntax: - delete from <table name> where <column name equals
value>;
Example: - delete from worldfreeapps where Sr = 2;
4. Delete Table
The DROP TABLE statement is used to delete a table.
12
Syntax: - drop table <table name>;
Example: - drop table worldfreeapps;
5. Delete Database
The DROP DATABASE statement is used to delete a database.
Syntax: - drop database <database name>;
Example: - drop database mywebsite;
Modify Table:
1. Change Column Name, Data Type
Syntax: - alter table <table name> change <column name> <changed
column name> <data type(<size>)>;
Example: - alter table worldfreeapps change Song Music char(30);
2. Update Table Data
Syntax: - update <table name> set <column name equal changed
data>;
Example: - update worldfreeapps set AppStore = “IOS” where Sr=2;
13
3. Show Table in database
Syntax: - show tables;
Example: - show tables;
4. Structure of Table
Syntax: - desc <table name>;
Example: - desc worldfreeapps;
14
Part: 5
Select Queries
____________________________________________
In this Part
Format of Select Query
Select Queries
SELECT QUERY is used for displaying your table in that
manner in which you want.
Format of Select Query:
Select Query Format
Syntax: - Select <what to select> from <which table> where
<condition to satisfy>;
Select Queries:
1. Selecting all data from a table
Syntax: - select * from <table name>;
Example: - select * from worldfreeapps;
2. Select all data where Appstore = Android
15
Syntax: - select * from <table name> where <condition to
satisfy>;
Example: - select * from worldfreeapps where Appstore =
“Android”;
3. Select all Data where Sr >= 2
Syntax: - select * from <table name> where <condition to
satisfy>;
Example: - select * from worldfreeapps where Sr >= 2;
4. Select all Data using “and” condition where both
condition are compulsory
Syntax: - select * from <table name> where <condition to
satisfy>;
Example: - select * from worldfreeapps where Sr=2 and
Appstore=’Windows’;
5. Select all data using “or” condition where any condition
are match from both condition
Syntax: - select * from <table name> where <condition to
satisfy>;
Example: - select * from worldfreeapps where Sr=2 or
Appstore=’Windows’;
16
6. Selecting Particular Column
Syntax: - select <which column to be displayed> from <table
name>;
Example: - select Sr,Appstore from worldfreeapps;
7. Remove Duplicate Data for Showing from Table
Syntax: - select distinct (<column name>) from <table name>;
Example: - select distinct (Appstore) from worldfreeapps;
8. Select all Data from Particular Table
Syntax: - select all <column name> from <table name>;
Example: - select all Appstore from worldfreeapps;
9. Using Column Aliases
Syntax: - select <column name> as <“Column Aliases Name”>
from <table name>;
Example: - select Sr,Appstore as “Two Column” from
worldfreeapps;
10. Condition Based on a Range
17
Syntax: - select <column which to be display> from <table
name> where <condition to satisfy>;
Example: - select Sr,Appstore from worldfreeapps where Sr
between 2 and 5;
11. Condition Based on a List
Syntax: - select <column which to be display> from <table
name> where <condition to satisfy>;
Example: - select * from worldfreeapps where Appstore
in(‘appstore’,’appstore2’,’appstore3’);
12. Condition Based on Pattern Matches
Name like Starting from a
Syntax: - select * from <table name> where <column
name> like ‘<letter>%’;
Example: - select * from worldfreeapps where Appstore
like ‘a%’;
Name like Ending from t
Syntax: - select * from <table name> where <column
name> like ‘%<letter>’;
Example: - select * from worldfreeapps where Appstore
like ‘%t’;
18
Word Anywhere in Appstore
Syntax: - select * from <table name> where <column
name> like ‘%a%’;
Example: - select * from worldfreeapps where Appstore
like ‘%a%’;
13. Searching for Null
Syntax: - select * from <table name> where <column name> is
Null
Example: - select * from worldfreeapps where Song is Null;
14. Shorting Records Order by Value
Ascending Order
Syntax: - select * from <table name> order by <column
name>;
Example: - select * from worldfreeapps order by
Appstore;
Descending Order
Syntax: - select * from <table name> order by <column
name> desc;
Example: - select * from worldfreeapps order by
Appstore desc;
19
15. Performing Simple Calculation
Arithmetic Operation
Select 1+5;
Find Current System Date
Select curdate();
20
Part: 6
MySQL Functions
________________________________________________________
In this Part
String functions
Numeric functions
String functions:
1. Return the Character from each integer passed
CHAR() interprets each argument N as an integer and returns a string consisting of
the characters given by the code values of those integers. NULL values are
skipped.
Syntax: - select char (<numeric1>,<numeric2>,<numeric3>,…);
Example: - select char (65,66,67,68);
2. Return Concatenated String
Returns the string that results from concatenating the arguments.
Syntax: - select concat(<column name1>,<column name2>,…) as “<as name you
want to display>” from <table name>;
21
Example: - select concat(Sr,Appstore) as “Sr and Appstore” from worldfreeapps;
3. Change data in Lower Case and Upper Case
Lower Case
Syntax: - select lower(<column name>) from <table name>;
Example: - select lower(Appstore) from worldfreeapps;
Or
Syntax: - select lcase(<column name>) from <table name>;
Example: - select lcase(Appstore) from worldfreeapps;
Upper Case
Syntax: - select upper(<column name>) from <table name>;
Example: - select upper(Appstore) from worldfreeapps;
Or
Syntax: - select ucase(<column name>) from <table name>;
Example: - select ucase(Appstore) from worldfreeapps;
4. Substring data in Column
22
Syntax: - select substr(<Column name>,<letter to be displayed numbering>) from
<table name>;
Example: - select substr(Appstore,1,2) from worldfreeapps;
Or
Syntax: - select substring(<Column name>,<letter to be displayed numbering>)
from <table name>;
Example: - select substring(Appstore,1,2) from worldfreeapps;
Or
Syntax: - select mid(<Column name>,<letter to be displayed numbering>) from
<table name>;
Example: - select mid(Appstore,1,2) from worldfreeapps;
5. Removing Leading Spaces
Syntax: - slect ltrim(<column name>) from <table name>;
Example: - select ltrim(Appstore) from worldfreeapps;
6. Removing Trailing Spaces
Syntax: - slect rtrim(<column name>) from <table name>;
Example: - select rtrim(Appstore) from worldfreeapps;
7. Removing Leading and Trailing Spaces
23
Syntax: - slect trim(<column name>) from <table name>;
Example: - select trim(Appstore) from worldfreeapps;
8. Show the index of the String
Syntax: - select instr(<column name>,<”letter”>) from <table name>;
Example: - select instr(Appstore,”a”) from worldfreeapps;
9. Show the length of the String
Syntax: - select length(<column name>) as “<the name you want to display>” from
<table name>;
Example: - select length(Appstore) as “Operating Systems” from worldfreeapps;
10. Show leftmost number of Character
Syntax: - select left (<column name>,<size>) as <“the name you want to display”>
from <table name>;
Example: - select left (Appstore,3) as “leftmost” from worldfreeapps;
11. Show rightmost number of Character
Syntax: - select right (<column name>,<size>) as <“the name you want to
display”> from <table name>;
24
Example: - select right (Appstore,3) as “rightmost” from worldfreeapps;
Numeric functions:
1. Show the reminder of one expression divided by another expression
Syntax: - select mod(<expression1>,<expression2>);
Example: - select mod(11,4);
2. Show the Power of any Value
Syntax: - select power(value1,value2);
Example: - select power(12,2);
3. Show the numeric expression rounded to an integer
Syntax: - select round(<numeric>);
Example: - select round(35.323,1);
4. Show the numeric expression truncated to an integer
Syntax: - select truncate (<numeric>) as “<the name you want to display>”;
Example: - select truncate (15.79,1) as “truncate”;
5. Show the sign of numeric values
25
Syntax: - select sign(<that you want to select>) as “<the name you want to
display>”;
Example: - select sign(-1) as “sign”;
6. Show the square root of any number
Syntax: - select sqrt(<numeric>) as “<the name you want to display>”;
Example: - select sqrt(36) as “sqrt”;
26
Part: 7
MySQL Join
__________________________________________________
In this Part
MySQL Join
Different MySQL Join
MySQL Join:
1. About MySQL Join
A MySQL Join clause is used to combine rows from two or more tables,
based on a common field between them.
The most common type of Join is: MySQL INNER JOIN (simple join). A
MySQL INNER JOIN return all rows from multiple tables where the join
condition is met.
2. MySQL Join Syntax
Syntax: - select <table name1.its column name>,<table name2.its column
name> from <table name1> inner join <table name2> on <table
name1.same column name>=<table name2.same column name>;
3. MySQL Join Example
Example: -
27
Let’s look at a selection from the “Persons” table:
Sr PersonID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
Then, have a look at a selection from the “Customer” table:
PersonID Name ContactName Country
1 Alfreds Futterkiste Maria Germany
2 Ana Trujillo Ana Mexico
3 Antonio Moreno Antonio Mexico
Then, if we run the following MySQL statement
Select Persons.Sr,Customers.Name,Persons.OrderDate From Persons Inner Join
Customers ON Persons.PersonID=Customers.PersonID;
It will produce something like this:
Sr Name OrderDate
10308 Ana Trujilli 1996-09-18
29
Part: 8
MySQL Create Index
________________________________________________________
In this Part
Create Index
Create Unique Index
Delete Index
The CREATE INDEX statement is used to create indexes in tables.Indexes
allow the database application to find data fast;without reading the whole
table.
Create Index:
1. MySQL Create Index
Syntax: - CREATE INDEX <index name> ON <table name> (<column name>);
Example: - CREATE INDEX PIndex ON Persons (Name);
30
Syntax: - CREATE UNIQUE INDEX <index name> ON <table name> (<column
name>);
Example: - CREATE UNIQUE PIndex ON Persons (Name);
Delete Index:
1. Delete Created Index
Syntax: - alter table <table name> drop index <index name>;
Example: - alter table worldfreeapps drop index Android;
31
Part: 9
MySQL Auto Increment a field
__________________________________________________
In this Part
Add Auto Increment in a field in table
Auto Increment allows a unique number to be generated when a new
record is inserted into a table.
Add Auto Increment in a field in table:
1. MySQL Auto Increment
Syntax: - Create Table <table name> (<column name1><data
type(<size>)>Auto_Increment,<column name2><data type(<size>)>,….);
Example: - Create Table worldfreeapps (Sr int Not Null Auto_Increment,Name
varchar(255),Primary Key(Sr));
To let the AUTO_INCREMENT sequence start with another value,
use the following MySQL statement:
Syntax: - alter table <table name> Auto_Increment=<size>;
Example: - alter table worldfreeapps Auto_Increment=100;
32
Part: 10
MySQL Views
__________________________________________________
In this Part
Create View
Replace View
Drop View
Create View:
1. MySQL Create View
Syntax: - Create view <view name> as select <column name> from <table name>;
Example: - Create view v as select Sr,Appstore from Persons;
Replace View:
1. MySQL Replace View
Syntax: - Create or Replace view <view name> as select <column name> from
<table name>;
Example: - Create view v as select Sr,Appstore,About from Persons;
Drop View:
33
1. MySQL Drop View
Syntax: - Drop view <view name>;
Example: - Drop view v;
34
Part: 11
MySQL Reference
__________________________________________________
MySQL Reference:
SQL Statement Syntax
IN SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)
SELECT * SELECT *
FROM table_name
38
Part: 12
About MySQL
________________________________________________________
MySQL is (as of July 2013) the world’s second most widely used
relational database management system (RDBMS) and most widely
used open-source RDBMS.
The MySQL development project has made its source code available
under the terms of the GNU General Public License, as well as under a
variety of proprietary agreements.
MySQL is a popular choice of database for use in web applications, and
is a central component of the widely used LAMP open source web
application software stack (and other ‘AMP’ stacks).
MySQL is written in C and C++. Its SQL parser is written in yacc, but it
uses a home-brewed lexical analyzer.
39
MySQL works on many system platforms, including AIX, BSDi,
FreeBSD, HP-UX, eComStation, i5/OS, IRIX, Linux, OS X, Microsoft
Windows, NetBSD, Novell NetWare, OpenBSD, OpenSolaris, OS/2
Warp, QNX, Oracle Solaris, Symbian, SunOS, SCO OpenServer, SCO
UnixWare,
Sanos and Tru64. A port of MySQL to OpenVMS also exists.
MySQL can be built and installed manually from source code, but this
can be tedious so it is more commonly installed from a binary package
unless special customizations are required.
Backup software are computer programs used to perform backup; they
create supplementary exact copies of files, databases or entire
computers.
Like other SQL databases, MySQL does not currently comply with the
full SQL standard for some of the implemented functionality, including
foreign key references when using some storage engines other than the
default of InnoDB, and check constraints.
Up until MySQL 5.7, triggers are limited to one per action / timing,
meaning that at most one trigger can be defined to be executed after an
INSERT operation, and one before INSERT on the same table. No
triggers can be defined on views.
40
MySQL database’s inbuilt functions like UNIX_TIMESTAMP() will
return 0 after 03:14:07 UTC on 19 January 2038.
On all platforms except Windows, MySQL ships with no GUI tools to
administer MySQL databases or manage data contained within the
databases. Users may use the included command line tools, or install
MySQL Workbench via a separate download. Many third party GUI
tools are also available.
Adminer (formerly known as phpMinAdmin) is a free MySQL front end
for managing content in MySQL databases (since version 2, it also
works on PostgreSQL, MS SQL, SQLite and Oracle SQL databases).
MySQL Workbench is the official integrated environment for MySQL.
It was developed by MySQL AB, and enables users to graphically
administer MySQL databases and visually design database structures.