Show List

Creating and altering database tables

Creating tables in a relational database is an essential part of setting up a database. Tables are used to store data in a structured way, with each table consisting of columns (also known as fields or attributes) and rows (also known as records or tuples).

Here is an example of how to create a table in SQL:

sql
Copy code
CREATE TABLE customers ( customer_id INT PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(255) NOT NULL, date_of_birth DATE NOT NULL );

In this example, the CREATE TABLE statement is used to create a table called customers. The table has five columns: customer_id, first_name, last_name, email, and date_of_birth. The INT and VARCHAR keywords are used to specify the data type of each column, and the NOT NULL constraint ensures that the values in these columns cannot be empty. The customer_id column is defined as the primary key, which means that it must be unique for each row in the table and is used to identify individual rows.

Altering tables in a relational database is also an important task. It involves modifying the structure of an existing table to add, remove, or modify columns, or to add or remove constraints.

Here is an example of how to add a new column to an existing table in SQL:

sql
Copy code
ALTER TABLE customers ADD address VARCHAR(255) NOT NULL;

In this example, the ALTER TABLE statement is used to add a new column called address to the customers table. The VARCHAR data type is used to define the column as a string data type, and the NOT NULL constraint ensures that the values in this column cannot be empty.

It's important to note that altering a table can have significant impacts on the data stored in the table, so it's important to understand the consequences of making changes and to have a backup of the data before making any changes.


    Leave a Comment


  • captcha text