Search code examples
sqlsql-serversql-server-2017

Creating a unique ID column for the following table


I would like to generate a unique ID column for the following table:

I am not sure how to do it as each column has null values

FromCompany Container   Numbers     ToCompany        Location
DISCOVERY   HALU 330308   5         MAGNA CHARGE     St-Laurent
            ATSU 827944   0         LEEZA DIST. 
                          4     
COLUMBIA    CAIU 807457   3         La Cie Canada    Baie D'Urfe
                          6     
                          0  

Solution

  • create an identity column for your table.

    Alter Table t
    Add Id Int Identity(1, 1)
    

    more comprehensive example

    create table t(col1 int);
    GO
    
    insert into t values (1), (2), (5)
    GO
    
    3 rows affected
    
    Alter Table t
    Add Id Int Identity(1, 1)
    
    
    GO
    
    select * from t
    GO
    
    col1 | Id
    ---: | -:
       1 |  1
       2 |  2
       5 |  3
    

    db<>fiddle here