In this section, we will explore how to create tables using Structured Query Language (SQL). A table is a fundamental component of relational databases, used to store and organize data. Understanding how to create tables is essential for any developer working with SQL databases.
By the end of this tutorial, you should be able to:
The CREATE TABLE statement is used to create a new table in a database. The basic syntax is as follows:
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
...
);
Data types define the kind of data that can be stored in a column. Common data types include:
INT or INTEGER: For integer values.VARCHAR(n) or CHAR(n): For variable-length or fixed-length character strings, respectively.DATE: For date values.BOOLEAN: For true/false values.Let's create a simple table named employees with the following columns:
id (integer)first_name (string)last_name (string)email (string)hire_date (date)CREATE TABLE employees (
id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100),
hire_date DATE
);
Constraints are used to enforce rules on the data in a table. Common constraints include:
Let's modify the employees table to include constraints:
CREATE TABLE employees (
id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
hire_date DATE NOT NULL
);
In some databases, you can use the AUTO_INCREMENT attribute to automatically generate a unique value for each new record.
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
hire_date DATE NOT NULL
);
You can set default values for columns using the DEFAULT keyword.
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
hire_date DATE DEFAULT CURRENT_DATE
);
Let's create a more complex table for an e-commerce application. We'll create a products table with the following columns:
product_idnamedescriptionpricecategory_idcreated_atCREATE TABLE products (
product_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
description TEXT,
price DECIMAL(10, 2) NOT NULL,
category_id INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (category_id) REFERENCES categories(category_id)
);
In this example, the products table has a foreign key constraint linking to a categories table, ensuring referential integrity.
Creating tables is a foundational skill in SQL & Databases. By understanding the syntax, data types, and constraints, you can effectively design and manage relational databases. Practice creating tables with different schemas to reinforce your learning.
In the next section, we will explore how to insert data into these tables and perform basic queries. Stay tuned!