How to Create Table in SQL

The CREATE TABLE statement is used to create a new table in a database. The column specifies the name of the column of the table. The datatype parameter specifies the type of data the column can hold.

CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);

Data Types in MySQL

Creating Table with Constraints

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 are used to specify rules for the data in a table.

CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);

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.

The following constraints are used in SQL:

  1. NOT NULL - Ensures that a column cannot have a NULL value
  2. UNIQUE - Ensures that all values in a column are different
  3. PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
  4. FOREIGN KEY - Uniquely identifies a row or record in another table
  5. CHECK - Ensures that all values in a column satisfies a specific condition
  6. DEFAULT - Sets a default value for a column when no value is specified
  7. INDEX - Used to create and retrieve data from the database very quickly

NOT NULL

Although SQL allows a column to contain null values, there are times when you want to be sure that a column always has a distinct value. In order for one row in a table to be distinguished from another, there must be some way of telling them apart. This is usually done with a primary key, which must have a unique value in every row. Because a null value in a column could be anything, it might match the value for that column in any of the other rows. Thus it makes sense to disallow a null value in the column that is used to distinguish one row from the rest.

UNIQUE

The NOT NULL constraint is a fairly weak constraint. You can satisfy the constraint as long as you put anything at all into the field. The UNIQUE constraint will not only disallow the entry of a null value in a column, but it will also disallow the entry of a value that matches a value already in the column.

CHECK

Use the CHECK constraint for preventing the entry of invalid data that goes beyond maintaining uniqueness. For example, you can check to make sure that a numeric value falls within an allowed range. You can also check to see that a particular character string is not entered into a column.

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive