Lab Chapter 4

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

CHAPTER FOUR

4. MySQL TABLE AND VIEW


Learning Objectives: After completing this chapter, you should be able to do the following:
• Identify the table name and structure
• Create a new table with the CREATE TABLE command
• Use a subquery to create a new table
• Add a column to an existing table
• Modify the definition of a column in an existing table
• Delete a column from an existing table
• Mark a column as unused and then delete it later
• Rename a table
• Truncate a table
• Drop a table
4.1. Create Table
Table is a collection of data, organized in terms of rows and columns. There are six properties of
tables in a relational database:
• Property 1: Entries in columns are single-valued
• Property 2: Entries in columns are of the same kind
• Property 3: Each row is unique
• Property 4: Sequence of columns is insignificant
• Property 5: Sequence of rows is insignificant
• Property 6: Each column has a unique name
The MySQL CREATE TABLE command is used to create a new table into the database. A table
creation command requires three things: name of the table, names of fields and definitions for each
field. Following is a generic syntax for creating a MySQL table in the database.
Syntax: CREATE TABLE table_name (column_name column_data_type (size) constraint,
column_name column_data_type (size) constraint,
column_name column_data_type (size) constraint, …);
Example: Here, we will create a table named "STUDENT" in the database "WKU".

1
CREATE TABLE Student (
STUDID INT NOT NULL AUTO_INCREMENT,
FirstName VARCHAR (100) NOT NULL,
Lastname VARCHAR (100) NOT NULL,
PRIMARY KEY (STUDID));
Note: 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. 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.
See the created table: Use the following command to see the table already created:
Example: SHOW tables;
See the table structure: Use the following command to see the table already created:
Example: DESCRIBE Student;
Exercise: Write a SQL statement to create a simple table country including columns country_id,
country_name and region_id?
CREATE TABLE country(
COUNTRY_ID varchar(2),
COUNTRY_NAME varchar(40),
REGION_ID decimal(10,0) );
Exercise: Write a SQL statement to create a simple table country including columns
country_id,country_name and region_id which is already exists?
CREATE TABLE IF NOT EXISTS country (
COUNTRY_ID varchar(2),
COUNTRY_NAME varchar(40),
REGION_ID decimal(10,0) );
Exercise: Write a SQL statement to create the structure of a table dup_country similar to country?

CREATE TABLE IF NOT EXISTS dup_country LIKE country;


Exercise: Write a SQL statement to create a duplicate copy of country table including structure
and data by name dup_country?

CREATE TABLE IF NOT EXISTS dup_country AS SELECT * FROM country;

2
Exercise: Write a SQL statement to create a table country set a constraint NULL?
CREATE TABLE IF NOT EXISTS country (
COUNTRY_ID varchar(2) NOT NULL,
COUNTRY_NAME varchar(40) NOT NULL,
REGION_ID decimal(10,0) NOT NULL );
4.2. 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 to add, modify
or delete columns in an existing table. It is also used to rename a table. You can also use MySQL
ALTER TABLE command to add and drop various constraints on an existing table.
4.2.1. Add Single Column
If you want to add column in table, the alter table syntax is given below:
Syntax: ALTER TABLE table_name ADD new_column_name column_definition or datatype [
FIRST | AFTER column_name ];
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: ALTER TABLE Student ADD age int NOT NULL;
Exercise: Write a SQL statement to add a column department_id to the table student after
LastName?
ALTER TABLE Student ADD department_id INT AFTER LastName;
Exercise: Write a SQL statement to add a column region_id to the table location?
ALTER TABLE location ADD region_id INT;
Exercise: Write a SQL statement to add a columns ID as the first column of the table location?
ALTER TABLE location ADD ID INT FIRST;

3
4.2.2. Add Multiple Columns
Syntax: ALTER TABLE table_name ADD new_column_name column_definition [ FIRST |
AFTER column_name], ADD new_column_name column_definition [ FIRST | AFTER
column_name], ...;
Example: ALTER TABLE Student ADD address varchar(100) NOT NULL AFTER FirstName,
ADD City Varchar(100) AFTER age;
See the recently added column: SELECT* FROM Student;
Exercise: Write a SQL statement to add a column region after city and column skill before age to
the table student?
ALTER TABLE Student ADD region Varchar(40) AFTER city, skill Varchar(30) FIRST age;
4.2.3. Modify Column
The MODIFY command is used to change the column definition of the table.
Syntax: ALTER TABLE table_name MODIFY column_name column_definition [FIRST |
AFTER column_name];
Example: In this example, we modify the column City to be a data type of varchar(100) and force
the column to allow NULL values. Use the following query to do this:
ALTER TABLE Student MODIFY City varchar(100) NULL;
Exercise: Write a SQL statement change the data type of the column STUDID to varchar in the
table student?
ALTER TABLE student MODIFY STUDID Varchar(30);
Exercise: Write a SQL statement change the data type of the column country_id to integer in the
table location?
ALTER TABLE location MODIFY country_id INT;
If you want to modify multiple columns in table will be:
Syntax: ALTER TABLE table-name MODIFY (column1 column-type, column 2 column-type,
..., column n column-type);
Exercise: Write a SQL statement change the data type of the column FirstName and LastName to
char in the table Student?
Exercise: Write a SQL statement change the data type of the column country_id to integer and
column contry_name to char the table location?

