In this unit, we will delve into the specifics of creating and modifying tables in SQL. Tables are the primary structures where data is stored in relational databases. Understanding how to create, modify, and delete tables is crucial for anyone working with databases.
The CREATE TABLE
statement is used to create a new table in a database. The syntax for creating a table is as follows:
CREATE TABLE table_name ( column1 datatype, column2 datatype, column3 datatype, .... );
Each column in the table is specified with a name (e.g., column1) and a datatype (e.g., INT, DATE, VARCHAR), which defines the type of data that column can hold.
Once a table is created, you may need to modify it. The ALTER TABLE
statement is used to add, delete/drop or modify columns in an existing table. It is also used to add and drop various constraints on an existing table.
To add a column:
ALTER TABLE table_name ADD column_name datatype;
To delete a column:
ALTER TABLE table_name DROP COLUMN column_name;
To modify the data type of a column:
ALTER TABLE table_name MODIFY column_name column_type;
The DROP TABLE
statement is used to drop an existing table in a database. Be careful with this statement! Once a table is deleted, all the information available in the table is lost.
DROP TABLE table_name;
Constraints are used to specify rules for the 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. If there is any violation between the constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
PRIMARY KEY
: Uniquely identifies each record in a table.FOREIGN KEY
: Uniquely identifies a record in another table.NOT NULL
: Ensures that a column cannot have a NULL value.UNIQUE
: Ensures that all values in a column are different.CHECK
: Ensures that all values in a column satisfy certain conditions.By understanding these commands and constraints, you can effectively manage your tables in SQL, ensuring that your data is organized, consistent, and reliable.