DB Ex3
DB Ex3
Data Definition Language (DDL) or Schema Definition Language, statements are used to define
the database structure or schema.
These statements handle the design and storage of database objects.
CREATE:
CREATE DATABASE:
The CREATE DATABASE statement is used to create a new SQL database.
Syntax
CREATE DATABASE databasename;
Example
The following SQL statement creates a database called "testDB":
CREATE TABLE:
The CREATE TABLE statement is used to create a new table in a database.
Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g. varchar,
integer, date, etc.).
Example
The following example creates a table called "Persons" that contains five columns: PersonID,
LastName, FirstName, Address, and City:
Example:
Describe persons;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| PersonID | int | YES | | NULL | |
| LastName | varchar(255)| YES | | NULL | |
| Firstname| varchar(255)| YES | | NULL | |
| Address | varchar(255)| YES | | NULL | |
| City | varchar(25) | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
Field indicates the column name, Type is the data type for the column, NULL indicates whether
the column can contain NULL values, Key indicates whether the column is indexed, and Default
specifies the column's default value. Extra displays special information about columns:
ALTER TABLE:
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing
table.
Example:
The following SQL adds an "Email" column to the "Persons" table:
ALTER TABLE Persons
ADD Email varchar(255);
Example:
The following SQL deletes the "Email" column from the "Persons" table:
ALTER TABLE Persons
DROP COLUMN Email;
TRUNCATE:
It is used to delete all the rows from the table and free the space containing the table.
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE Persons;
Example
The following SQL statement drops the existing table "Person":
DROP TABLE Person;