4
4.2.4. Drop Column
Syntax: ALTER TABLE table_name DROP COLUMN column_name;
Example: ALTER TABLE Student DROP COLUMN City;
Exercise: Write a SQL statement to drop the column city from the table student?
ALTER TABLE student DROP city;
Exercise: Write a SQL statement to drop the column address, age and region from the table
student?
4.2.5. Rename Column
Syntax: ALTER TABLE table_name CHANGE COLUMN old_name new_name
column_definition [ FIRST | AFTER column_name];
In this example, we will change the column name "City" to "Town".
Example: ALTER TABLE Student CHANGE COLUMN City Towen varchar(20);
Exercise: Write a SQL statement to rename the column name region to country?
ALTER TABLE Student CHANGE COLUMN region country varchar(20);
Exercise: Write a SQL statement to rename the column name country_id to ID?
4.3. Truncate Table
MYSQL TRUNCATE statement removes the complete data without removing its structure. The
TRUNCATE TABLE statement is used when you want to delete the complete data from a table
without removing the table structure. A truncate is similar to the DELETE statement with no
WHERE clause. Truncate table is faster and uses lesser resources than DELETE TABLE
command. Drop table command can also be used to delete complete table but it deletes table
structure too. TRUNCATE TABLE doesn't delete the structure of the table.
Syntax: TRUNCATE TABLE table_name;
This example specifies how to truncate a table. In this example, we truncate the table "Student".
Example: TRUNCATE TABLE Student;
See the table: SELECT* FROM Student;
Note: The rollback process is not possible after truncate table statement. Once you truncate a table
you cannot use a flashback table statement to retrieve the content of the table.

5
4.4. Drop Table
MySQL DROP TABLE statement is used to delete a table definition and all data from a table. This
is very important to know that once a table is deleted all the information available in the table is
lost forever, so we have to be very careful when using this command.
Syntax: DROP TABLE table_name;
This example specifies how to drop a table. In this example, we are dropping the table "Student ".
Example: DROP TABLE Student;
Exercise: Write a SQL statement to drop the table location and IS_Student?
4.4.1. Drop Vs Truncate Statements
When you use the drop statement it deletes the table's row together with the table's definition so
all the relationships of that table with other tables will no longer be valid. When you drop a table:
• Table structure will be dropped
• Relationship will be dropped
• Integrity constraints will be dropped
• Access privileges will also be dropped
In the case of TRUNCATE TABLE, it removes only table data not structure. You don't need to
re-create the table again because the table structure already exists, so you will not face any of the
above problems.
4.5. Delete Statement
The DELETE statement is used to delete rows from a table. If you want to remove a specific row
from a table, you should use WHERE condition.
Syntax: DELETE FROM table-name [WHERE condition];
But if you do not specify the WHERE condition it will remove all the rows from the table.
Syntax: DELETE FROM table-name;
There are some more terms similar to DELETE statement like as DROP statement and
TRUNCATE statement but they are not exactly same there are some differences between them.
4.5.1. Delete Vs Truncate
There is a slight difference between delete and truncate statement. The DELETE statement only
deletes the rows from the table based on the condition defined by WHERE clause or delete all the
rows from the table when condition is not specified. But it does not free the space containing by

6
the table. The TRUNCATE statement: it is used to delete all the rows from the table and free
the containing space.
4.6. Rename Table
SQL RENAME TABLE syntax is used to change the name of a table. Sometimes, we choose
non-meaningful name for the table. So it is required to be changed.
Syntax: ALTER TABLE table-name RENAME TO new-table-name;
Example: ALTER TABLE Student RENAME TO Learner;
Example: ALTER TABLE Employee RENAME TO Worker;
Syntax: ALTER TABLE table_name RENAME TO new_table_name;
In this example, the table name Student is renamed as IS_Student.
Example: ALTER TABLE Student RENAME TO IS_Student;
See the renamed table: show tables;
Exercise: Write a SQL statement to rename the table country to country_new?
ALTER TABLE country RENAME country_new;
Exercise: Write a SQL statement to rename the table IS_student to CCI_student?
4.7. Create View Table
A VIEW is created by SELECT statements. SELECT statements are used to take data from the
source table to make a VIEW.
Syntax: CREATE [OR REPLACE] VIEW view_name AS SELECT columns FROM tables
[WHERE conditions];
OR REPLACE: It is optional. It is used when a VIEW already exist. If you do not specify this
clause and the VIEW already exists, the CREATE VIEW statement will return an error.
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 "Student". This is a virtual table made by taking
data from the table "course".
CREATE VIEW Student AS SELECT course_name, course_learner FROM course;
To see the created VIEW:
Syntax: ELECT * FROM view_name;
Let's see how it looks the created VIEW: SELECT * FROM Student;

