02_02_Tables
02_02_Tables
1. Create table
2. Alter table
3. Show table
4. TRUNCATE Table
5. Describe table
6. Drop table
7. Copy/Clone/Duplicate Table
a.
MySQL Table
1. create database >create database p1;
> use p1;
2. create tables
1. Create Table Optiona
l
CREATE TABLE [IF NOT EXISTS] table_name(
column_definition1,
column_definition2,
table_constraints
);
Example:
Or describe emp;
2. ALTER Table
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.
Alter table always use "ADD", "DROP" and "MODIFY"
1. ADD column
alter table emp table name
add salary int not null;
2. MODIFY column
lets modify address
before:
After:
alter table emp
modify address varchar(150) null;
3. DROP column
alter table emp
drop column surname;
4. RENAME column 2 ways (rename and change)
alter table emp
rename to emp1;
Rename column
alter table emp Rename column works but the data which is
rename column Name to Full_Name; inserted gets lost
Using Change
2) use p1;
show full tables;
WHERE clause to list different types of tables (either Base or View type)
SHOW TABLES FROM sakila WHERE table_type= "VIEW";
TRUNCATE Table
we use this command when we want to delete an entire data from a table without
removing the table structure.
The following points must be considered while using the TRUNCATE command:
cannot use the WHERE clause (filtering of records is not possible).
cannot rollback the deleted data
We cannot use the truncate statement when a table is referenced by a foreign
key or participates in an indexed view.
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:
truncate table emp;
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 update a parent row: a foreign key constr
aint fails
In that case, we need to log into the MySQL server and disable foreign key checks
before executing the TRUNCATE statement as below:
SET FOREIGN_KEY_CHECKS=0;
Now, we are able to truncate tables. After execution, re-enable foreign key checks
as given below:
SET FOREIGN_KEY_CHECKS=1;
Syntax:
describe table_name;
Or
desc table_name;
6 DROP Table
Syntax:
drop table table_name;
1 delete a table that does not exist in the database, we will get an error message
2 IF EXISTS clause with the DROP TABLE statement, MySQL gives the warning message
7 Copy/Clone/Duplicate Table
1 create a table
create table original_table (
Id int primary key not null,
Name varchar(45) not null,
Product varchar(45) null,
Country varchar(25) null,
Year int not null );
Copying a table
create table if not exists duplicate_table
select * from original_table;
8 Table Locking
READ LOCK: This lock allows a user to only read the data from a table.
WRITE LOCK: This lock allows a user to do both reading and writing into a table.