Professional Documents
Culture Documents
Module-IV: Database concepts: Open source database software: MySQL features MySQL
data types: Numeric, date & time, string Table creation in MySQL: insert, select, where
clause, ordering the result, like operator Selecting Multiple tables: using join, using queries
Modifying records: update command, replace command, delete command date & time
functions in MySQL Interacting with MySQL using PHP: connecting to MYSQL ,Executing
queries, Retrieving error messages, inserting data with PHP, retrieving data with PHP
Syntax
The following are the syntax used to change the name of the table:
Here, we have to make sure that new_table_name must not exist, and old_table_name should
be present in the database. Otherwise, it will throw an error message. It is to ensure that the table
is not locked as well as there are no active transactions before executing this statement.
Let us understand how the RENAME TABLE statement works in MySQL through the various
examples. Suppose we have a table named EMPLOYEE, and due to some reason, there is a need
to change it into the table named CUSTOMER.
Output
We will see that the table named "employee" will be changed into a new table name "customer":
1
In the above output, we can see that if we use the table name employee after executing a
RENAME TABLE statement, it will throw an error message.
Syntax
Parameter Description
Name
TEMPORARY It is an optional parameter that specifies to delete the temporary tables only.
table_name It specifies the name of the table which we are going to remove from the
database.
IF EXISTS It is optional, which is used with the DROP TABLE statement to remove the
tables only if it exists in the database.
RESTRICT and Both are optional parameters that do not have any impact or effect on this
CASCADE statement. They are included in the syntax for future versions of MySQL.
2
Example
This example specifies how we can drop an existing table from the database. Suppose our
database contains a table "orders" as shown in the image below:
It will remove the table permanently. We can also check the table is present or not as shown in
the below output:
If we try to delete a table that does not exist in the database, we will get an error message as
given below:
If we use the IF EXISTS clause with the DROP TABLE statement, MySQL gives the warning
message which can be shown in the below output:
3
1. Insert record in a single row
Syntax:
The below is generic syntax of SQL INSERT INTO command to insert a single record
in MySQL table:
In the above syntax, we first have to specify the table name and list of comma-separated columns.
Second, we provide the list of values corresponding to columns name after the VALUES clause.
NOTE: Field name is optional. If we want to specify partial values, the field name is mandatory. It also
ensures that the column name and values should be the same. Also, the position of columns and
corresponding values must be the same.
If we want to insert multiple records within a single command, use the following statement:
( value1, value2,...valueN )
( value1, value2,...valueN )
...........
( value1, value2,...valueN );
In the above syntax, all rows should be separated by commas in the value fields.
Let us understand how INSERT statements work in MySQL with the help of multiple examples.
First, create a table "People" in the database using the following command:
1. If we want to store single records for all fields, use the syntax as follows:
INSERT INTO People (id, name, occupation, age) VALUES (101, 'Peter', 'Engineer', 32);
2. If we want to store multiple records, use the following statements where we can either specify
all field names or don't specify any field.
4
INSERT INTO People VALUES
(102, 'Joseph', 'Developer', 30),
(103, 'Mike', 'Leader', 28),
(104, 'Stephen', 'Scientist', 45);
3. If we want to store records without giving all fields, we use the following partial
field statements. In such case, it is mandatory to specify field names.
In the below output, we can see that all INSERT statements have successfully executed and stored
the value in a table correctly.
We can use the below syntax to show the records of the People table:
We can also use the INSERT STATEMENT to add the date in MySQL table. MySQL provides several
data types for storing dates such as DATE, TIMESTAMP, DATETIME, and YEAR. The default
format of the date in MySQL is YYYY-MM-DD.
5
o YYYY: It represents the four-digit year, like 2020.
o MM: It represents the two-digit month, like 01, 02, 03, and 12.
o DD: It represents the two-digit day, like 01, 02, 03, and 31.
INSERT INTO table_name (column_name, column_date) VALUES ('DATE: Manual Date', '2008-
7-04');
If we want to insert a date in the mm/dd/yyyy format, it is required to use the below statement:
The UPDATE statement is used with the SET and WHERE clauses. The SET clause is used to
change the values of the specified column. We can update single or multiple columns at a time.
Syntax
Following is a generic syntax of UPDATE command to modify data into the MySQL table:
Parameter Explanation
The description of parameters used in the syntax of the UPDATE statement is given below:
Parameter Descriptions
column_name It is the name of a column in which we want to perform updation with the
new value using the SET clause. If there is a need to update multiple
columns, separate the columns with a comma operator by specifying the
value in each column.
WHERE It is optional. It is used to specify the row name in which we are going to
Clause perform updation. If we omit this clause, MySQL updates all rows.
6
Note:
o WHERE clause is very important because sometimes we want to update only a single row,
and if we omit this clause, it accidentally updates all rows of the table.
Example:
Suppose we have a table "trainer" within the "testdb" database. We are going to update the
data within the "trainer" table.
This query will update the email id of Java course with the new id as follows:
In the output, we can see that our table is updated as per our conditions.
The UPDATE statement can also be used to update multiple columns by specifying a comma-
separated list of columns. Suppose we have a table as below:
7
This statement explains will update the name and occupation whose id = 105 in
the People table as follows:
UPDATE People SET name = 'Mary', occupation = 'Content Writer' WHERE id = 105;
Once we delete the records using this query, we cannot recover it. Therefore before
deleting any records from the table, it is recommended to create a backup of your database.
The database backups allow us to restore the data whenever we need it in the future.
Syntax:
The following are the syntax that illustrates how to use the DELETE statement:
DELETE FROM table_name WHERE condition;
In the above statement, we have to first specify the table name from which we want to delete
data. Second, we have to specify the condition to delete records in the WHERE clause, which is
optional. If we omit the WHERE clause into the statement, this query will remove whole records
from the database table.
8
If we want to delete records from multiple tables using a single DELETE query, we must add
the JOIN clause with the DELETE statement.
If we want to delete all records from a table without knowing the count of deleted rows, we must
use the TRUNCATE TABLE statement that gives better performance.
Here, we are going to use the "Employees" and "Payment" tables for the demonstration of the
DELETE statement. Suppose the Employees and Payment tables contain the following data:
If we want to delete an employee whose emp_id is 107, we should use the DELETE statement
with the WHERE clause. See the below query:
After the execution of the query, it will return the output as below image. Once the record is
deleted, verify the table using the SELECT statement:
9
If we want to delete all records from the table, there is no need to use the WHERE clause with the
DELETE statement. See the below code and output:
In the above output, we can see that after removing all rows, the Employees table will be empty.
It means no records available in the selected table.
Parameter Explanation
field_name(s) or It is used to specify one or more columns to returns in the result set. The
* asterisk (*) returns all fields of a table.
WHERE It is an optional clause. It specifies the condition that returned the matched
records in the result set.
GROUP BY It is optional. It collects data from multiple records and grouped them by
one or more columns.
HAVING It is optional. It works with the GROUP BY clause and returns only those
rows whose condition is TRUE.
ORDER BY It is optional. It is used for sorting the records in the result set.
LIMIT It is optional. It is used to limit the number of returned records in the result
set.
NOTE: It is to note that MySQL always evaluates the FROM clause first, and then the SELECT clause
will be evaluated.
Let us understand how SELECT command works in MySQL with the help of various examples.
Suppose we have a table named employee_detail that contains the following data:
1. If we want to retrieve a single column from the table, we need to execute the below query:
We will get the below output where we can see only one column records.
2. If we want to query multiple columns from the table, we need to execute the below query:
We will get the below output where we can see the name, email, and city of employees.
3. If we want to fetch data from all columns of the table, we need to use all column's names
with the select statement. Specifying all column names is not convenient to the user, so MySQL
uses an asterisk (*) to retrieve all column data as follows:
4. Here, we use the SUM function with the HAVING clause in the SELECT command to get the
employee name, city, and total working hours. Also, it uses the GROUP BY clause to group them
by the Name column.
5. MySQL SELECT statement can also be used to retrieve records from multiple tables by using
a JOIN statement. Suppose we have a table named "customer" and "orders" that contains the
following data:
Table: customer
Table: orders
Execute the following SQL statement that returns the matching records from both tables using
the INNER JOIN query:
After successful execution of the query, we will get the output as follows:
MySQL REPLACE
The REPLACE statement in MySQL is an extension of the SQL Standard. This statement works the
same as the INSERT statement, except that if an old row matches the new record in the table for a
PRIMARY KEY or a UNIQUE index, this command deleted the old row before the new row is added.
This statement is required when we want to update the existing records into the table to keep
them updated. If we use the standard insert query for this purpose, it will give a Duplicate entry
for PRIMARY KEY or a UNIQUE key error. In this case, we will use the REPLACE statement to
perform our task. The REPLACE command requires one of the two possible actions take place:
o If no matching value is found with the existing data row, then a standard INSERT
statement is performed.
o
o If the duplicate record found, the replace command will delete the existing row and then
adds the new record in the table.
In the REPLACE statement, the updation performed in two steps. First, it will delete the existing
record, and then the newly updated record is added, similar to a standard INSERT command.
Thus, we can say that the REPLACE statement performs two standard
functions, DELETE and INSERT.
Syntax
First, we are going to create a table named "Person" using the following statement:
Next, we need to fill the record into the table using the INSERT statement as below:
Execute the SELECT statement to verify the records that can be shown in the below output:
After verifying the data into a table, we can replace any old row with the new row using the
REPLACE statement. Execute the below statement that updates the city of a person whose id is
4.
After the successful execution of the above statement, it is required to query the data of the table
Person again to verify the replacement.
The value in the name and email columns are NULL now. It is because the REPLACE statement
works as follows:
o This statement first tries to insert a new row into the Person table. But the insertion of a
new row is failed because the id = 4 already exists in the table.
o So this statement first delete the row whose id = 4 and then insert a new row with the
same id and city as Amsterdam. Since we have not specified the value for the name and
email column, it was set to NULL.
We can use the following REPLACE statement to update a row data into a table:
The above syntax is similar to the UPDATE statement except for the REPLACE keyword. It is to
note that we cannot use the WHERE clause with this statement.
Execute the below example that uses the REPLACE statement to update the city of the person
named Mike from California to Birmingham.
We can use the following REPLACE INTO statement to inserts data into a table with the data
returns from a query.
It is to note that the above REPLACE query is similar to the INSERT INTO SELECT statement.
Execute the below example that uses the REPLACE INTO statement to copy a row within the same
table.
REPLACE INTO Person(Name, City) SELECT Name, City FROM Person WHERE id = 2;
After verification of the table, we will get the following output. In this output, we can see that the
copy of a row within the same table is successfully added.
WHERE conditions;
Parameter:
conditions: It specifies the conditions that must be fulfilled for records to be selected.
Table structure:
Output:
Output:
Output:
Output:
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:
FROM table1
[ { INNER JOIN | LEFT [OUTER] JOIN| RIGHT [OUTER] JOIN } table2
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.
MySQL FROM Clause: Retrieve data from one table
The following query specifies how to retrieve data from a single table.
MySQL FROM Clause: Retrieve data from two tables with inner
join
Let's take an example to retrieve data from two tables using INNER JOIN.
Syntax:
SELECT expressions FROM tables [WHERE conditions] 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.
Output:
SELECT officer_name, address FROM officers WHERE officer_id < 5 ORDER BY officer_name
DESC, address ASC;
Output:
You can also use some aggregate functions like COUNT, SUM, MIN, MAX, AVG etc. on the grouped
column.
Syntax:
Parameters
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.
aggregate_function: It specifies a function such as SUM, COUNT, MIN, MAX, or AVG etc. tables:
It specifies the tables, from where you want to retrieve the 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:
Output:
Output:
Output:
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.
WHERE conditions: It is optional. It specifies the conditions for the records to be selected.
HAVING condition: It is used to restrict the groups of returned rows. It shows only those groups
in result set whose conditions are TRUE.
Here, we use the SUM function with the HAVING Clause to return the emp_name and sum of their
working hours.
Simply, it can also be used with COUNT, MIN, MAX and AVG functions.