SQL DDL Tutorial: How to Create and Manage a Database Table Using Data Definition Language Commands.

4.Modify the Customers table by adding a column to hold each customer's date of birth. This column must not be null.
ORACLE
ALTER TABLE Customers
ADD (DateOfBirth DATE NOT NULL);
MySQL, PostgreSQL, SQL Server
ALTER TABLE Customers
ADD DateOfBirth DATE NOT NULL;


5.Alter the Accounts table to change the Balance column data type so that it is large enough to hold larger numbers but still remains a non-negative value.
ORACLE
ALTER TABLE Accounts
MODIFY Balance DECIMAL(15, 2) CHECK (Balance >= 0);
MySQL and PostgreSQL
ALTER TABLE Accounts
MODIFY COLUMN Balance DECIMAL(15, 2) CHECK (Balance >= 0);
SQLServer
1. ALTER TABLE Accounts
ALTER COLUMN Balance DECIMAL(15, 2);
2. ALTER TABLE Accounts ADD CONSTRAINT Balance_Check CHECK (Balance >= 0);


6.Drop the Transactions table as it is no longer needed in the database schema.
DROP TABLE IF EXISTS Transactions;


7.Implement a unique constraint on the Email column within the Customers table so that no duplicate entries in regard to email addresses are done in the database.
ALTER TABLE Customers
ADD CONSTRAINT unique_email UNIQUE (Email);
The SQL query ensures data integrity no two customers can share the same email. This query consequently is started with the statement ALTER TABLE to make alterations to an existing table in this case Customers Table. ADD CONSTRAINT is the command to create a new rule for the table. A unique user defined name of the constraint is unique_email that is easier to find later. The keyword UNIQUE will indicate that the column Email is to have unique values and the (Email) defines the specific column affected by the constraint. Because of this when a user tries to insert a customer with an email that already exists in the table this will prompt a probable database rejection and creation of an error. It gives a guarantee that the Email column contains no duplicate values in the database.


8.Create an index on the column Phone of the table Customers so that querying by phone number becomes much faster
CREATE INDEX idx_phone ON Customers(Phone);
The query is used to create an index on phone column of customer table.
An index is a database data structure which enables quicker execution of retrieval operations on data. Once created on a column the database is able to search for records on the fly using that column's values. In the example, the CREATE INDEX statement is used to create an index named idx_phone on the column Phones of the table Customers. It can then be used or referenced anytime changes or deletions are required as the user defines a name for it, say idx_phone. In addition, indexing the Phone column will make queries filtering or searching customers by phone number much faster especially with large datasets. But on the other side indexes speed up read operations but slightly slow down write operations like INSERT, UPDATE and DELETE as the index needs to be updated anytime data in the indexed column changes.


9.Renamed Balance column in Accounts to AccountBalance to make it easier to understand.
ALTER TABLE Accounts
RENAME COLUMN Balance TO AccountBalance;
The SQL statement renamed the column Balance in the table Accounts as AccountBalance. The ALTER TABLE command changes the existing table structure. With a change in the column name this may offer better clarity about what is being stored in the column particularly in the event that the context of the table changes. This makes the database schema more readable and understandable. After this statement executes all the uses of column name in old terms would have to be replaced by AccountBalance.


10.Drop the IsActive column for the Customers table as it's no longer needed.
ALTER TABLE Customers
DROP COLUMN IsActive;
Deletes the column IsActive from the Customers table. Once this command is executed the column along with its data will permanently be deleted from that table. It can be done when a column is not required or the schema of the database needs to be simplified. Once the column is dropped, all the data stored in that column will be lost from that table and the structure of that table would no longer hold the IsActive column. That change will have an impact on all queries and operations that were referencing the column earlier.


11.Ensure that the CustomerID in the Accounts table has a foreign key constraint referencing the CustomerID in the Customers table.
ALTER TABLE Accounts
ADD CONSTRAINT fk_customer
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID);
The SQL statement creates a foreign key relationship between the Accounts table and the Customers table. The ALTER TABLE command applies here to change the existing structure of a table which in this case is the Accounts table. The query adds the constraint fk_customer which makes sure that CustomerID in Accounts refers with a valid CustomerID in Customers. So, this adds the enforcement of referential integrity meaning you can't create an account without having a CustomerID which exists in the Customers table. It also enforce the fact that if one record in the Customers table is deleted or modified corresponding modifications can be made to the Accounts table, thus maintaining integrity and preventing orphan records.


12.Alter the Accounts table so that now the table will have a composite primary key formed with the columns AccountID and CustomerID.
ALTER TABLE Accounts
ADD PRIMARY KEY (AccountID, CustomerID);
This query is used for modifying the existing accounts table structure by adding a composite primary key constraint. The primary key is a combination of columns that uniquely identify every record in a table and here it is combined AccountID and CustomerID columns. This would make the two columns together unique in the records for the Accounts table, so no row can have a duplicate pair of AccountID and CustomerID. Defining this composite primary key enforces referential integrity between the two fields for the database. This change also serves automatically to enforce that neither AccountID nor CustomerID may contain NULL values providing yet another layer of data integrity.


