0% found this document useful (0 votes)
3 views19 pages

Table

The document provides an overview of MySQL commands for altering tables, including adding, modifying, dropping, and renaming columns and tables. It also covers the TRUNCATE command for removing all data from a table without deleting its structure, as well as the UPDATE command for modifying existing data. Additionally, it explains how to list tables in a database and use pattern matching with the SHOW TABLES command.

Uploaded by

dhassahil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

Table

The document provides an overview of MySQL commands for altering tables, including adding, modifying, dropping, and renaming columns and tables. It also covers the TRUNCATE command for removing all data from a table without deleting its structure, as well as the UPDATE command for modifying existing data. Additionally, it explains how to list tables in a database and use pattern matching with the SHOW TABLES command.

Uploaded by

dhassahil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

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.

1) ADD a column in the table


Syntax:

1. ALTER TABLE table_name


2. ADD new_column_name column_definition
3. [ FIRST | AFTER column_name ];

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).

FIRST | AFTER column_name: It is optional. It tells MySQL where in the table to


create the column. If this parameter is not specified, the new column will be added to
the end of the table.

Example:

In this example, we add a new column "cus_age" in the existing table "cus_tbl".

Use the following query to do this:

1. ALTER TABLE cus_tbl


2. ADD cus_age varchar(40) NOT NULL;

Output:
See the recently added column:

1. SELECT* FROM cus_tbl;

Output:

2) Add multiple columns in the table


Syntax:

1. ALTER TABLE table_name


2. ADD new_column_name column_definition
3. [ FIRST | AFTER column_name ],
4. ADD new_column_name column_definition
5. [ FIRST | AFTER column_name ],
6. ...
7. ;

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.

Use the following query to do this:

1. ALTER TABLE cus_tbl


2. ADD cus_address varchar(100) NOT NULL
3. AFTER cus_surname,
4. ADD cus_salary int(100) NOT NULL
5. AFTER cus_age ;
See the recently added columns:

1. SELECT* FROM cus_tbl;

3) MODIFY column in the table


The MODIFY command is used to change the column definition of the table.

Syntax:

1. ALTER TABLE table_name


2. MODIFY column_name column_definition
3. [ FIRST | AFTER column_name ];

Example:

In this example, we modify the column cus_surname to be a data type of varchar(50)


and force the column to allow NULL values.

Use the following query to do this:

1. ALTER TABLE cus_tbl


2. MODIFY cus_surname varchar(50) NULL;
See the table structure:

4) DROP column in table


Syntax:

1. ALTER TABLE table_name


2. DROP COLUMN column_name;
Let's take an example to drop the column name "cus_address" from the table "cus_tbl".

Use the following query to do this:

1. ALTER TABLE cus_tbl


2. DROP COLUMN cus_address;

Output:

See the table structure:


5) RENAME column in table
Syntax:

1. ALTER TABLE table_name


2. CHANGE COLUMN old_name new_name
3. column_definition
4. [ FIRST | AFTER column_name ]

Example:

In this example, we will change the column name "cus_surname" to "cus_title".

Use the following query to do this:

1. ALTER TABLE cus_tbl


2. CHANGE COLUMN cus_surname cus_title
3. varchar(20) NOT NULL;

Output:
6) RENAME table
Syntax:

1. ALTER TABLE table_name


2. RENAME TO new_table_name;

Example:

In this example, the table name cus_tbl is renamed as cus_table.

1. ALTER TABLE cus_tbl


2. RENAME TO cus_table;

Output:
See the renamed table:

MySQL TRUNCATE Table


The TRUNCATE statement in MySQL removes the complete data without removing its
structure. It is a part of DDL or data definition language command. Generally, we use
this command when we want to delete an entire data from a table without removing the
table structure.

The TRUNCATE command works the same as a DELETE command without using
a WHERE clause that deletes complete rows from a table. However, the TRUNCATE
command is more efficient as compared to the DELETE command because it removes
and recreates the table instead of deleting single records one at a time. Since this
command internally drops the table and recreates it, the number of rows affected by the
truncate statement is zero, unlike the delete statement that returns the number of
deleted rows.

