Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>Syntax:</h2> <pre><code>ALTER TABLE {TABLENAME} ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE} WITH VALUES </code></pre> <h2>Example:</h2> <pre><code>ALTER TABLE SomeTable ADD SomeCol Bit NULL --Or NOT NULL. CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogenerated. DEFAULT (0)--Optional Default-Constraint. WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records. </code></pre> <h2>Notes:</h2> <p><strong>Optional Constraint Name:</strong><br /> If you leave out <code>CONSTRAINT D_SomeTable_SomeCol</code> then SQL Server will autogenerate<br /> &nbsp; &nbsp; a Default-Contraint with a funny Name like: <code>DF__SomeTa__SomeC__4FB7FEF6</code><br /></p> <p><strong>Optional With-Values Statement:</strong><br /> The <code>WITH VALUES</code> is only needed when your Column is Nullable<br /> &nbsp; &nbsp; and you want the Default Value used for Existing Records.<br /> If your Column is <code>NOT NULL</code>, then it will automatically use the Default Value<br /> &nbsp; &nbsp; for all Existing Records, whether you specify <code>WITH VALUES</code> or not.</p> <p><strong>How Inserts work with a Default-Constraint:</strong><br /> If you insert a Record into <code>SomeTable</code> and do <strong><em>not</em></strong> Specify <code>SomeCol</code>'s value, then it will Default to <code>0</code>.<br /> If you insert a Record <strong><em>and</em></strong> Specify <code>SomeCol</code>'s value as <code>NULL</code> (and your column allows nulls),<br /> &nbsp; &nbsp; then the Default-Constraint will <strong><em>not</em></strong> be used and <code>NULL</code> will be inserted as the Value.<br /></p> <p>Notes were based on everyone's great feedback below.<br /> Special Thanks to:<br /> &nbsp; &nbsp; @Yatrix, @WalterStabosz, @YahooSerious, and @StackMan for their Comments.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload