Managing Tables in SQL Database Engine
Tables are the fundamental data structures in a relational database. They store data in rows and columns. Effective table management is crucial for database performance, integrity, and maintainability.
Creating Tables
Use the CREATE TABLE statement to define the structure of a new table. You specify the table name, column names, data types for each column, and any constraints.
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY IDENTITY(1,1),
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Email VARCHAR(100) UNIQUE,
RegistrationDate DATE DEFAULT GETDATE()
);
Altering Tables
The ALTER TABLE statement allows you to modify an existing table's structure. You can add, delete, or modify columns, as well as add or drop constraints.
Adding a Column
ALTER TABLE Customers
ADD PhoneNumber VARCHAR(20);
Modifying a Column
ALTER TABLE Customers
ALTER COLUMN Email VARCHAR(150);
Dropping a Column
ALTER TABLE Customers
DROP COLUMN PhoneNumber;
Adding a Constraint
ALTER TABLE Orders
ADD CONSTRAINT FK_CustomerOrder
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID);
Dropping Tables
Use the DROP TABLE statement to remove a table and all its data from the database. This action is irreversible.
DROP TABLE Customers;
Table Constraints
Constraints enforce data integrity rules:
- PRIMARY KEY: Uniquely identifies each row in a table. Cannot contain NULL values.
- FOREIGN KEY: Enforces referential integrity between two tables. Links a column in one table to a primary key in another.
- UNIQUE: Ensures that all values in a column are different.
- NOT NULL: Ensures that a column cannot have a NULL value.
- CHECK: Ensures that all values in a column satisfy a specific condition.
- DEFAULT: Sets a default value for a column when no value is specified.
Key Table Management Concepts
Data Types
Choosing appropriate data types (e.g., INT, VARCHAR, DATE, DECIMAL) is critical for efficient storage and data accuracy.
Indexing
Indexes improve the speed of data retrieval operations. Consider creating indexes on columns that are frequently used in WHERE clauses or JOIN conditions.
Normalization
Database normalization is a design process that organizes data to minimize redundancy and improve data integrity. Understanding normal forms (1NF, 2NF, 3NF) is important for good table design.
Common Table Operations
| Operation | Description | SQL Statement |
|---|---|---|
| Create Table | Defines a new table structure. | CREATE TABLE |
| Add Column | Adds a new column to an existing table. | ALTER TABLE ADD COLUMN |
| Delete Column | Removes a column from a table. | ALTER TABLE DROP COLUMN |
| Drop Table | Deletes a table and all its data. | DROP TABLE |
| Truncate Table | Removes all rows from a table quickly, but keeps the table structure. | TRUNCATE TABLE |