{"id":3563,"date":"2012-12-26T14:47:06","date_gmt":"2012-12-26T14:47:06","guid":{"rendered":"http:\/\/craftydba.com\/?p=3563"},"modified":"2012-12-26T16:12:23","modified_gmt":"2012-12-26T16:12:23","slug":"basic-training-default-constraint","status":"publish","type":"post","link":"https:\/\/craftydba.com\/?p=3563","title":{"rendered":"Basic Training &#8211; Default Constraint"},"content":{"rendered":"<p><a href=\"https:\/\/craftydba.com\/wp-content\/uploads\/2012\/08\/boot-camp.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/craftydba.com\/wp-content\/uploads\/2012\/08\/boot-camp-150x150.jpg\" alt=\"\" title=\"boot-camp\" width=\"150\" height=\"150\" class=\"alignleft size-thumbnail wp-image-2575\" \/><\/a>Today, I continuing my series of talks on fundamental SQL Server database topics.  I am a proud United States Army Reservist (<a href=\"http:\/\/en.wikipedia.org\/wiki\/United_States_Army_Reserve\">USAR<\/a>) Veteran.  Just like boot camp I went to so long ago, I am going nick name the series <a href=\"http:\/\/en.wikipedia.org\/wiki\/United_States_Army_Basic_Training\">BASIC TRAINING<\/a>.<\/p>\n<p>In my last article, I was talking about how to ADD, ALTER and DROP columns using the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms190273%28v=sql.110%29.aspx\">ALTER TABLE<\/a> statement.  One problem that we faced was how to add a column with a NOT NULL clause to an existing table that contained data.  I will be introducing the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms187083%28v=sql.105%29.aspx\">DEFAULT<\/a> constraint which can be used to solve this problem.<\/p>\n<p>We are going to build upon the sample database named [TRAINING] containing a schema named [PUBS] and a table named [PUBLISHERS].  As a database developer, one should always check the existence of an object before dropping it.  That way, the drop statement will not fail.  <\/p>\n<p>The code snippet below drops the column if it exists.<\/p>\n<pre><span style=\"color: #008000; font-size: small;\">-- Remove column if it exists\r\nIF EXISTS (\r\n    SELECT * FROM sys.objects o join sys.columns c ON o.object_id = c.object_id\r\n    WHERE o.name = 'PUBLISHERS' and o.type = 'U' and c.name = 'zip'\r\n)\r\nALTER TABLE [PUBS].[PUBLISHERS] DROP COLUMN zip;\r\nGO\r\n\r\n<\/span><\/pre>\n<p>Please note that every user table exists in the &#8216;sys.objects&#8217; system view and every column of that table exists in the &#8216;sys.columns&#8217; system view.  By joining the tables and selecting on the appropriate names, we can determine the existence of the column.<\/p>\n<p>There are two ways to add a constraint: unnamed and named.  The code snippet below adds a unnamed default constraint.  <\/p>\n<pre><span style=\"color: #008000; font-size: small;\">-- Add constraint w\/o name\r\nALTER TABLE [PUBS].[PUBLISHERS]\r\nADD zip char(5) NOT NULL DEFAULT('02910');\r\nGO\r\n\r\n<\/span><\/pre>\n<p>The system creates a unique name for this constraint based upon the table name, column name, and a random hex string.<\/p>\n<p>Let&#8217;s drop this column so that I can demonstrate how to create a named constraint.  We can see below that this failed due to the DEFAULT constraint.<\/p>\n<p><a href=\"https:\/\/craftydba.com\/wp-content\/uploads\/2012\/12\/basic-training-default1.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/craftydba.com\/wp-content\/uploads\/2012\/12\/basic-training-default1.jpg\" alt=\"\" title=\"basic-training-default1\" width=\"930\" height=\"207\" class=\"aligncenter size-full wp-image-3573\" \/><\/a><\/p>\n<pre>&nbsp;<\/pre>\n<p>To successfully drop the column, we need to drop the constraint first.<\/p>\n<p><a href=\"https:\/\/craftydba.com\/wp-content\/uploads\/2012\/12\/basic-training-default21.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/craftydba.com\/wp-content\/uploads\/2012\/12\/basic-training-default21.jpg\" alt=\"\" title=\"basic-training-default2\" width=\"951\" height=\"167\" class=\"aligncenter size-full wp-image-3574\" \/><\/a><\/p>\n<pre>&nbsp;<\/pre>\n<p>Let&#8217;s repeat this process by adding back the DEFAULT constraint with a name of DF_LOCAL_ZIP.<\/p>\n<p><a href=\"https:\/\/craftydba.com\/wp-content\/uploads\/2012\/12\/basic-training-default3.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/craftydba.com\/wp-content\/uploads\/2012\/12\/basic-training-default3.jpg\" alt=\"\" title=\"basic-training-default3\" width=\"1009\" height=\"233\" class=\"aligncenter size-full wp-image-3575\" \/><\/a><\/p>\n<p>If you query the table named [PUBLISHERS], you will noticed that the new field has a default zip code of &#8216;02910&#8217;.  Just what we want.<\/p>\n<p>This is due to the fact that we added the new COLUMN and DEFAULT constraint at the same time.  If we did it in two separate steps, with a allow NULL clause on the column, we would end up with NULL values in the zip column.  See code examples at end of article.  <\/p>\n<p>This is where the WITH VALUES clause comes into play.  It has to be specified with the ADD column sub-command inside a ALTER TABLE statement.  In short, it will fill in a column that allows NULLS with the default value.<\/p>\n<pre><span style=\"color: #008000; font-size: small;\">-- Add constraint with name, with values clause\r\nALTER TABLE [PUBS].[PUBLISHERS]\r\nADD zip char(5) NOT NULL CONSTRAINT DF_LOCAL_ZIP DEFAULT('02910') WITH VALUES;\r\nGO\r\n\r\n<\/span><\/pre>\n<p>In summary, I started introducing the four <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms188066.aspx\">table constraints<\/a> that can be used to add data integrity to a database design.  <\/p>\n<p>The DEFAULT constraint allows you want to add a NOT NULL column to an existing table.  The constraint inserts a default value into a COLUMN when no value is supplied.  I use DEFAULT constraints when creating tables so that I can have two audit columns at the end of a table:  who inserted the record <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms174427.aspx\">SUSER_SNAME()<\/a> and when it was inserted <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms188383\">GETDATE()<\/a>.  <\/p>\n<p>Note, you can just ADD or DROP constraints.  There is no ALTER clause.  Next time, I will be talking about <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms188066.aspx\">PRIMARY KEY<\/a> constraints.<\/p>\n<p><a href='https:\/\/craftydba.com\/wp-content\/uploads\/2012\/12\/basic-training-default.sql_.txt'>Default Examples<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Today, I continuing my series of talks on fundamental SQL Server database topics. I am a proud United States Army Reservist (USAR) Veteran. Just like boot camp I went to so long ago, I am going nick name the series BASIC TRAINING. In my last article, I was talking about how to ADD, ALTER and DROP columns using the ALTER TABLE statement. One problem that we faced was how to add a column with a NOT NULL clause to an existing table that contained data. I will be introducing the&hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[684,77,64,31,687,685,78,12,15,679,680,29,688],"class_list":["post-3563","post","type-post","status-publish","format-standard","hentry","category-db-dev","tag-add-column","tag-add-constraint","tag-alter-table","tag-database-developer","tag-default","tag-drop-column","tag-drop-constraint","tag-free-code","tag-john-f-miner-iii","tag-not-null","tag-null","tag-tsql","tag-with-values"],"_links":{"self":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/posts\/3563","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=3563"}],"version-history":[{"count":0,"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/posts\/3563\/revisions"}],"wp:attachment":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=3563"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=3563"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=3563"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}