7
4.7.1. Update View Table
In MYSQL, the ALTER VIEW statement is used to modify or update the already created VIEW
without dropping it.
Syntax: ALTER VIEW view_name AS SELECT columns FROM table WHERE conditions;
The following example will alter the already created VIEW name "Student" by adding a new
column.
Example: ALTER VIEW Student AS SELECT course_name, course_learner, course_id FROM
course; To see the altered VIEW:
Example: SELECT*FROM Student;
4.7.2. Drop View Table
You can drop the VIEW by using the DROP VIEW statement.
Syntax: DROP VIEW [IF EXISTS] view_name;
view_name: It specifies the name of the VIEW that you want to drop.
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: DROP VIEW trainer;
4.8. SQL Copy Table
If you want to copy a SQL table into another table in the same SQL server database, it is possible
by using the select statement. The syntax of copying table from one to another is given below:
Syntax: SELECT * INTO destination-table FROM source-table;
For example, you can write following command to copy the records of Employee table into
Instructor table.
Example: SELECT * INTO Instructor FROM Employee;
Note: SELECT INTO is totally different from INSERT INTO statement.
In MySQL, View is a virtual table created by a query by joining one or more tables.

Summary
You create a table with the CREATE TABLE command. Each column to be included in the table
must be defined in terms of the column name, datatype, and the width (for certain datatypes). A
table can contain up to 1000 columns. Each column name in a table must be unique. Table and
column names can contain as many as 30 characters. The names must begin with a letter and can’t
contain blank spaces. A DEFAULT setting assigns a column value if no value is provided for the

8
column when a new row is added. A virtual column is a column defined by an expression that
generates a value based on other column values in the table when queried.
A query on the data dictionary object USER_TAB_COLUMNS enables you to verify DEFAULT
and virtual column settings. A column may be hidden from users by using the invisible option. To
create a table based on existing tables’ structure and data, use the CREATE TABLE … AS
command to use a subquery that extracts the necessary data from the existing table. You can
change a table’s structure with the ALTER TABLE command. Columns can be added, resized,
and even deleted with the ALTER TABLE command. When using the ALTER TABLE command
with the DROP COLUMN clause, only one column can be specified for deletion. Tables can be
renamed with the RENAME … TO command. To delete all the rows in a table, use the
TRUNCATE TABLE command. To remove both the structure of a table and all its contents, use
the DROP TABLE command. A dropped table is moved to the recycle bin and can be recovered
by using the FLASHBACK TABLE command. Using the PURGE option in a DROP TABLE
command removes the table permanently, meaning you can’t recover it from the recycle bin.

Review Questions
1. Which command is used to create a table based on data already contained in an existing table?
2. List four datatypes supported by Oracle, MySQL and AQL Server, and provide an example of
data that could be stored by each datatype.
3. What guidelines should you follow when naming tables and columns in Oracle, MySQL, SQL
Server?
4. How many columns can be dropped in one ALTER TABLE command?
5. What happens to the existing rows of a table if the DEFAULT value of a column is changed?
6. Explain the difference between truncating a table and deleting a table.
7. If you add a new column to an existing table, where does the column appear in relation to
existing columns?
8. What happens if you try to decrease the scale or precision of a NUMBER column to a value
less than the data already stored in the field?
9. Are a table and the data contained in the table erased from the system permanently if a DROP
TABLE command is issued on the table?

Depend on the figure below answer question 10 to question 17

9
10. Write a SQL statement to create table region, country, location, department, employee, job,
job_history, and job_grade? In other word, understand the following diagram and map the
figure into SQL statement.
11. Write a SQL statement to rename the table country to country_new?
12. Write a SQL statement to add a column region_id to the table location?
13. Write a SQL statement to add a columns ID as the first column of the table location?
14. Write a SQL statement to add a column region_id after state_province to the table location?
15. Write a SQL statement change the data type of the column country_id to integer in the table
location?
16. Write a SQL statement to drop the column city from the table location?
17. Write a SQL statement to change the name of the column state_province to state, keeping the
data type and size same? In that case, if there are no data in the table, the old column will be
removed and new column will be creating, no problem at all, but if data in the table you can
use the following statement.

10

You might also like