To create a table in SQL, you use the CREATE TABLE
statement, which defines the name of the table and its columns. Each column is specified with a name and a data type, which indicates what kind of data can be stored in that column, such as integers, text, or dates. The basic syntax for this command includes the table name followed by a list of columns defined in parentheses. For example, if you want to create a table called employees
, you might write something like this:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
hire_date DATE,
salary DECIMAL(10, 2)
);
In this example, we define four columns: id
, name
, hire_date
, and salary
. The column id
is of type INT
and is marked as the primary key, meaning it must be unique for each entry and cannot be null. The name
column is a variable character string with a maximum length of 100 characters. The hire_date
column stores dates, and the salary
column is a decimal number that can accommodate up to 10 digits, with 2 decimal places.
Once you execute the CREATE TABLE
statement, the table will be created in the specified database, and you can start inserting data into it using the INSERT INTO
statement. It’s also essential to ensure that the table structure meets your application requirements, including setting constraints like NOT NULL
for mandatory fields or establishing foreign key relationships between tables where applicable. Proper planning of the table schema will help maintain data integrity and improve query performance in your database.