Tables are the foundation of any relational database. They store structured data in rows and columns, defining the schema of a database. In this tutorial, we will cover how to create, modify, and manage tables in SQL using various SQL commands.
To create a table in SQL, use the CREATE TABLE statement. A table consists of columns with defined data types and constraints.
CREATE TABLE table_name (
column1 datatype constraints,
column2 datatype constraints,
...
);Creating a students table:
CREATE TABLE students (
student_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT CHECK (age >= 18),
email VARCHAR(100) UNIQUE,
enrollment_date DATE DEFAULT CURRENT_DATE
);student_id INT PRIMARY KEY: Unique identifier for each student.
name VARCHAR(50) NOT NULL: Name cannot be empty.
age INT CHECK (age >= 18): Ensures students are at least 18 years old.
email VARCHAR(100) UNIQUE: No two students can have the same email.
enrollment_date DATE DEFAULT CURRENT_DATE: Defaults to the current date if not provided.
To check the structure of a table:
DESCRIBE students; -- MySQL
PRAGMA table_info(students); -- SQLite
SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'students'; -- PostgreSQLYou can modify a table using the ALTER TABLE statement.
ALTER TABLE students ADD COLUMN phone VARCHAR(15);ALTER TABLE students ALTER COLUMN age SET DEFAULT 20; -- PostgreSQLALTER TABLE students RENAME COLUMN phone TO contact_number;ALTER TABLE students DROP COLUMN contact_number;If you need to remove a table, use the DROP TABLE statement.
DROP TABLE students;To delete all records without removing the structure:
TRUNCATE TABLE students;CREATE TABLE to define a new table with appropriate constraints.ALTER TABLE to modify existing tables.DROP TABLE to remove a table completely.TRUNCATE TABLE to delete all records but keep the table structure.With these concepts, you can effectively create and manage tables in SQL.
Sign in to join the discussion and post comments.
Sign in