13.Create a table called Transactions which includes a foreign key. In this foreign key the ON DELETE CASCADE action will be applied meaning all the transactions associated with it will be deleted if the account is deleted.
CREATE TABLE Transactions (
 TransactionID INT PRIMARY KEY,
  AccountID INT,
 tDate DATE NOT NULL,
 Amount DECIMAL(10, 2) CHECK (Amount > 0),
 TransactionType VARCHAR(50) NOT NULL,
 FOREIGN KEY (AccountID) REFERENCES Accounts(AccountID) ON DELETE CASCADE );
This SQL statement creates a table named Transactions that will hold a variety of financial transaction information associated with accounts including some very important columns. The TransactionID column is unique for each of the transactions that are executed because it is a primary key. Then, there is the AccountID column which connects an account to each transaction so that a relationship exists between these two tables Accounts. tDate column stores the date of a transaction and is not null as it can't be blank. Amount column is a decimal column this column stores the amount of the transaction. Check constraint is defined over this column because this value should always be greater than zero. A column called TransactionType specifies what type of transaction it is-they might simply be "Deposit" or "Withdrawal". This, in addition is an enforcement of referential integrity with the constraint being on AccountID referencing the Accounts table. If an account is deleted ON DELETE CASCADE deletes all transactions that are associated with that account. In this way, integrity between the tables will be kept. This will aid in effective tracking of transactions while keeping data integrity.


14.To change the data type of column Phone in Customers so that more extended phone number are allowed.
ALTER TABLE Customers
MODIFY (Phone VARCHAR(20));


15.Alter the Accounts table to set a default value of 0 for the Balance column.
ALTER TABLE Accounts
ALTER COLUMN AccountBalance SET DEFAULT 0;


16.Create a view that will list all active customers based on an IsActive column.
CREATE VIEW ActiveCustomers AS
SELECT *
FROM Customers
WHERE IsActive = TRUE;
CREATE VIEW ActiveCustomers defines a view named ActiveCustomers. A view is actually a virtual table whose rows originate from the resultset of a query with which the view was defined. This view selects all columns from the 'Customers' table but only incorporates rows in which the IsActive column is set to TRUE. This way it streamlines the querying since the customers can simply refer to the 'ActiveCustomers' view instead of their writing a filter condition every time they need data on active customers. Select * FETCH ALL columns of the 'Customers' table but 'WHERE IsActive = TRUE' conditions will add only the customers with their `IsActive` status marked as 'TRUE' to this view. This gets the list of currently active customers quickly without changing the underlying table in any manner but gives a clean and convenient means of working with filtered data.


17.Drop the unique constraint on column Email in the table Customers.
ALTER TABLE Customers
DROP CONSTRAINT unique_email;
The SQL statement to drop the unique constraint named unique_email from the Customers table is found as follows within relational databases. ALTER TABLE Customers DROP CONSTRAINT unique_email; A unique constraint in a relational database is used to make sure that no two entries in the table will carry the same value in the column(s) specified. This unique_email constraint most probably enforced email address uniqueness in each row of the Customers table. This ALTER TABLE removes the uniqueness requirement from the Email column and consequently duplicate email addresses are allowed to be inserted into the table as a result of this execution. This could be useful in case that the business logic goes under the modification and it is no longer required to enforce unique email addresses for the customers.


18.Add a check constraint to the Accounts table to ensure that the balance cannot be negative.
ALTER TABLE Accounts
ADD CONSTRAINT chk_balance CHECK (AccountBalance >= 0);


19.Create a new table that defines account types, which can be referenced in the Accounts table.
CREATE TABLE AccountTypes (
AccountTypeID INT PRIMARY KEY,
AccountTypeName VARCHAR(50) NOT NULL
);


20.modify the transactions table by adding a foreign key that refers to the Accounts table.
ALTER TABLE Transactions ADD CONSTRAINT fk_account FOREIGN KEY (AccountID) REFERENCES Accounts(AccountID);
The SQL command adds a foreign key constraint to the Transactions table linking the AccountID column in the Transactions table to the AccountID column in the Accounts table. This would mean that each AccountID found in the Transactions table corresponds to an existing AccountID in the Accounts table. It thus enforces data integrity by preventing transactions from being linked to accounts that do not exist. That foreign key relationship will enforce referential integrity between the two tables meaning the data throughout both of the tables remains consistent and related. If an AccountID is deleted in the Accounts table all necessary additional actions would be handled by specific behavior set by the database such as rejecting the deletion if there are related transactions.


Previous Topic:-->>Managing indexes,synonyms and sequences || Next topic:-->>Managing Views


Other Topics for Account Management
Joins With Group by Having Equi JoinJoins with Subqueries Self Join Outer Join