This command does not maintain the transaction log during the execution. It deallocates
the data pages instead of rows and makes an entry for the deallocating pages instead
of rows in transaction logs. This command also locks the pages instead of rows; thus, it
requires fewer locks and resources.

The following points must be considered while using the TRUNCATE command:

o We cannot use the WHERE clause with this command so that filtering of records is not
possible.
o We cannot rollback the deleted data after executing this command because the log is
not maintained while performing this operation.
o We cannot use the truncate statement when a table is referenced by a foreign key or
participates in an indexed view.
o The TRUNCATE command doesn't fire DELETE triggers associated with the table that
is being truncated because it does not operate on individual rows.

Syntax
The following syntax explains the TRUNCATE command to remove data from the table:

1. TRUNCATE [TABLE] table_name;

In this syntax, first, we will specify the table name which data we are going to remove.
The TABLE keyword in the syntax is not mandatory. But it's a good practice to use it to
distinguish between the TRUNCATE() function and the TRUNCATE TABLE statement.

MySQL Truncate Table Example


Let us demonstrate how we can truncate the table with the help of an example. First, we
are going to create a table named "customer" using the below statement:

1. CREATE TABLE customer (


2. Id int PRIMARY KEY NOT NULL,
3. Name varchar(45) NOT NULL,
4. Product varchar(45) DEFAULT NULL,
5. Country varchar(25) DEFAULT NULL,
6. Year int NOT NULL
7. );

Next, we will add values to this table using the below statement:

1. INSERT INTO customer ( Id, Name, Product, Country, Year)


2. VALUES (1, 'Stephen', 'Computer', 'USA', 2015),
3. (2, 'Joseph', 'Laptop', 'India', 2016),
4. (3, 'John', 'TV', 'USA', 2016),
5. (4, 'Donald', 'Laptop', 'England', 2015),
6. (5, 'Joseph', 'Mobile', 'India', 2015),
7. (6, 'Peter', 'Mouse', 'England', 2016);

Now, verify the table by executing the SELECT statement whether the records inserted
or not:

1. mysql> SELECT * FROM customer;

We will get the output, as shown below:

Now, execute the following statement that truncates the table customer using the
TRUNCATE syntax discussed above:

1. mysql> TRUNCATE TABLE customer;

After the successful execution, we will get the following output:


As we can see, this query returns 0 rows are affected even if all the table records are
deleted. We can verify the deletion of the data by executing the SELECT statement
again. This command gives the following output that shows none of the records present
in the table:

How to Truncate Table with Foreign key?


If we perform the TRUNCATE operation for the table that uses a foreign key constraint,
we will get the following error:

ERROR 1217 (23000): Cannot delete or u


pdate a parent row: a foreign key constrain
t fails MySQL UPDATE Query
MySQL UPDATE query is a DML statement used to modify the data of the MySQL table
within the database. In a real-life scenario, records are changed over a period of time.
So, we need to make changes in the values of the tables also. To do so, it is required to
use the UPDATE query.

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:

1. UPDATE table_name
2. SET column_name1 = new-value1,
3. column_name2=new-value2, ...
4. [WHERE Clause]
Parameter Explanation
The description of parameters used in the syntax of the UPDATE statement is given
below:

Play Video

Parameter Descriptions

table_name It is the name of a table in which we want to perform updation.

column_nam It is the name of a column in which we want to perform updation with the new value using the
e 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 perform updation. If
Clause we omit this clause, MySQL updates all rows.

Note:

o This statement can update values in a single table at a time.


o We can update single or multiple columns altogether with this statement.
o Any condition can be specified by using the WHERE clause.
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.

The UPDATE command supports these modifiers in MySQL:

LOW_PRIORITY: This modifier instructs the statement to delay the UPDATE


command's execution until no other clients reading from the table. It takes effects only
for the storage engines that use only table-level locking.

IGNORE: This modifier allows the statement to do not abort the execution even if errors
occurred. If it finds duplicate-key conflicts, the rows are not updated.

Therefore, the full syntax of UPDATE statement is given below:


