SQL Create Table
How to CREATE TABLE in SQL?
CREATE TABLE used to create a new table within a database.
It specifies the columns, their data types, and any constraints on those columns.
Syntax:
Let's see the syntax how you can create a new table.
CREATE TABLE table_name (
column1 datatype1,
column2 datatype2,
...
PRIMARY KEY (one_or_more_columns) -- Optional
);
- table_name: The name of the new table.
- column1, column2, ...: The columns of the table along with their data types.
- PRIMARY KEY: Optional. Specifies the primary key for the table.
Example:
The below it explain with example how to creating a table named students with columns student_id, first_name, last_name, and age.
CREATE TABLE students (
student_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
age INT
);
In this example, we are creating a table named students with columns student_id, first_name, last_name, and age. The student_id column is defined as an integer and set as the primary key for the table.
Additional Options:
Constraints:
You can add constraints to your columns, such as NOT NULL, UNIQUE, and DEFAULT. For example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE,
hire_date DATE DEFAULT CURRENT_DATE
);
In this example, first_name and last_name are marked as NOT NULL, email is marked as UNIQUE, and hire_date has a default value set to the current date.
Foreign Key:
You can define a foreign key relationship between tables:
CREATE TABLE orders (
order_id INT PRIMARY KEY,
product_id INT,
quantity INT,
FOREIGN KEY (product_id) REFERENCES products(product_id)
);
In this example, the product_id column in the orders table is a foreign key referencing the product_id column in the products table.
Tips:
- Choose meaningful and descriptive names for tables and columns.
- Consider adding constraints to ensure data integrity.
- Define appropriate data types for each column based on the nature of the data.