DEV Community

Jarvish John
Jarvish John

Posted on

Alter Tables

1. You have a table customers with a column email that currently allows NULL values. Modify the table so that future entries must always have an email.

The email column in the customers table currently allows NULL values. To ensure every new record has an email, we modify the column and set it to NOT NULL. This prevents future entries from leaving it empty.

2. In the users table, ensure that the username column is unique across all records using an ALTER statement.

To avoid duplicate usernames, we update the users table by adding a UNIQUE constraint on the username column. This guarantees that each username is distinct across all records.

3. In the products table, enforce that price must always be greater than 0 using an ALTER command.

We modify the products table by adding a CHECK constraint on the price column. This ensures that every product must have a price greater than 0.

4. Modify the orders table so that the status column defaults to 'pending' if no value is provided during insertion.

In the orders table, we set a default value for the status column as 'pending'. This means if no status is provided during insertion, it will automatically be assigned 'pending'.

5. Alter the employees table by adding a new column salary such that It cannot be NULL. It must always be greater than 10,000.

We add a new column salary to the employees table. This column is set to not null and also includes a check constraint to ensure the salary is always greater than 10,000.

6. Modify the foreign key constraint between employees and departments so that when a department is deleted, all related employees are automatically removed.

We modify the foreign key relationship between employees and departments. By adding on delete cascade, when a department is deleted, all employees linked to that department are automatically removed as well.

7. In the accounts table, remove an existing CHECK constraint that enforces balance >= 0.

We remove an existing CHECK constraint on the balance column in the accounts table. This means the condition (like balance ≥ 0) is no longer enforced.

8. In the payments table, ensure that the combination of user_id and transaction_id is unique using an ALTER TABLE statement.
In the payments table, we add a composite UNIQUE constraint on (user_id, transaction_id). This ensures that the same combination cannot appear more than once.

Top comments (0)