1. UPDATE [LOW_PRIORITY] [IGNORE] table_name
2. SET column_assignment_list
3. [WHERE condition]
Example:
Let us understand the UPDATE statement with the help of various examples. Suppose
we have a table "trainer" within the "testdb" database. We are going to update the
data within the "trainer" table.

Update Single Column

This query will update the email id of Java course with the new id as follows:

1.

In that case, we need to log into the MySQL server and disable foreign key checks
before executing the TRUNCATE statement as below:

1. SET FOREIGN_KEY_CHECKS=0;

Now, we are able to truncate tables. After execution, re-enable foreign key checks as
given below:

1. SET FOREIGN_KEY_CHECKS=1;
How to truncate all tables in MySQL?
The TRUNCATE statement in MySQL will delete only one table at a time. If we want to
delete more than one table, we need to execute the separate TRUNCATE statement.
The below example shows how to truncate multiple tables in MySQL:

1. TRUNCATE TABLE table_name1;


2. TRUNCATE TABLE table_name2;
3. TRUNCATE TABLE table_name3;

We can also use the below SQL query that generates several TRUNCATE TABLE
commands at once using the table names in our database:

1. SELECT Concat('TRUNCATE TABLE ', TABLE_NAME)


2. FROM INFORMATION_SCHEMA.TABLES
3. WHERE table_schema = 'database_name';

MySQL Show/List Tables


The show or list table is very important when we have many databases that contain
various tables. Sometimes the table names are the same in many databases; in that
case, this query is very useful. We can get the number of table information of a
database using the following statement:

1. mysql> SHOW TABLES;

The following steps are necessary to get the list of tables:

Step 1: Open the MySQL Command Line Client that appeared with a mysql> prompt.
Next, log in to the MySQL database server using the password that you have created
during the installation of MySQL. Now, you are connected to the MySQL server, where
you can execute all the SQL statements.

Step 2: Next, choose the specific database by using the command below:

1. mysql> USE database_name;

Step 3: Finally, execute the SHOW TABLES command.

Let us understand it with the example given below. Suppose we have a database name
"mystudentdb" that contains many tables. Then execute the below statement to list the
table it contains:

1. mysql> USE mystudentdb;


2. mysql>SHOW TABLES;

The following output explains it more clearly:


We can also use the FULL modifier with the SHOW TABLES query to get the type of
table (Base or View) that appears in a second output column.

1. mysql> SHOW FULL TABLES;

This statement will give the following output:

If we want to show or list the table name from different databases or database to which
you are not connected without switching, MySQL allows us to use the FROM or IN
clause followed by the database name. The following statement explains it more clearly:

1. mysql> SHOW TABLES IN database_name;

The above statement can also be written as:

1. mysql> SHOW TABLES FROM database_name;


When we execute the below statements, we will get the same result:

1. mysql> SHOW TABLES FROM mystudentdb;


2. OR,
3. mysql> SHOW TABLES IN mystudentdb;

Output:

Show Tables Using Pattern Matching


Show Tables command in MySQL also provides an option that allows us to filter the
returned table using different pattern matching with LIKE and WHERE clause.

Syntax

The following are the syntax to use pattern matching with show table command:

1. mysql> SHOW TABLES LIKE pattern;


2. OR,
3. mysql> SHOW TABLES WHERE expression;

We can understand it with the example given below where percent (%) sign assumes
zero, one, or multiple characters:

1. mysql> SHOW TABLES FROM mystudentdb LIKE "stud%";

The above statement will give the following output:


Let us see another statement that returned the table names starting with "time":

1. mysql> SHOW TABLES IN mysql LIKE "time%";

The above query will give the following output:

Now, we are going to see how we can use the WHERE clause with the SHOW TABLES
command to list different types of tables (either Base or View type) in the selected
database:

1. mysql> SHOW TABLES FROM sakila WHERE table_type= "VIEW";

This statement gives the below output:


It is noted that if MySQL does not provide the privileges for accessing a Base table or
view, then we cannot get the tables in the result set of the SHOW TABLES command.

Here, we can also see another example of Show Tables statement with the WHERE
clause:

1. mysql> SHOW TABLES In mystudentdb WHERE Tables_in_mystudentdb= "employees";

It will give the following output:

You might also like