22

I'm about ready to rip my hair out on this one. I'm fairly new to MS SQL, and haven't seen a similar post anywhere.

When I try to do a statement like this:

INSERT INTO qcRawMatTestCharacteristic 
VALUES(NULL, 1,1,1,1,1,1,1,'','','', GETDATE(), 1)

I get the following:

Cannot insert the value NULL into column 'iRawMatTestCharacteristicId', table 'Intranet.dbo.qcRawMatTestCharacteristic'; column does not allow nulls. INSERT fails.

I understand the error, but the null value is for my my primary field with an int data type.

Any ideas!?

A-K
  • 16,804
  • 8
  • 54
  • 74
Nick
  • 257
  • 1
  • 2
  • 5
  • 2
    Okay I should clarify. I JUST WANT AN AUTO-INCREMENTING PRIMARY KEY. In MySQL a NULL value will give me this effect. If I use the same INSERT statement as above, specify my fields and leave off the primary key. I get the SAME error. – Nick Oct 06 '10 at 21:07
  • 1
    @Nick: that column in SQL Server must be defined as an `INT IDENTITY` for this to work. Key is the `IDENTITY` part - you need to have that defined on your PK column, otherwise it won't work – marc_s Oct 06 '10 at 21:16
  • I got it now guys. Thanks a lot. I'm aware of how relational databases work. But you answered my MS SQL question. :) – Nick Oct 06 '10 at 21:23
  • @Nick: ok, glad we could help. SQL is standardized..... to a degree :-) Beyond that are obviously more or less subtle differences :-) – marc_s Oct 06 '10 at 21:25
  • @Conrad I know you posted before me but I thought you updated your post after me. I can't see the timestamp. I'm just kidding around either way. – Spencer Ruport Oct 07 '10 at 22:12

8 Answers8

54

Primary keys in any relational database are not allowed to be NULL - it's one of the main, fundamental characteristics of a primary key.

See: SQL by Design: how to Choose the primary key

Never Null
No primary key value can be null, nor can you do anything to render the primary key null. This is an inviolate rule of the relational model as supported by ANSI, of relational database management system (RDBMS) design, and of SQL Server.

UPDATE: ok, so you want an "auto-increment" primary key in SQL Server.

You need to define it as an INT IDENTITY in your CREATE TABLE statement:

 CREATE TABLE dbo.YourTable(ID INT IDENTITY, col1 INT, ..., colN INT)

and then when you do an INSERT, you need to explicitly specify the columns to insert, but just don't specify the "ID" column in that list - then SQL Server will handle finding the proper value automagically:

 INSERT INTO dbo.YourTable(col1, col2, ..., colN) -- anything **except** `ID`      
 VALUES(va1l, val2, ..., valN)

If you want to do this after having created the table already, you can do so in the SQL Server Management Studio's table designer:

alt text

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 3
    +1 (definite answer). For completeness sake: `unique` keys *can* generally contain `null` values (`primary` can't). – ChristopheD Oct 06 '10 at 20:59
  • 6
    @Nick: shame on MySQL ! This clearly violates ANSI rules on the relational model – marc_s Oct 06 '10 at 21:00
  • 2
    @Nick & @Marc - That doesn't make any sense. If you truly have a primary key and MySQL allows you to insert null values, then you have defeated the point of a primary key. That means you could insert multiple rows with all null values with no way of uniquely identifying each one. I wonder if in MySQL the null gets ignored and it autoincrements. It's like saying you'll give the same ID Number to two people. How will you ID them? – Nelson Rothermel Oct 06 '10 at 21:11
  • @Nelson: it seems that inserting a NULL value into the PK column in MySQL will trigger an "auto-numbering" scheme. Rather strange behavior in my opinion........ – marc_s Oct 06 '10 at 21:13
  • @marc - Then there's the InterBase/Firebird way, `... VALUES (GEN_ID(SOMEID, 1), "another val"`. Decouples the ID generating from the table which can be good and bad. It's good because you can use it for other purposes in your stored procedures. – Nelson Rothermel Oct 06 '10 at 21:27
  • 1
    As your example shows, it is *always* a good idea to specify the insert column names. – aaaa bbbb Oct 06 '10 at 22:00
  • @Nick, concerning "Not true, MySQL does". Can you comment please on comment to http://stackoverflow.com/questions/3906811/null-permitted-in-primary-key-why-and-in-which-dbms , affirming that PK in MySQL cannot be NULL? – Gennady Vanin Геннадий Ванин Oct 11 '10 at 14:36
  • 1
    @Nelson Rothermal I don't see why you shouldn't have an option to have a Null value as a valid primary key value. Paradox allows this. The primary key can still be unique - you can have a Null key field value and still not allow a duplicate key... Treat Null as just another value. – user610064 Dec 21 '12 at 16:37
  • @user610064: Allowing one null value would be fine. Multiple null values would be a problem and I was alluding to that, though I don't remember what I was thinking at the time and why I assumed you would have multiple nulls. Oh well... – Nelson Rothermel Feb 19 '13 at 20:37
  • 1
    This got me nearly all the way, I couldn't change the Identity Specification in SSMS, believe this was because the PK column was set to "unique identifier". Had to create a new column and delete the old PK (http://stackoverflow.com/questions/4446596/unable-to-change-identity-specification-to-yes-in-sql-server-table) then it worked perfectly. – jonnow Apr 20 '17 at 09:15
  • @jonnow: yes, the `IDENTITY` is *only* available to `int` or `bigint` datatypes – marc_s Apr 20 '17 at 10:28
9

Primary Key fields cannot contain null values in MS SQL. If you want to populate a SQL table and dont know what to enter for a integer based primary key field then set the pk to an Identity field. Also when specifying Insert statements its wise to use the column mapping portion of the insert statment for example:

Insert into (field1, field2, field3)
values
(value1, value2, value3)

The reason for this is it insures that the column order is what you developed for as a SQL administrator can modify column order. It also allows you to insert a row with an identity Primary key with out specifying the value of the Primary Key Example

CREATE TABLE [dbo].[foo](
    [fooid] [int] IDENTITY(1,1) NOT NULL,
    [name] [varchar](50) NULL,
 CONSTRAINT [PK_foo] PRIMARY KEY
(
        [fooid] ASC
)

now my insert statement is simple

Insert into foo (name)
values
("John")

the result in the table would be

1, "John"
John Hartsock
  • 85,422
  • 23
  • 131
  • 146
4

You probably don't have (you forgot to add) autoincrement set on your integer primary key.

Alin Purcaru
  • 43,655
  • 12
  • 77
  • 90
3

Primary keys shouldnt accept null value.Why you are inserting null values to a primary key field ?Primary key field should have a non-nullable,unique value which will make each of your record in the table unique

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • For an auto-increment, even if I leave the null out of the insert arguements. I get the same error. – Nick Oct 06 '10 at 21:04
2

you can use 0 instead of null for only 1 unique row, null is not possible for PK. Or you can omit PK and use and auto increament PK field

sirmak
  • 3,749
  • 4
  • 30
  • 34
2

Assuming you have an autoincrement field for your primary Key you'll need to include the field list on your insert and not put a value for that field e.g.

INSERT INTO qcRawMatTestCharacteristic 
(Answer1,Answer2,...SomeDateField)
VALUES(1,1,1,1,1,1,1,'','','', GETDATE(), 1)
Conrad Frix
  • 51,984
  • 12
  • 96
  • 155
2

I'm assuming your real issue is that you're not sure how to write an insert statement so that the PK is auto populated correct? You need to name the fields you're setting values for, it looks like you're trying to set all of them but just exclude the PK field like so:

INSERT INTO someTable
(fieldName1, fieldName2) 
VALUES(1,1)

Where sometable is a table with three fields. PK, fieldName1, and fieldName2. You also need to make sure that the identity property on the PK field is set to true.

Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147
0

if you have an identity column, you don't need to specify it in the insert statement.

INSERT INTO qcRawMatTestCharacteristic  
VALUES(1,1,1,1,1,1,1,'','','', GETDATE(), 1) 

However, if you have a primary key that isn't an identity column, then you do need to specify it, because otherwise it'll try to insert a null and primary keys by default are non-nullable.

DForck42
  • 19,789
  • 13
  • 59
  • 84