Module ll
Data Definition in SQL
DDL is an abbreviation of Data Definition Language.
The DDL Commands in Structured Query Language are used to create and
modify the schema of the database and its objects. The syntax of DDL
commands is predefined for describing the data. The commands of Data
Definition Language deal with how the data should exist in the database.
Following are the five DDL commands in SQL:
CREATE Command
DROP Command
ALTER Command
TRUNCATE Command
RENAME Command
1. The SQL CREATE
CREATE is a DDL command used to create databases, tables, triggers and other database
objects.
Syntax to Create a Database:
CREATE Database Database_Name;
Example:
Create Database Books;
Syntax to create a new table:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
2. DROP Command
DROP is a DDL command used to delete/remove the database objects from the SQL database.
We can easily remove the entire table, view, or index from the database using this DDL
command.
Syntax to remove a database:
DROP DATABASE Database_Name;
Example
DROP DATABASE Books;
Dropping of tables
The DROP TABLE statement is used to drop an existing table in a database.
Syntax
DROP TABLE table_name;
Example
DROP TABLE Shippers;
3. ALTER Command
ALTER is a DDL command which changes or modifies the existing structure of the database,
and it also changes the schema of database objects.
Modifying the structure of the tables
SQL ALTER TABLE Statement
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.
ALTER TABLE - ADD Column
To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype;
Example
ALTER TABLE Customers
ADD Email varchar(255);
ALTER TABLE - DROP COLUMN
To delete a column in a table, use the following syntax (notice that some database systems
don't allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name;
Example
ALTER TABLE Customers
DROP COLUMN Email;
ALTER TABLE - RENAME COLUMN
To rename a column in a table, use the following syntax:
ALTER TABLE table_name
RENAME COLUMN old_name to new_name;
ALTER TABLE - ALTER/MODIFY DATATYPE
To change the data type of a column in a table, use the following syntax:
SQL Server / MS Access:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
ALTER TABLE Persons
ALTER COLUMN DateOfBirth year;
My SQL / Oracle (prior version 10G):
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
4. TRUNCATE Command
TRUNCATE is another DDL command which deletes or removes all the records from the table.
This command also removes the space allocated for storing the table records.
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table
itself.
Syntax
TRUNCATE TABLE table_name;
Example
TRUNCATE TABLE Student;
5. RENAME Command
RENAME is a DDL command which is used to change the name of the database table.
Syntax of RENAME command
RENAME TABLE Old_Table_Name TO New_Table_Name
Example
RENAME TABLE Student TO Student_Details ;
Data types in sql
Data types are used to represent the nature of the data that can be stored
in the database table. For example, in a particular column of a table, if we
want to store a string type of data then we will have to declare a string data
type of this column.
Data types mainly classified into three categories for every database.
String Data types
Numeric Data types
Date and time Data types
String Data Types
CHAR(size)
A FIXED length string (can contain letters, numbers, and special
characters). The size parameter specifies the column length in characters -
can be from 0 to 255. Default is 1
VARCHAR(size)
A VARIABLE length string (can contain letters, numbers, and special
characters). The size parameter specifies the maximum string length in
characters - can be from 0 to 65535
BINARY(size)
Equal to CHAR(), but stores binary byte strings. The size parameter
specifies the column length in bytes. Default is 1
VARBINARY(size)
Equal to VARCHAR(), but stores binary byte strings. The size
parameter specifies the maximum column length in bytes.
TEXT(size)
Holds a string with a maximum length of 65,535 bytes
Numeric Data Types
INT
A medium integer. Signed range is from -2147483648 to 2147483647.
Unsigned range is from 0 to 4294967295. The size parameter specifies the
maximum display width (which is 255)
BIT(size)
A bit-value type. The number of bits per value is specified in size. The
size parameter can hold a value from 1 to 64. The default value for size is 1.
FLOAT(size, d)
A floating point number. The total number of digits is specified in size.
The number of digits after the decimal point is specified in the d parameter.
This syntax is deprecated in MySQL 8.0.17, and it will be removed in future
MySQL versions
DOUBLE(size, d)
A normal-size floating point number. The total number of digits is
specified in size. The number of digits after the decimal point is specified
in the d parameter
TINYINT(size)
A very small integer. Signed range is from -128 to 127. Unsigned range
is from 0 to 255. The size parameter specifies the maximum display width
(which is 255)
BOOL
Zero is considered as false, nonzero values are considered as true.
Date and Time Data Types
DATE
A date. Format: YYYY-MM-DD. The supported range is from '1000-01-
01' to '9999-12-31'
DATETIME(fsp)
A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The
supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
Adding DEFAULT and ON UPDATE in the column definition to get automatic
initialization and updating to the current date and time
TIME(fsp)
A time. Format: hh:mm:ss. The supported range is from '-838:59:59' to
'838:59:59'
YEAR
A year in four-digit format. Values allowed in four-digit format: 1901 to
2155, and 0000.
Insertion
The SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Selection/ Viewing
The SQL SELECT Statement
The SELECT statement is used to select data from a database. The data returned is stored in a
result table, called the result-set.
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If you
want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
Example
SELECT CustomerName, City FROM Customers;
SELECT * FROM Customers;
Updation
The SQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table.
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
Deletion of tables
The SQL DELETE Statement
The DELETE statement is used to delete existing records in a table.
DELETE Syntax
DELETE FROM table_name WHERE condition;
Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste
Data Constraints
SQL constraints are used to specify rules for data in a table.Constraints are used to limit
the type of data that can go into a table. This ensures the accuracy and reliability of the
data in the table.
Constraints can be specified when the table is created with the CREATE TABLE
statement, or after the table is created with the ALTER TABLE statement.
Constraints can be column level or table level. Column level constraints apply to a column, and
table level constraints apply to the whole table.
Constrains that control data insertion and data retrieval speed are known as I/O (Input-Output)
constraints.
Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
The following constraints are commonly used in SQL:
NOT NULL - Ensures that a column cannot have a NULL value. This enforces a field to always
contain a value
UNIQUE - Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a
table. A table can have only ONE primary key; and in the table, this primary key can consist of
single or multiple columns (fields).
FOREIGN KEY - Prevents actions that would destroy links between tables. A FOREIGN KEY is a
field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.
The table with the foreign key is called the child table, and the table with the primary key is
called the referenced or parent table.
CHECK - Ensures that the values in a column satisfies a specific condition
DEFAULT - Sets a default value for a column if no value is specified
CREATE INDEX - Used to create and retrieve data from the database very quickly.
CREATE INDEX idx_lastname ON Persons (LastName);
AUTO INCREMENT : Auto-increment allows a unique number to be generated automatically
every time a new record is inserted.
Example
CREATE TABLE Persons (
ID int NOT NULL AUTO_INCREMENT ,
LastName varchar(255) NOT NULL UNIQUE,
PersonID int,
FirstName varchar(255) NOT NULL,
Age int,
City varchar(255) DEFAULT 'Sandnes'
PRIMARY KEY (ID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID),
CHECK (Age>=18)
);
ALTER TABLE students ADD PRIMARY KEY (S_Id);
ALTER TABLE students DROP PRIMARY KEY
Difference between primary key and foreign key in SQL:
These are some important difference between primary key and foreign key in SQL-
Primary key cannot be null on the other hand foreign key can be null.
Primary key is always unique while foreign key can be duplicated.
Primary key uniquely identify a record in a table while foreign key is a field in a table that is
primary key in another table.
There is only one primary key in the table on the other hand we can have more than one foreign
key in the table.
Composite Key
A primary key that is made by the combination of more than one attribute is known as a
composite key.
CREATE TABLE SAMPLE_TABLE
(COL1 integer,
COL2 varchar(30),
COL3 varchar(50),
PRIMARY KEY (COL1, COL2));