Mysql Notes
Mysql Notes
Mysql Notes
MySQL tutorial provides basic and advanced concepts of MySQL. Our MySQL tutorial is
designed for beginners and professionals.
Our MySQL tutorial includes all topics of MySQL database such as insert record, update
record, delete record, select record, create table, drop table etc. There are also given
MySQL interview questions to help you better understand the MySQL database.
What is MySQL
MySQL is a fast, easy to use relational database. It is currently the most popular open-
source database. It is very commonly used in conjunction with PHP scripts to create
powerful and dynamic server-side applications.
MySQL is used for many small and big businesses. It is developed, marketed and
supported by MySQL AB, a Swedish company. It is written in C and C++.
Reasons of popularity
MySQL is becoming so popular because of these following reasons:
MySQL Features
o Relational Database Management System (RDBMS): MySQL is a relational
database management system.
o Easy to use: MySQL is easy to use. You have to get only the basic knowledge of
SQL. You can build and interact with MySQL with only a few simple SQL
statements.
o It is secure: MySQL consist of a solid data security layer that protects sensitive
data from intruders. Passwords are encrypted in MySQL.
o Client/ Server Architecture: MySQL follows a client /server architecture. There
is a database server (MySQL) and arbitrarily many clients (application programs),
which communicate with the server; that is, they query data, save changes, etc.
o Free to download: MySQL is free to use and you can download it from MySQL
official website.
o It is scalable: MySQL can handle almost any amount of data, up to as much as
50 million rows or more. The default file size limit is about 4 GB. However, you
can increase this number to a theoretical limit of 8 TB of data.
o Compatibale on many operating systems: MySQL is compatible to run on
many operating systems, like Novell NetWare, Windows* Linux*, many varieties
of UNIX* (such as Sun* Solaris*, AIX, and DEC* UNIX), OS/2, FreeBSD*, and
others. MySQL also provides a facility that the clients can run on the same
computer as the server or on another computer (communication via a local
network or the Internet).
o Allows roll-back: MySQL allows transactions to be rolled back, commit and
crash recovery.
o High Performance: MySQL is faster, more reliable and cheaper because of its
unique storage engine architecture.
o High Flexibility: MySQL supports a large number of embedded applications
which makes MySQL very flexible.
o High Productivity: MySQL uses Triggers, Stored procedures and views which
allows the developer to give a higher productivity.
o MySQL version less than 5.0 doesn't support ROLE, COMMIT and stored
procedure.
o MySQL does not support a very large database size as efficiently.
o MySQL doesn't handle transactions very efficiently and it is prone to data
corruption.
o MySQL is accused that it doesn't have a good developing and debugging tool
compared to paid databases.
o MySQL doesn't support SQL check constraints.
How to install MySQL
Download MySQL
Follow these steps:
Open your MySQL Command Line Client, it should be appeared with a mysql> prompt. If
you have set any password, write your password here. Now, you are connected to the
MySQL server and you can execute all the SQL command at mysql> prompt as follows:
For example: Check the already created databases with show databases command:
What is Primary key
A primary key is a single field or combination of fields that contains a unique record. It
must be filled. None of the field of primary key can contain a null value. A table can have
only one primary key.
Open the MySQL console and write down password, if you set one while installation. You
will get the following:
Syntax:
Example:
1. SHOW DATABASES;
Output
Syntax:
1. USE database_name;
Example:
1. USE customers;
Note: All the database names, table names and table fields name are case sensitive.
You must have to use proper names while giving any SQL command.
Syntax:
Example:
Now you can check that either your database is removed by executing the following
query:
1. SHOW DATABASES;
Output:
Syntax:
Example:
Note:
1. Here, NOT NULL is a field attribute and it is used because we don't want this field
to be NULL. If you will try to create a record with NULL value, then MySQL will
raise an error.
2. The field attribute AUTO_INCREMENT specifies MySQL to go ahead and add the
next available number to the id field.PRIMARY KEY is used to define a column as
primary key. You can use multiple columns separated by comma to define a
primary key.
1. SHOW tables;
1. DESCRIBE cus_tbl;
MySQL ALTER Table
MySQL ALTER statement is used when you want to change the name of your table or any
table field. It is also used to add or delete an existing column in a table.
The ALTER statement is always used with "ADD", "DROP" and "MODIFY" commands
according to the situation.
Parameters
table_name: It specifies the name of the table that you want to modify.
new_column_name: It specifies the name of the new column that you want to add to
the table.
column_definition: It specifies the data type and definition of the column (NULL or
NOT NULL, etc).
Example:
In this example, we add a new column "cus_age" in the existing table "cus_tbl".
Output:
Output:
2) Add multiple columns in the table
Syntax:
Example:
In this example, we add two new columns "cus_address", and cus_salary in the existing
table "cus_tbl". cus_address is added after cus_surname column and cus_salary is added
after cus_age column.
Syntax:
Let's take an example to drop the column name "cus_address" from the table "cus_tbl".
Output:
Example:
Output:
6) RENAME table
Syntax:
Example:
Output:
See the renamed table:
The TRUNCATE TABLE statement is used when you want to delete the complete data
from a table without removing the table structure.
Syntax:
This example specifies how to truncate a table. In this example, we truncate the table
"cus_tbl".
Output:
Output:
MySQL DROP Table
MYSQL DROP table statement removes the complete data with structure.
Syntax:
Example:
This example specifies how to drop a table. In this example, we are dropping the table
"cus_tbl".
MySQL View
In MySQL, View is a virtual table created by a query by joining one or more tables.
Syntax:
view_name: It specifies the name of the VIEW that you want to create in MySQL.
WHERE conditions: It is also optional. It specifies the conditions that must be met for
the records to be included in the VIEW.
The following example will create a VIEW name "trainer". This is a virtual table made by
taking data from the table "courses".
Syntax:
Example:
The following example will alter the already created VIEW name "trainer" by adding a
new column.
1. SELECT*FROM trainer;
Syntax:
IF EXISTS: It is optional. If you do not specify this clause and the VIEW doesn't exist,
the DROP VIEW statement will return an error.
Example:
MySQL Queries
A list of commonly used MySQL queries to create database, use database, create table,
insert record, update record, delete record, select record, truncate table and drop table
are given below.
More Details...
1. use db1;
More Details...
More Details...
More Details...
More Details...
More Details...
More Details...
More Details...
More Details...
Syntax:
The SQL INSERT INTO command is used to insert data in MySQL table. Following is a
generic syntax:
Field name is optional. If you want to specify partial values, field name is mandatory.
Example:
Or,
Visual Representation:
See the data within the table by using the SELECT command:
Syntax:
Following is a generic syntax of UPDATE command to modify data into the MySQL table:
Example:
Here, we have a table "cus_tbl" within the database "customers". We are going to
update the data within the table "cus_tbl".
This query will update cus_surname field for a record having cus_id as 5.
1. UPDATE cus_tbl
2. SET cus_surname = 'Ambani'
3. WHERE cus_id = 5;
Visual Representation:
Syntax:
Example:
Output:
MySQL SELECT Statement
The MySQL SELECT statement is used to fetch data from the one or more tables in
MySQL. We can retrieve records of all fields or specified fields.
1. SELECT expressions
2. FROM tables
3. [WHERE conditions];
Example:
Let's take two tables "students" and "officers", having the following data.
Execute the following query:
Output:
Syntax:
1. WHERE conditions;
Parameter:
conditions: It specifies the conditions that must be fulfilled for records to be selected.
Table structure:
1. SELECT *
2. FROM officers
3. WHERE address = 'Mau';
Output:
MySQL WHERE Clause with AND condition
In this example, we are retrieving data from the table "officers" with AND condition.
1. SELECT *
2. FROM officers
3. WHERE address = 'Lucknow'
4. AND officer_id < 5;
Output:
WHERE Clause with OR condition
Execute the following query:
1. SELECT *
2. FROM officers
3. WHERE address = 'Lucknow'
4. OR address = 'Mau';
Output:
1. SELECT *
2. FROM officers
3. WHERE (address = 'Mau' AND officer_name = 'Ajeet')
4. OR (officer_id < 5);
Output:
MySQL Distinct Clause
MySQL DISTINCT clause is used to remove duplicate records from the table and fetch
only the unique records. The DISTINCT clause is only used with the SELECT statement.
Syntax:
Parameters
expressions: specify the columns or calculations that you want to retrieve.
tables: specify the name of the tables from where you retrieve records. There must be
at least one table listed in the FROM clause.
WHERE conditions: It is optional. It specifies the conditions that must be met for the
records to be selected.
Note:
o If you put only one expression in the DISTINCT clause, the query will return the
unique values for that expression.
o If you put more than one expression in the DISTINCT clause, the query will
retrieve unique combinations for the expressions listed.
o In MySQL, the DISTINCT clause doesn't ignore NULL values. So if you are using
the DISTINCT clause in your SQL statement, your result set will include NULL as a
distinct value.
MySQL DISTINCT Clause with single
expression
If you use a single expression then the MySQL DISTINCT clause will return a single field
with unique records (no duplicate record).
Syntax:
1. FROM table1
2. [ { INNER JOIN | LEFT [OUTER] JOIN| RIGHT [OUTER] JOIN } table2
3. ON table1.column1 = table2.column1 ]
Parameters
table1 and table2: specify tables used in the MySQL statement. The two tables are
joined based on table1.column1 = table2.column1.
Note:
o If you are using the FROM clause in a MySQL statement then at least one table
must have been selected.
o If you are using two or more tables in the MySQL FROM clause, these tables are
generally joined using INNER or OUTER joins.
1. SELECT *
2. FROM officers
3. WHERE officer_id <= 3;
Syntax:
1. SELECT expressions
2. FROM tables
3. [WHERE conditions]
4. ORDER BY expression [ ASC | DESC ];
Parameters
expressions: It specifies the columns that you want to retrieve.
tables: It specifies the tables, from where you want to retrieve records. There must be
at least one table listed in the FROM clause.
WHERE conditions: It is optional. It specifies conditions that must be fulfilled for the
records to be selected.
ASC: It is optional. It sorts the result set in ascending order by expression (default, if no
modifier is provider).
DESC: It is also optional. It sorts the result set in descending order by expression.
Note: You can use MySQL ORDER BY clause in a SELECT statement, SELECT LIMIT
statement, and DELETE LIMIT statement.
1. SELECT *
2. FROM officers
3. WHERE address = 'Lucknow'
4. ORDER BY officer_name;
Output:
1. SELECT *
2. FROM officers
3. WHERE address = 'Lucknow'
4. ORDER BY officer_name ASC;
Output:
Output:
You can also use some aggregate functions like COUNT, SUM, MIN, MAX, AVG etc. on the
grouped column.
Syntax:
WHERE conditions: It is optional. It specifies the conditions that must be fulfilled for
the records to be selected.
Output:
(ii) MySQL GROUP BY Clause with SUM
function
Let's take a table "employees" table, having the following data.
Now, the following query will GROUP BY the example using the SUM function and return
the emp_name and total working hours of each employee.
Output:
Output:
(iv) MySQL GROUP BY Clause with MAX
function
The following example specifies the maximum working hours of the employees form the
table "employees".
Output:
(v) MySQL GROUP BY Clause with AVG
function
The following example specifies the average working hours of the employees form the table
"employees".
Output:
MySQL HAVING Clause
MySQL HAVING Clause is used with GROUP BY clause. It always returns the rows where
condition is TRUE.
Syntax:
Parameters
aggregate_function: It specifies any one of the aggregate function such as SUM,
COUNT, MIN, MAX, or AVG.
expression1, expression2, ... expression_n: It specifies the expressions that are not
encapsulated within an aggregate function and must be included in the GROUP BY
clause.
HAVING condition: It is used to restrict the groups of returned rows. It shows only
those groups in result set whose conditions are TRUE.
HAVING Clause with SUM function
Consider a table "employees" table having the following data.
Here, we use the SUM function with the HAVING Clause to return the emp_name and
sum of their working hours.