Description
The SQL keyword TABLE is used together with other keywords to perform operations on a table.
Keyword | Description |
CREATE TABLE | Creates a new table. |
ALTER TABLE | Alters an existing table definition. |
DROP TABLE | Deletes a table permanently from a database. |
TRUNCATE TABLE | Deletes all the data from a table, leaving the table structure as is. |
CREATE TABLE
The below SQL creates a new table with the structure defined.
CREATE TABLE users (
user_id INT,
user_name VARCHAR(255),
address VARCHAR(255),
city VARCHAR(255)
);
CREATE TABLE Using Another Table
The below SQL creates a new table "test_users" by copying the records from the "users" table, but only specific columns.
CREATE TABLE test_users AS
SELECT user_id, user_name
FROM users;
ALTER TABLE
The ALTER TABLE keyword adds, deletes, or modifies a table definition, which includes changes to columns, constraints, etc.,
The below SQL adds a new column to a table.
ALTER TABLE users
ADD email VARCHAR(255);
The below SQL deletes an existing column from a table.
ALTER TABLE users
DROP COLUMN email;
DROP TABLE
The below SQL deletes a table permanently from a database, which cannot be reverted.
DROP TABLE users;
TRUNCATE TABLE
The below SQL deletes all the data from a table, leaving the table structure as is, which makes it an empty table.
TRUNCATE TABLE users;