codegurukool.com · Free coding tutorials & online compiler

Home › SQL Tutorial › SQL CREATE TABLE and constraints

SQL CREATE TABLE and constraints

Define a table and its rules.

Constraints keep data valid: NOT NULL, UNIQUE, PRIMARY KEY (unique row id), FOREIGN KEY (link to another table), CHECK and DEFAULT. AUTO_INCREMENT numbers new rows for you (MySQL). Remove a table with DROP TABLE and change it with ALTER TABLE.

Example code

CREATE TABLE Products (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(50) NOT NULL UNIQUE,
  price DECIMAL(8,2) CHECK (price >= 0),
  stock INT DEFAULT 0
);

ALTER TABLE Products ADD brand VARCHAR(30);

Run this code in the online editor

← SQL EXISTS, ANY and ALLSQL indexes, dates and views →