Create MySQL Table

How to create a Mysql Database table?

Explanation

Creating MySQL tables :


Once you have selected the database, we can start create mysql table. The CREATE statement is used to creating mysql table with constraint. A Constraint is restriction to the behavior of a variable.

The Create syntax is


CREATE TABLE tableName
(
fieldName1 dataType(size) [NULL | NOT NULL]
fieldName2 dataType(size) [NULL | NOT NULL]
);
If NULL is specified, the field is allowed to be left empty. If NOT NULL is specified, the field must be given a value. In the absence of either a NULL or NOT NULL, NULL is assumed.
The below example query will help you in create mysql table:

Example :

CREATE TABLE student
(
studID INT(5),
name VARCHAR(30),
);
The above query will creating mysql table student with fields ID and Name.

PRIMARY KEY :


A PRIMARY KEY is a field in a table that uniquely identifies a record. This attribute is used to define the field name to create a primary key.

Example :


fieldName INT UNSIGNED AUTO_INCREMENT PRIMARY KEY
The PRIMARY KEY is specified after defining the fields in the below example:

Example

CREATE TABLE student
(
studID INT UNSIGNED AUTO_INCREMENT,
name VARCHAR(30),
PRIMARY KEY(studID)
);
We can also create a compound primary key. A compound primary key is where more than one field is used to uniquely identify a record.
Lets create a table for holding student details in a class.
mysql> create table student(studid int(10), name varchar(20), address varchar(40), phone int(10));

Query OK, 0 rows affected (0.05 sec)

Ask Questions

Ask Question