After creating a database in SQL, the next step is to create tables where data will be stored. SQL provides the CREATE TABLE command to define the structure of a table, including columns, data types, and constraints.
The general syntax for creating a table is:
sqlCREATE TABLE table_name ( column1 datatype constraint, column2 datatype constraint, ... );
In this syntax:
sqlCREATE TABLE employees ( employee_id INT PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, hire_date DATE, salary DECIMAL(10, 2) );
This example creates an employees table with five columns: employee_id, first_name, last_name, hire_date, and salary. The employee_id is set as the primary key.
When creating a table, you can specify constraints to enforce rules on the data. Common constraints include:
sqlCREATE TABLE departments ( department_id INT PRIMARY KEY, department_name VARCHAR(50) NOT NULL, manager_id INT UNIQUE, location_id INT, CONSTRAINT fk_manager FOREIGN KEY (manager_id) REFERENCES employees(employee_id) );
In this example, the departments table has a PRIMARY KEY on the department_id, a NOT NULL constraint on department_name, a UNIQUE constraint on manager_id, and a FOREIGN KEY linking manager_id to the employees table.
For many primary keys, especially ID fields, you may want to automatically increment the value for each new record. SQL provides an AUTO_INCREMENT feature for this purpose.
sqlCREATE TABLE projects ( project_id INT AUTO_INCREMENT PRIMARY KEY, project_name VARCHAR(100) NOT NULL );
In this example, the project_id column will automatically increase by 1 with each new project.
Temporary tables are used to store intermediate results temporarily and are automatically deleted when the session ends.
sqlCREATE TEMPORARY TABLE temp_sales ( sale_id INT, product_id INT, sale_amount DECIMAL(10, 2) );
This creates a temporary table named temp_sales that will only exist during the current session.
If you need to make changes to an existing table, such as adding or removing columns, use the ALTER TABLE command.
sqlALTER TABLE employees ADD email VARCHAR(100);
This adds an email column to the employees table.
sqlALTER TABLE employees DROP COLUMN hire_date;
This removes the hire_date column from the employees table.
If you need to delete a table permanently, you can use the DROP TABLE command.
sqlDROP TABLE employees;
This will remove the employees table and all its data.
Creating tables in SQL is a foundational task when designing a database. Understanding how to define columns, data types, and constraints is essential for ensuring data integrity. SQL provides a wide range of options for creating tables, adding constraints, using auto-incrementing columns, and modifying existing structures. Properly structured tables enable efficient querying, data retrieval, and management.
Copyrights © 2024 letsupdateskills All rights reserved