In this blog I will show you how to use a CTAS to create a table with non-nullable columns. I have a table with the following structure (note all columns are non-nullable):

CREATE TABLE [dbo].[Date]
(
[Date] DATE NOT NULL,
[Day] INT NOT NULL,
[Week] INT NOT NULL,
[Month] INT NOT NULL,
[Quarter] INT NOT NULL,
[Year] INT NOT NULL
)
GO

If I want to create a new version of this table with an additional column called YearMonth, the easiest way to do this is using a CTAS (CREATE TABLE AS SELECT), so to do this I use the following script:

CREATE TABLE [dbo].[Date_New]
AS
SELECT
*
,CAST(CONCAT([Year],RIGHT(CONCAT(’00’,[Month]),2)) AS INT) AS [YearMonth]
FROM [dbo].[Date];

When I run this script and check the result I notice that NOT NULL has been preserved for existing columns from the original table but the new column called YearMonth is nullable:

This is not the intended behaviour, I want YearMonth as non-nullable, so to achieve this I wrap the new column in the CTAS within ISNULL:

CREATE TABLE [dbo].[Date_New]
AS
SELECT
*
,ISNULL(CAST(CONCAT([Year],RIGHT(CONCAT(’00’,[Month]),2)) AS INT),0) AS [YearMonth]
FROM [dbo].[Date];

This now creates YearMonth as a non-nullable column:

A final note: to make sure the new column is non-nullable the ISNULL must be the outermost function:
  • This does not work: CAST(ISNULL(CONCAT([Year],RIGHT(CONCAT(’00’,[Month]),2)),0) AS INT) AS [YearMonth]
  • It must be: ISNULL(CAST(CONCAT([Year],RIGHT(CONCAT(’00’,[Month]),2)) AS INT),0) AS [YearMonth]

Tags: , ,