I have a column Column
which is declared to be NULL DEFAULT(GETUTCDATE())
and there's a non-clustered index that includes this column. I want to change this column to be NOT NULL DEFAULT(GETUTCDATE())
and when I run ALTER TABLE ALTER COLUMN
statement the SQL Azure service says it cannot change the column because there's an index depending on this column.
That's a production database and the table holds about ten million records. So I'd rather not drop and recreate the index because that would slow down the database (especially creating the index can take minutes).
How can I change the column without recreating the index?
Next, we will change amount column from null to not null, using ALTER TABLE statement. Here is the syntax for it. Replace table_name, col_name and data_type with table name, column name and data type respectively. Here’s the SQL query to change amount column from NULL to NOT NULL.
You can change NOT NULL constraint column to contain NULL values by: alter table table_name modify column_name null; After this modification, the column can contain null values. In Oracle, not null constraints are created automatically when not null is specified for a column.
You will see that columns amount and order_date contain NO value for NULL column indicating that they are not permitted to store NULL values. Ubiq makes it easy to visualize data, and monitor them in real-time dashboards. Try Ubiq for free. Ubiq is a powerful dashboard & reporting platform.
Prevents the column from containing null values. The default-clause must also be specified (SQLSTATE 42601). Specifies NULL as the default for the column. If NOT NULL was specified, DEFAULT NULL must not be specified within the same column definition. Or you could alter the column data type with a not null after the data type.
Table column does not have to be altered to enforce NOT NULL. Instead a new constraint can be added to the table:
ALTER TABLE [Table] WITH CHECK
ADD CONSTRAINT [TableColumnNotNull] CHECK ([Column] Is NOT NULL);
That would not affect the index but the optimizer would use this constraint to improve performance:
CREATE TABLE Test (ID bigint PRIMARY KEY, [Column] DATE NULL DEFAULT(GETUTCDATE()));
GO --< Create test table
CREATE NONCLUSTERED INDEX TestColumnIdx ON Test ([Column]);
GO --< Create the index
ALTER TABLE Test ALTER COLUMN [Column] DATE NOT NULL;
GO --< That won't work: the index 'TestColumnIdx' is dependent on column 'Column'
Select * From Test Where [Column] Is NULL;
GO --< Check the plan: it has "Index Seek (NonClustered)"
ALTER TABLE Test WITH CHECK ADD CONSTRAINT TestColumnNotNull CHECK ([Column] Is NOT NULL);
GO --< Add a "stand-alone" NOT NULL constraint
Select * From Test Where [Column] Is NULL;
GO --< Check the plan: it has "Constant Scan" now
DROP TABLE Test;
GO --< Clean-up
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With