How to create a table with more than 1024 columns in SQL Server?

Anonymous
2024-01-06T00:33:17.22+00:00

Our application requires a table with 1500 columns, but SQL Server restricts tables to a maximum of 1024 columns. Is there a way to create a table with more than 1024 columns in SQL Server that meets this requirement?

SQL Server | Other
{count} votes

1 answer

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2024-01-06T10:41:30.2933333+00:00

    Usually when you run into hard limits, you run into to hard limits. But this is your lucky day!

    If you have columns that you mainly expect to be NULL values, you can define them as SPARSE. Then you also define an XML column which is a so-called column set. You can have up to 30000 sparse columns in a table. Here is a quick example:

    CREATE TABLE sparse_table (
        id int NOT NULL,
        col1 int SPARSE NULL,
        col2 int SPARSE NULL,
        col3 int SPARSE NULL,
        colset xml COLUMN_SET FOR ALL_SPARSE_COLUMNS
        CONSTRAINT pk_sparse_table PRIMARY KEY(id)
    )
    

    If memory serves, you can retrieve the columns individually, or just return colset as one XML document with all columns.

    You can read more about this feature here: https://learn.microsoft.com/en-us/sql/relational-databases/tables/use-sparse-columns.

    If you expect all 1500 columns to mainly have non-NULL values, I don't think sparse columns are a good bet. In that case you would be better off splitting up the columns into two tables. Or make an overall review of the design that led to these 1500 columns.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.