How to add a column in Microsoft SQL server

The examples in this post are for MSSQL (Microsoft SQL server) but they will likely work with most other databases. If we have the following Table:

CREATE TABLE SomeTable(
  Id INT IDENTITY(1,1) PRIMARY KEY,
  SomeText VARCHAR(MAX) NOT NULL
)

Which is a simple table with an INT as an Id and primary key and a VARCHAR(MAX) Column with some text. If we wish to add a column with a DateTime we can run the following query:

ALTER TABLE [dbo].[SomeTable]
   ADD CreationTime DATETIME2 NULL DEFAULT NULL

The above alters the table and adds a column called CreationTime with the type DATETIME2. It defines the column as being nullable and sets the DEFAULT value to NULL. If we want the column to be auto filled with a date we can run the following query instead:

ALTER TABLE [dbo].[SomeTable]
   ADD CreationTime DATETIME2 NOT NULL DEFAULT GETDATE()

The above creates the new column as not nullable and instead assigns the current time as the DateTime.

That is all

I hope you found this helpful and please leave a comment down below with your thoughts!