39

I noticed that I can have NULL values in columns that have the UNIQUE constraint: UNIQUE(col)

Would that generate any issues in certain situations?

5
  • 1
    situations like what? btw whats the datatype? Commented Mar 27, 2014 at 21:19
  • 2
    "Would that generate any issues in certain situations?" Probably - which situations are you concerned about? Commented Mar 27, 2014 at 21:20
  • Like doing any kind of db operations. Would I get any errors? I was thinking to set records to NULL when I don't need them anymore. The thing is that deleting them takes a huge amount of time and I would rather do that in a cron job Commented Mar 27, 2014 at 21:26
  • So the issue there is any queries that don't filter out NULL records would see the "deleted" ones. But that's an application issue, not a database issue. I would do more research on why deleting takes so long - DELETE operations should be as fast as finding the records. Commented Mar 27, 2014 at 21:27
  • I already know why. It's because of foreign key constrains and some triggers attached to each related record :( Commented Mar 27, 2014 at 21:38

3 Answers 3

53

While the following addresses multiple null values, it does not address any "issues" associated with such a design, other than possible database/SQL portability - as such, it should probably not be considered an answer, and is left here merely for reference.


This is actually covered in the SQLite FAQ. It is a design choice - SQLite (unlike SQL Server) chose that multiple NULL values do not count towards uniqueness in an index.

The SQL standard requires that a UNIQUE constraint be enforced even if one or more of the columns in the constraint are NULL, but SQLite does not do this. Isn't that a bug?

Perhaps you are referring to the following statement from SQL92:

  • A unique constraint is satisfied if and only if no two rows in a table have the same non-null values in the unique columns.

That statement is ambiguous, having at least two possible interpretations:

  1. A unique constraint is satisfied if and only if no two rows in a table have the same values and have non-null values in the unique columns.

  2. A unique constraint is satisfied if and only if no two rows in a table have the same values in the subset of unique columns that are not null.

SQLite follows interpretation (1), as does PostgreSQL, MySQL, Oracle, and Firebird. It is true that Informix and Microsoft SQL Server use interpretation (2), however we the SQLite developers hold that interpretation (1) is the most natural reading of the requirement and we also want to maximize compatibility with other SQL database engines, and most other database engines also go with (1), so that is what SQLite does.

See a comparison of NULL handling.

Sign up to request clarification or add additional context in comments.

4 Comments

I can't think of a situation in which (1) would be the useful interpretation.
I have one: Users have a key card with a unique id, which means no two users can have the same key. But some users don't have a key card anymore (NULL). And they might have given their key card to another user.
@JohannesEgger One of those the times when SQL Server's filtered indices (stackoverflow.com/a/15206061/2864740) becomes very useful for behavior (1) semantics.
I can't think of a situation in which (2) would be the useful interpretation. What is the purpose of allowing NULL if there can only be one value with it? It would no longer be special, it would be just another value, and NULL is very much not just another value. As Johannes mentioned, it is useful for any situation where a column may not apply to certain rows (but must be unique if it does apply).
14

If you want your unique index to throw an error when a two rows would be the same if you disregard NULL columns (and don't want to use triggers from Satyam's answer) you can do something like this

CREATE TABLE `test` (
    `Field1`    INTEGER,
    `Field2`    INTEGER
);
CREATE UNIQUE INDEX `ix` ON `test` (
    `Field1`,
    `Field2`
);
INSERT INTO `test`(`Field1`,`Field2`) VALUES (1,NULL);
INSERT INTO `test`(`Field1`,`Field2`) VALUES (1,NULL); -- This shouldn't be allowed

DROP INDEX IF EXISTS `ix`;
CREATE UNIQUE INDEX `ix2` ON `test` (
    `Field1`,
    ifnull(`Field2`, 0)  --use this instead
); --will fail

4 Comments

The ifnull() solution also causes inserts to fail for me on 'INSERT INTO test(Field1,Field2) VALUES (2,3);' and I'm not sure why, but it's not what I expected. I solved the problem in the application instead of in the database, but I wanted to put that here for anyone who came after me.
Another option to to use a filtered index (stackoverflow.com/a/15206061/2864740).
you're right, here is a better link sqlite.org/partialindex.html, also see the note on when it can be used
Nice trick. However, the code sample could be improved on by dropping the unnecessary back-ticks (or at least replacing them with the standard double quotes) and using the standard coalesce(Field2,0) instead of ifnull().
3

You can create 2 triggers on table to check if a row with column as null exists before any insert or update operation, if so raise exception.

CREATE TRIGGER UniqueColumnCheckNullInsert
        BEFORE INSERT
        ON 'Tablename'
        WHEN NEW.'column_name' IS NULL
        BEGIN
        SELECT CASE WHEN((
            SELECT 1
            FROM 'Tablename'
            WHERE 'column_name' IS NULL
            )
            NOTNULL) THEN RAISE(ABORT, "error row exists") END;
    END;

CREATE TRIGGER UniqueColumnCheckNullUpdate
        BEFORE UPDATE
        ON 'Tablename'
        WHEN NEW.'column_name' IS NULL
        BEGIN
        SELECT CASE WHEN((
            SELECT 1
            FROM 'Tablename'
            WHERE 'column_name' IS NULL
            )
            NOTNULL) THEN RAISE(ABORT, "error row exists") END;
    END;

1 Comment

This blocks all other row inserts (on all columns) if at least one row has NULL in 'column_name', so it doesn't make much sense because field is nullable. This would make sense only on table with one field.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.