Topic
About MySQL.
Introduction to MySQL.
Explanation
MySQL is the most popular open source SQL database management system
(DBMS), is developed, distributed, and supported by MySQL AB. MySQL AB is a
commercial company, founded by the MySQL developers.
Although under constant development, MySQL Server today offers a rich and useful
set of functions. Its connectivity, speed, and security make MySQL Server highly
suited for accessing databases on the Internet.
Now let's go step by step into MySQL from Installation to Advanced concepts. In the
next page we can see How to install MySQL.
MySQL is the most popular open source Relational database Management system
(RDBMS). Being a open source anyone can use and change the software for their
needs.
Overview of Database
Topic
What is Database?
Overview of Relational Database
Explanation
Database :
A database is a collection of data that is organized so that its contents can be easily
accessed, managed and updated. The software used to manage and query a database
is known as a Database Management System (DBMS). Then came the concept of
Relational Database Management System(RDBMS). Relational database is a
database where data are stored in more than one table, each one containing different
types of data. The different tables can be linked so that information from the separate
files can be used together. This is explained below using an example.
Example :
Consider the Student's personal information and the test marks in a school.
Suppose the student's infomation and test results are stored seperately, we can get
information regarding the student's personal information like Address from the first
file. And also a student's mark at a test can be obtained from the other file.
But consider a situation where we want to get the Address of a student as well as
his marks. These things become hard when we have a large volume of data. If we
have a studentID stored in two files then we can easily relate the details and recollect
them.
MySQL
MySQL is one of the popular Relational Database Management System. Now let us
see an example for a simple database which consists of a table. Consider the same
example we took earlier, a student database. The table may have different fields such
as StudID, Name, Marks, Address, Phone. These five fields constitutes a table named
as student.StudID, Name are fileds and the particular row is a record.
Now we slightly move to MySQL and see how to create database, use database and
remove database
Topic
Explanation
The following will not be needed if you have installed MySQL as a service.
Let’s see how to start MySQL from the windows command line manually.
To start the mysqld from the command line, first you should open a console
window i.e., Start -> Run.., type cmd or command to open the console window. After
opening the console window, enter the path where your MySQL is installed. For
example:
The version depends upon the mysql server you have installed. The path may also
vary depending on the MySQL installation on your system.
You can stop the MySQL server using the below command:
The above commands will help you to start and stop the MySQL server.
Explanation
Command Prompt
MySQL Command Line Client
External MySQL Tools
Command Prompt :
You can connect MySQL from your Console window i.e., Start -> Run.., type cmd or
command to open the Command prompt window.
After opening the console window, enter the path where your MySQL is installed. For
example:
After giving the path, enter the below command to connect to MySQL server:
The path may vary depending on the MySQL installation on your system. Instead of
root you can also connect by giving your username.
You can also get connected to MySQL, using external tool like MySQL Query
Browser.
Topic
Explanation
Before going to create a database check whether there is any database with the
name you are going to create. Check this by the following SHOW statement:
Once you have confirmed that you don't have a database with the name you
intended to create, then you can create your own database by,
Please note that only in Unix the database name is case sensitive. The above query
will create an empty database and it wouldn't contain any tables.
Topic
Explanation
If you want to create tables for a database first you have to select the database. For
selecting a database you have to enter the following query :
mysql> USE sample;
Database changed
Here sample is the database you want to select. The USE command doesn't need
a semicolon at the end of the query.
You can use the following command to view the current database that you're
connected to:
Note : You have to select the database using the USE command everytime you are
entering into Mysql server or when you want to change the database.
If you type the following query you can see an information like Empty set (ie.,)
there are no tables in the selected database.
Topic
DROP Statement.
How to remove/ delete a database in MySQL?
Explanation
This query will delete the database sample. The query will permanently
remove the database.
DROP DATABASE drops all tables in the database and deletes the database.
Once the DROP command is used, then we cannot use that database. So, we
should be careful with this command.
Topic
Explanation
Data types :
Definition : Data type is the characteristic of columns and variables that defines what
types of data values they can store. The characteristic indicating whether a data item
represents a number, date, character string, etc.
Data types are used to indicate the type of the field we are creating into the table.
MySQL supports a number of datatypes in three important categories:
Numeric types
Date and Time types
String(Character) types
For example, if the number of students in a school are in hundreds set the column
as an unsigned three-digit SMALLINT(allowing for up to 999 values).
We should be concise in inserting a string of five characters long into a char(3) field,
the final two characters will be truncated. It is better to set the maximum length for
text and number columns as well as other attributes such as UNSIGNED.
Square brackets ('[' and ']') indicate optional parts of type definitions.
Topic
Explanation
BIT :
TINYINT[(M)] :
A very small integer. The signed range is -128 to 127. The unsigned range is 0 to
255.
BOOL, BOOLEAN :
These types are synonyms for TINYINT(1). A value of zero is considered false.
Non-zero values are considered true.
SMALLINT :
A small integer. The signed range is -32768 to 32767. The unsigned range is 0 to
65535.
MEDIUMINT :
INT :
INTEGER :
BIGINT :
FLOAT :
DOUBLE :
DECIMAL :
Topic
What are the String/Text data types?
Explanation
It is a fixed length string and is mainly used when the data is not going to vary
much in it's length. It ranges from 0 to 255 characters long. While storing CHAR
values they are right padded with spaces to the specified length. When retrieving the
CHAR values, trailing spaces are removed.
VARCHAR() :
It is a variable length string and is mainly used when the data may vary in length.
It ranges from 0 to 255 characters long. VARCHAR values are not padded when they
are stored.
TINYTEXT, TINYBLOB :
TEXT :
BLOB :
BLOB stands for Binary Large OBject. It can hold a variable amount of data. BLOB
columns are treated as byte strings(binary strings). It contains a maximum length of
65535 characters.
MEDIUMTEXT, MEDIUMBLOB :
LONGTEXT, LONGBLOB :
BINARY :
The BINARY is similar to the CHAR type. It stores the value as binary byte strings
instead of non-binary character strings.
VARBINARY :
The VARBINARY is similar to the VARCHAR type. It stores the value as binary
byte strings instead of non-binary character strings.
ENUM() :
An enumeration. Each column may have one of a specified possible values. It can
store only one of the values that are declared in the specified list contained in the ( )
brackets. The ENUM list ranges up to 65535 values.
SET() :
A set. Each column may have more than one of the specified possible values. It
contains up to 64 list items and can store more than one choice. SET values are
represented internally as integers.
If CHAR and VARCHAR options are used in the same table, then MySQL will
automatically change the CHAR into VARCHAR for compatability reasons. The ( )
bracket allows to enter a maximum number of characters that will be used in the
column.
Topic
Explanation
Creating tables :
Once you have selected the database, we can start creating tables. The CREATE
statement is used to create a table in MySQL with constraint. A Constraint is restriction
to the behavior of a variable.
If NULL is specified, the field is allowed to be left empty. If NOT NULL is specified,
the field must be given a value. In the absence of either a NULL or NOT NULL, NULL
is assumed.
The above query will create the table student with fields ID and Name.
PRIMARY KEY :
A PRIMARY KEY is a field in a table that uniquely identifies a record. This attribute
is used to define the field name to create a primary key.
Example :
The PRIMARY KEY is specified after defining the fields in the below example:
We can also create a compound primary key. A compound primary key is where
more than one field is used to uniquely identify a record.
Let’s create a table for holding student details in a class.
Topic
Explanation
Desc table :
Listing Tables :
We can list all the tables in the database using SHOW TABLES query. The following
query will list the tables in the current database.
mysql> show tables;
+--------------------+
| Tables_in_sample |
+--------------------+
| student |
+--------------------+
1 row in set (0.00 sec)
Topic
Explanation
Deleting tables :
The DROP statement is used to delete one or more tables completely from a
database.
The syntax is
DROP TABLE tbl_name
The following example deletes the student table.
DROP TABLE query drops all fields in the table and deletes the table. Once the
DROP TABLE statement is used, we cannot use that table. So, we should be careful
with this statement.
Topic
Explanation
Renaming tables:
Now we can view the table whether the name is changed by the following query.
We can also swap two table names. Let us assume tmp table which does not exists.
Example :
RENAME TABLE emp1 TO tmp,
emp2 TO emp1,
tmp TO emp2;
We can also use RENAME TABLE to move a table from one database to another.
Example :
Topic
Explanation
ALTER TABLE:
ALTER TABLE is used to change the structure of an existing table. We can add or
delete columns, change the type of existing columns, or rename columns or the table
itself. We can also change the comment for the table and type of the table.
The Syntax is
Renaming a Table:
We can also RENAME the table using ALTER TABLE. The following example query
renames the table student to class.
The ADD COLUMN modifier is used to add a column to a table. The following
example query adds a field called marks to the student table.
Topic
Altering Mysql Database tables
How to insert a new database field column at the beginning?
How to insert a new database field column next to the specified field?
Explanation
We can position the field using FIRST and AFTER modifiers. The following example
query will place the new field as the first field in the table.
We can also place the new field next to any of the field. The following example
query will place the new field immediately after the field name.
mysql> ALTER TABLE student ADD COLUMN marks INT(10) AFTER names;
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
Topic
Explanation
Delete a column:
When we modify a column, we have to specify the attribute of the column again.
The following example renames the name field to stud_name in the student table.
mysql> ALTER TABLE student CHANGE name stud_name VARCHAR(20);
Query OK, 0 rows affected (0.05 sec)
Records: 0 Duplicates: 0 Warnings: 0
If we want to change the attribute alone, we can use the same column as in the
following example.
Topic
Explanation
Modify a column type:
The modify statement is also used to change the column type in a table, as the
previous example. The below query will modify the column type.
Topic
Explanation
INSERT STATEMENT:
INSERT query is used for inserting new rows or data into an existing table.
The Insert syntax is
The following example query will add the values like studid, name, marks, address
and Phone number into the table student.
mysql> insert into student values(1, "steve", 100, "5th cross street", 2456987);
Query OK, 1 row affected (0.01 sec)
INSERT...SET STATEMENT :
The INSERT...SET is also used to insert values the using the column name.
The syntax is
Lets take the same values inserting into the table student.
Explanation
INSERT STATEMENT FOR MULTIPLE ROWS:
We can insert multiple rows into a table using a single INSERT statement.
The Syntax is
Example :
The above query will insert the three students details into the table student. This
query will be useful while inserting large amount data into a specific table.
Topic
Explanation
Auto Increment:
The auto increment attribute is used to generate a unique identity for the inserting
rows. Let’s see an example using auto increment.
Now if we select the table, the field name id will be automatically incremented as
shown below.
mysql> select * from stud;
+----+---------+
| id | name |
+----+---------+
| 1 | anne |
| 2 | michael |
| 3 | james |
| 4 | rajesh |
| 5 | harry |
+----+---------+
5 rows in set (0.00 sec)
Topic
How to count the number of rows using select query in the database table?
Explanation
Counting Rows:
The syntax is
Example :
mysql> select count(*) from student;
+----------+
| count(*) |
+----------+
| 5 |
+----------+
1 row in set (0.00 sec)
The above query will list the number of rows in the student table.
Topic
Explanation
After inserting datas into the table, we probably want to check the datas are stored
correctly. To do so, we use the SELECT query.
To view all the data from the table, we use the below query.
The above example query will list the complete details of the student table. Here *
will select all the columns from the table.
Topic
Explanation
LIMIT:
The LIMIT clause can be used to constrain the number of rows returned by the
SELECT statement. It takes one or two numeric arguments, which must both be non-
negative integer constants.
We can also return the values from the beginning of the result set by specifying the
number of rows in a single argument as follows.
Topic
We can select a particular column to display, regretting the entire rows. Suppose
you want to see the name of the students alone we can use the below query.
Topic
Explanation
In the preceding examples, the query for selected rows are displayed in no
particular order. We can also select the rows to display in an ordered format using
ORDER BY Clause.
The following example query will sort the rows in an ascending order based on the
marks.
mysql> select name, marks from student order by marks;
+---------+-------+
| name | marks |
+---------+-------+
| michael | 75 |
| steve | 75 |
| anne | 80 |
| jack | 82 |
| david | 98 |
| mille | 98 |
| steve | 100 |
| anne | 100 |
+---------+-------+
8 rows in set (0.03 sec)
We can also sort the orders in descending order. In the below example query the
marks are sorted in descending order.
Topic
Explanation
We can also sort multiple columns in different directions as given in the below
query.
So if there are same names, the highest mark will be taken as the first priority. In
the above example query, there are 2 anne, so the anne with highest mark will be
displayed first.
Topic
Sometimes we may need to look for the table with a certain matching character. In
MySQL we use LIKE or NOT LIKE operator for comparison. In MySQL the patterns are
case-insensitive by default.
Let us consider an example query to display the student names starting with the
letter M.
The following example query will list the names that ends with letter e.
Topic
Query using "Group by" query
How to select the columns using Groupby clause?
Explanation
Group By:
The Group by clause is used to display the rows and columns grouped by selective
columns. It can be used to perform the aggregate functions, such as count().
The following example query will list the name of the student and also count the
repeative names using Group By clause in the select statement.
Topic
Explanation
UPDATE Statement:
The UPDATE query is used to change or modify the existing values in a table.
Suppose if we want to set the address of a single student to a new address then we
can choose the below option.
Topic
Explanation
DELETE Statement:
The syntax is
We can also delete all the values in the table as the following query.
Topic
Operators in MySQL.
Operator Precedence in MySQL.
Explanation
Operator Precedence:
Operators are used to operate with two operands. Wide collection of Operators are
available in MySQL. The operator precedences are shown below in the table.
Highest Precedence :=
1 ||, OR, XOR
2 &&, AND
3 BETWEEN, CASE, WHEN, THEN, ELSE
4 =, <=>, >=, >, <=, <, <>, !=, IS, LIKE, REGEXP, IN
5 |
6 &
7 <<, >>
8 -, +
9 *, /, DIV, %, MOD
10 ^
11 - (unary minus), ~ (unary bit inversion)
12 !, NOT
Lowest BINARY, COLLATE
If a statement contains paranthesis, then the operations inside the paranthesis are
performed first. These operators will be explained in the following sections.
Topic
Explanation
Type Conversion:
Type conversion takes place when operators are used with different types of
operands in an expression. Some conversions are done implicitly and some need
explicit conversions.
In MySQL the numbers are converted to strings and sometimes strings to numbers
depending upon the condition.
Topic
Explanation
Logical Operator :
AND(&&) Operator
OR(||) Operator
NOT(!) Operator
AND(&&) Operator :
The logical AND(&&) operator indicates whether the both operands are true. Lets
see a statement using AND operator.
OR(||) Operator :
The logical OR(||) operator indicates whether either operand is true. Lets see a
statement using OR operator.
NOT(!) Operator :
The logical NOT(!) operator have only one operand and it returns the inverse of the
value.
Comparison Operators
Topic
Explanation
Comparison Operator :
=:
Equal.
mysql> select 1 = 0;
--> 0
Less than.
mysql> select 4.5 < 5;
--> 1
Greater than.
mysql> select 7 > 2;
--> 1
Not equal.
mysql> select 8 <> 8;
--> 0
If expr is greater than or equal to min and expr is less than or equal to max,
BETWEEN returns 1, otherwise it returns 0.
mysql> select 5 between 5 and 6;
--> 1
GREATEST(value1,value2,...) :
This operator returns the largest argument, compared with two or more arguments.
mysql> select greatest('N', 'M', 'O');
--> O
Topic
Explanation
Numeric Functions :
Numeric function consists of two main sections. They are :
Arithmetic Operations
Mathematical Functions
Arithmetic Operations :
In MySQL, we have the usual Arithmetic operations. Lets see the arithmetic
operators one by one with an example.
Addition (+) :
mysql> select 5+5;
--> 10
Subtraction (-) :
mysql> select 25-18;
--> 7
Multiplication (*) :
mysql> select 4*4;
--> 16
Division (/) :
mysql> select 5/3;
--> 1.67
Next lets move to the Mathematical functions.
Topic
Explanation
Mathematical Functions :
ABS(X) :
Returns the smallest integer nearest to the given value but not less than that.
mysql> select ceil(1.14);
--> 2
Topic
Explanation
String Function :
Functions are predefined set of instructions that returns a value. Functions which
involves strings are called as String functions. There are different types of functions
availble in MySQL.
CHAR_LENGTH(str) or CHARACTER_LENGTH(str) :
It stands for Concatenate With Separator and is a special form of CONCAT function.
Returns the concatenated string of the given arguments seperated by given seperator.
mysql> SELECT CONCAT_WS('!','One','Two','Three');
--> 'One!Two!Three'
( Here '!' is the seperator)
FORMAT() :
Formats the given no and rounds to the given digits after decimal point.
mysql> SELECT FORMAT(12332.123456, 4);
--> '12,332.1235'
LCASE(str) or LOWER() :
Like wise UPPER or UCASE returns the uppercase of the given string.
LENGTH(str) :
Returns the length of the given string in bytes. If there is a 2 byte character the
length is calculated as 2. Whereas the CHAR_LENGTH calculates only the character
length.
mysql> select length('HIOXINDIA');
--> 9
LOCATE(substr,str) or POSITION(substr IN Str) :
Returns the position of the first occurance of the substring in the string.
mysql> select locate('ind','hioxindia');
--> 5
In the given string 'str' the 'from_str' is replaced by the 'to_str' string.
mysql> select replace('MyMYSql','My','you');
--> youMYSql
The given 'from_str' is case sensitive. Here in the above example the first 'My' is
changed but not the second('MY').
REVERSE(str) :
The function returns a substring from the string 'str' starting at position 'pos'.
mysql> select substring('EASYCALCULATION', 5);
--> 'CALCULATION'
Date and Time Functions in MySQL
Topic
Explanation
This function is used to manipulate the display format of a date and time. Lets see some
basic functions for date and time.
CURDATE() :
This date function returns the current date in the format 'YYYY-MM-DD' or 'YYYYMMDD'.
DAYNAME(date) :
Returns the date for the day of the month in the range of 1 to 31. DAY() is a synonym
for DAYOFMONTH().
mysql> select dayofmonth('2007-01-04');
--> 4
DAYOFWEEK(date) :
Returns the day of the week in the numeric format as 1 for Sunday to 7 for Saturday.
mysql> select dayofweek('2007-01-04');
--> 5
DAYOFYEAR(date) :
Returns the day of the year for given date in the numeric format, in the range 1 to 366.
mysql> select dayofyear('2007-07-09');
--> 190
HOUR(time) :
Returns the hour of the specified time in the numeric format from 0 to 23.
mysql> select hour('14:46:12');
--> 14
MINUTE(time) :
Returns the minute of the specified time in the numeric format from 0 to 59.
mysql> select minute('14:46:12');
--> 46
MONTH(date) :
Returns the month for the given date in the numeric format, in the range 0 to 12.
mysql> select month('2007-07-09');
--> 7
MONTHNAME(date) :
This date time function returns the current date and time in the format 'YYYY-MM-DD
HH:MM:SS' or YYYYMMDDHHMMSS.
mysql> select now();
--> 2007-01-04 14:56:15