Short Notes 1 - MySQL Commands 1 1650270538687
Short Notes 1 - MySQL Commands 1 1650270538687
NOTES
History of MySQL
MySQL is an open source database product that was created by MySQL AB, a company founded in 1995 in
Sweden. In 2008, MySQL AB announced that it had agreed to be acquired by Sun Microsystems for approximately
$1 billion.
A Data Type specifies a particular type of data, like integer, floating points, Boolean etc. It also identifies the
possible values for that type, the operations that can be performed on that type and the way the values of that
type are stored.
MySQL supports a lot number of SQL standard data types in various categories. It uses many different data types
broken into mainly three categories: numeric, date and time, and string types.
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.
INT A normal-sized integer that can be signed or unsigned. If signed, the allowable range is from -2147483648 to 21
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 unsign
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 unsign
from 0 to 65535. You can specify a width of up to 5 digits.
MEDIUMINT A medium-sized integer that can be signed or unsigned. If signed, the allowable range is from -8388608 to 8388
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 t
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 decim
and will default to 10,2, where 2 is the number of decimals and 10 is the total number of digits (including decim
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
This is not required and will default to 16,4, where 4 is the number of decimals. Decimal precision can go to 53 p
synonym for double.
DECIMAL(m,d) An unpacked floating-point number that cannot be unsigned. In unpacked decimals, each decimal corresponds t
display length (m) and the number of decimals (d) is required. Numeric is a synonym for decimal.
DATETIME Values range from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'. Displayed as 'yyy
TIMESTAMP(m) Values range from '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' TC. Displayed as 'YYY
CHAR(size) Maximum size of 255 characters. Where size is the number of characters to store. Fixed-length str
to equal size characters.
VARCHAR(size) Maximum size of 255 characters. Where size is the number of characters to store. Variable-length
TINYTEXT(size) Maximum size of 255 characters. Where size is the number of characters to store.
TEXT(size) Maximum size of 65,535 characters. Where size is the number of characters to store.
MEDIUMTEXT(size) Maximum size of 16,777,215 characters. Where size is the number of characters to store.
LONGTEXT(size) Maximum size of 4GB or 4,294,967,295 Where size is the number of characters to store.
characters.
BINARY(size) Maximum size of 255 characters. Where size is the number of binary characters to store. Fixed-len
on right to equal size characters.
(introduced in MySQL 4.1.2)
VARBINARY(size) Maximum size of 255 characters. Where size is the number of characters to store. Variable-length
(introduced in MySQL 4.1.2)
You can create a MySQL database by using MySQL Command Line Client.
Open the MySQL console and write down password, if you set one while installation. You will get the following:
Syntax:
1. CREATE DATABASE database_name;
Example:
1. SHOW DATABASES;
Output
The MySQL CREATE TABLE command is used to create a new table into the database. A table creation command
requires three things:
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. DESCRIBE cus_tbl;
MySQL INSERT statement is used to insert data in MySQL table within the database. We can insert single or
multiple records using a single query in MySQL.
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.
If you have to store all the field values, either specify all field name or don't specify any field.
Example:
Or,
Here, we are going to insert record in the "cus_tbl" table of "customers" database.
Visual Representation:
See the data within the table by using the SELECT command:
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:
MySQL SELECT statement can also be used to retrieve records from multiple tables by using JOIN statement.
Let's take two tables "students" and "officers", having the following data.
Output:
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
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.
If you use a single expression then the MySQL DISTINCT clause will return a single field with unique records (no
duplicate record).
If you use multiple expressions with DISTINCT Clause then MySQL DISTINCT clause will remove duplicates from
more than one field in your SELECT statement.
The MYSQL ORDER BY Clause is used to sort the records in ascending or descending order.
Syntax:
1. SELECT expressions
2. FROM tables
3. [WHERE conditions]
4. ORDER BY expression [ ASC | DESC ];
Parameters
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.
If you use MySQL ORDER BY clause without specifying the ASC and DESC modifier then by default you will get the
result in ascending order.
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:
1. SELECT *
2. FROM officers
3. WHERE address = 'Lucknow'
4. ORDER BY officer_name DESC;
Output:
MySQL BETWEEN Condition
The MYSQL BETWEEN condition specifies how to retrieve values from an expression within a specific range. It is
used with SELECT, INSERT, UPDATE and DELETE statement.
Syntax:
Parameters
value1 and value2: These values define an inclusive range that expression is compared to.
1. SELECT *
2. FROM officers
3. WHERE officer_id BETWEEN 1 AND 3;
Output:
Note: In the above example, you can see that only three rows are returned between 1 and 3.
MySQL BETWEEN condition also facilitates you to retrieve records according to date.
1. SELECT *
2. FROM employees
3. WHERE working_date BETWEEN CAST ('2015-01-24' AS DATE) AND CAST ('2015-01-25' AS DATE);
Output:
Note: In the above example you can see that only data between specific dates are shown.
MySQL IN Condition
The MySQL IN condition is used to reduce the use of multiple OR conditions in a SELECT, INSERT, UPDATE and
DELETE statement.
Syntax:
Parameters
value1, value2, ... or value_n: These are the values to test against expression. If any of these values matches
expression, then the IN condition will evaluate to true. This is a quick method to test if any one of the values
matches expression.
MySQL IN Example
1. SELECT *
2. FROM officers
3. WHERE officer_name IN ('Ajeet', 'Vimal', 'Deepika');
Output:
1. SELECT *
2. FROM officers
3. WHERE officer_name = 'Ajeet'
4. OR officer_name = 'Vimal'
5. OR officer_name = 'Deepika';
Output:
It also produces the same result. So IN condition is preferred over OR condition because it has minimum number
of codes.
In MySQL, LIKE condition is used to perform pattern matching to find the correct result. It is used in SELECT,
INSERT, UPDATE and DELETE statement with the combination of WHERE clause.
Syntax:
Parameters
escape_character: It is optional. It allows you to test for literal instances of a wildcard character such as % or _.
If you do not provide the escape_character, MySQL assumes that "\" is the escape_character.
1. SELECT officer_name
2. FROM officers
3. WHERE address LIKE 'Luck%';
Output:
1.
2. SELECT officer_name
3. FROM officers
4. WHERE address LIKE 'Luc_now';
Output:
You can also use NOT operator with MySQL LIKE condition. This example shows the use of % wildcard with the
NOT Operator.
1. SELECT officer_name
2. FROM officers
3. WHERE address NOT LIKE 'Luck%';
Output:
Aggregate Functions
MySQL count() function is used to returns the count of an expression. It allows us to count all rows or only some
rows of the table that matches a specified condition. It is a type of aggregate function whose return type is
BIGINT. This function returns 0 if it does not find any matching rows.
We can use the count function in three forms, which are explained below:
o Count (*)
o Count (expression)
o Count (distinct)
COUNT(*) Function: This function uses the SELECT statement to returns the count of rows in a result set. The
result set contains all Non-Null, Null, and duplicates rows.
COUNT(expression) Function: This function returns the result set without containing Null rows as the result of
an expression.
COUNT(distinct expression) Function: This function returns the count of distinct rows without containing NULL
values as the result of the expression.
Syntax
aggregate_expression: It specifies the column or expression whose NON-NULL values will be counted.
table_name: 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 the conditions that must be fulfilled for the records to be selected.
Example1
Execute the following query that uses the COUNT(expression) function to calculates the total number of employees
name available in the table:
Output:
Example2
Execute the following statement that returns all rows from the employee table and WHERE clause specifies the
rows whose value in the column emp_age is greater than 32:
Output:
Example3
This statement uses the COUNT(distinct expression) function that counts the Non-Null and distinct rows in the
column emp_age:
Output:
MySQL Count() Function with GROUP BY Clause
We can also use the count() function with the GROUP BY clause that returns the count of the element in each
group. For example, the following statement returns the number of employee in each city:
Let us see another clause that uses ORDER BY and Having clause with the count() function. Execute the following
statement that gives the employee name who has at least two age same and sorts them based on the count
result:
The MySQL sum() function is used to return the total summed value of an expression. It returns NULL if the result
set does not have any rows. It is one of the kinds of aggregate functions in MySQL.
Syntax
1. SELECT SUM(aggregate_expression)
2. FROM tables
3. [WHERE conditions];
Parameter Explanation
aggregate_expression: It specifies the column or expression that we are going to calculate the sum.
table_name: It specifies the tables from where we want to 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 fulfilled for the records to be selected.
Consider our database has a table named employees, having the following data. Now, we are going to understand
this function with various examples:
1. Basic Example
Execute the following query that calculates the total number of working hours of all employees in the table:
Output:
This example is used to return the result based on the condition specified in the WHERE clause. Execute the
following query to calculate the total working hours of employees whose working_hours>= 12.
1. mysql> SELECT SUM(working_hours) AS "Total working hours" FROM employees WHERE working_hours>=12;
Output:
We can also use the SUM() function with the GROUP BY clause to return the total summed value for each group.
For example, this statement calculates the total working hours of each employee by using the SUM() function with
the GROUP BY clause, as shown in the following query:
1. mysql> SELECT emp_id, emp_name, occupation, SUM(working_hours) AS "Total working hours" FROM employee
s GROUP BY occupation;
Output:
Here, we can see that the total working hours of each employee calculates by grouping them based on their
occupation.
The HAVING clause is used to filter the group with the sum() function in MySQL. Execute the following statement
that calculates the working hours of all employees, grouping them based on their occupation and returns the result
whose Total_working_hours>24.
Output:
MySQL uses the DISTINCT keyword to remove the duplicate rows from the column name. This clause can also be
used with sum() function to return the total summed value of a Unique number of records present in the table.
Execute the following query that removes the duplicate records in the working_hours column of the employee
table and then calculates the sum:
Output:
MySQL Count() Function
MySQL count() function is used to returns the count of an expression. It allows us to count all rows or only some
rows of the table that matches a specified condition. It is a type of aggregate function whose return type is
BIGINT. This function returns 0 if it does not find any matching rows.
We can use the count function in three forms, which are explained below:
o Count (*)
o Count (expression)
o Count (distinct)
COUNT(*) Function: This function uses the SELECT statement to returns the count of rows in a result set. The
result set contains all Non-Null, Null, and duplicates rows.
COUNT(expression) Function: This function returns the result set without containing Null rows as the result of
an expression.
COUNT(distinct expression) Function: This function returns the count of distinct rows without containing NULL
values as the result of the expression.
Syntax
aggregate_expression: It specifies the column or expression whose NON-NULL values will be counted.
table_name: 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 the conditions that must be fulfilled for the records to be selected.
Execute the following query that uses the COUNT(expression) function to calculates the total number of employees
name available in the table:
Output:
Example2
Execute the following statement that returns all rows from the employee table and WHERE clause specifies the
rows whose value in the column emp_age is greater than 32:
Output:
Example3
This statement uses the COUNT(distinct expression) function that counts the Non-Null and distinct rows in the
column emp_age:
Output:
We can also use the count() function with the GROUP BY clause that returns the count of the element in each
group. For example, the following statement returns the number of employee in each city:
Let us see another clause that uses ORDER BY and Having clause with the count() function. Execute the following
statement that gives the employee name who has at least two age same and sorts them based on the count
result:
The MySQL min() function is used to return the minimum value from the table.
Syntax:
Parameter explanation
aggregate_expression: It specifies the column or expression, from which the minimum value will be returned.
table_name: 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 the conditions that must be fulfilled for the records to be selected.
Output:
The MySQL max() function is used to return the maximum value of an expression. It is used when you need to get
the maximum value from your table.
Syntax:
1. SELECT MAX(aggregate_expression)
2. FROM tables
3. [WHERE conditions];
Parameter explanation
aggregate_expression: It specifies the column or expression, from which the maximum value will be returned.
table_name: 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 the conditions that must be fulfilled for the records to be selected.
Output:
The MySQL avg() is an aggregate function used to return the average value of an expression in various records.
Syntax
1. SELECT AVG(aggregate_expression)
2. FROM tables
3. [WHERE conditions];
Parameter explanation
aggregate_expression: It specifies the column or expression that we are going to find the average result.
table_name: It specifies the tables from where we want to 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 fulfilled for the records to be selected.
Consider our database has a table named employees, having the following data. Now, we are going to understand
this function with various examples:
1. Basic Example
Execute the following query that calculates the average working hours of all employees in the table:
Output:
Output:
The GROUP BY clause is used to return the result for each group by one or more columns. For example, this
statement calculates the average working hours of each employee using the AVG() function and then group the
result with the GROUP BY clause:
Output:
Here, we can see that the total working hours of each employee calculates by grouping them based on their
occupation.
ASSIGNMENT
Table : Stud