SQL Server CREATE TABLE – Syntax, Constraints, Temp Tables, and Examples | DbSchema



SQL Server CREATE TABLE guide in DbSchema

Table of Contents

  1. What SQL Server CREATE TABLE does
  2. Basic syntax
  3. Common SQL Server data types
  4. Constraints you will use most often
  5. Create a simple table
  6. Create a production-ready table
  7. Useful CREATE TABLE variants
  8. Check the result
  9. Create tables visually in DbSchema
  10. FAQ
  11. Conclusion

CREATE TABLE is the statement that turns a schema idea into a real SQL Server object. It defines column names, data types, keys, defaults, checks, and the table options your application will rely on in production.

For a quick demo, you can write the DDL directly in sqlcmd. For team workflows, DbSchema is useful because you can design the table visually, connect through the SQL Server JDBC driver, generate the SQL, and deploy with schema synchronization.

What SQL Server CREATE TABLE does

In SQL Server, CREATE TABLE creates a table in a schema such as dbo, sales, or audit. When you define the table, you usually decide:

  • the schema and table name
  • the columns and data types
  • which columns are required with NOT NULL
  • how rows are uniquely identified with PRIMARY KEY
  • which values must be unique, checked, or related to another table
  • what defaults should be applied when the application omits a value

If you have not created the database yet, start with SQL Server: How to Create a Database. If indexes are the next step, read SQL Server: How to Create an Index.

Basic syntax

CREATE TABLE [schema_name.]table_name (
    column_name data_type [NULL | NOT NULL] [column_constraint],
    column_name data_type [NULL | NOT NULL] [column_constraint],
    table_constraint
);

SQL Server also supports IDENTITY, DEFAULT, CHECK, PRIMARY KEY, UNIQUE, and FOREIGN KEY directly inside the statement, so it is usually better to add core rules up front instead of waiting for later migrations.

Common SQL Server data types

Data typeTypical use
int / bigintNumeric IDs, counters, surrogate keys
decimal(p,s)Prices, balances, exact calculations
bitBoolean-style flags
dateCalendar dates
datetime2Application timestamps
nvarchar(n)Unicode text
varchar(n)Non-Unicode text when Unicode is not needed
uniqueidentifierGUID keys
varbinary(max)Binary documents or files

For modern SQL Server work, prefer datetime2 over older datetime, and use decimal instead of floating-point types for money.

Constraints you will use most often

ConstraintWhat it doesExample
PRIMARY KEYidentifies each row uniquelyOrderID bigint PRIMARY KEY
IDENTITYauto-generates integer valuesOrderID bigint IDENTITY(1,1)
NOT NULLrequires a valueCustomerID bigint NOT NULL
UNIQUEprevents duplicatesEmail nvarchar(255) UNIQUE
DEFAULTsupplies a value automaticallyStatus nvarchar(20) DEFAULT 'New'
CHECKenforces a ruleCHECK (TotalAmount >= 0)
FOREIGN KEYlinks rows to another tableFOREIGN KEY (CustomerID) REFERENCES dbo.Customers(CustomerID)

These constraints are what turn a demo table into something safe for real applications.

Create a simple table

CREATE TABLE dbo.Students (
    StudentID   int           NOT NULL PRIMARY KEY,
    StudentName nvarchar(100) NOT NULL,
    StudentAge  int           NULL
);

This is enough for a quick example, but production tables normally need defaults, audit columns, and relationship constraints too.

Create a production-ready table

Here is a more realistic Orders table:

CREATE TABLE dbo.Orders (
    OrderID        bigint        IDENTITY(1,1) NOT NULL,
    CustomerID     bigint        NOT NULL,
    OrderNumber    nvarchar(30)  NOT NULL,
    Status         nvarchar(20)  NOT NULL CONSTRAINT DF_Orders_Status DEFAULT ('New'),
    TotalAmount    decimal(12,2) NOT NULL CONSTRAINT CK_Orders_TotalAmount CHECK (TotalAmount >= 0),
    CreatedAt      datetime2     NOT NULL CONSTRAINT DF_Orders_CreatedAt DEFAULT (sysutcdatetime()),
    LastModifiedAt datetime2     NOT NULL CONSTRAINT DF_Orders_LastModifiedAt DEFAULT (sysutcdatetime()),
    CONSTRAINT PK_Orders PRIMARY KEY CLUSTERED (OrderID),
    CONSTRAINT UQ_Orders_OrderNumber UNIQUE (OrderNumber),
    CONSTRAINT FK_Orders_Customers
        FOREIGN KEY (CustomerID) REFERENCES dbo.Customers(CustomerID)
);

This version is closer to what enterprise teams ship:

  • IDENTITY handles key generation
  • named constraints make deployments and troubleshooting easier
  • DEFAULT values reduce application boilerplate
  • CHECK blocks invalid totals early
  • a FOREIGN KEY preserves referential integrity

If you want to document these rules for analysts or auditors, DbSchema can reverse-engineer the table and publish the structure using schema documentation.

Useful CREATE TABLE variants

Create a temporary table

CREATE TABLE #RecentOrders (
    OrderID   bigint,
    CreatedAt datetime2
);

Temporary tables are session-scoped and common in ETL jobs, reporting procedures, and troubleshooting sessions.

Create a table only if it does not already exist

SQL Server does not support CREATE TABLE IF NOT EXISTS directly. Use a guard:

IF OBJECT_ID('dbo.AuditLog', 'U') IS NULL
BEGIN
    CREATE TABLE dbo.AuditLog (
        AuditID   bigint IDENTITY(1,1) PRIMARY KEY,
        EventName nvarchar(100) NOT NULL,
        CreatedAt datetime2 NOT NULL DEFAULT sysutcdatetime()
    );
END;

SQL Server alternative to CREATE TABLE AS SELECT

Many users search for CREATE TABLE AS SELECT, but in SQL Server the common equivalent is SELECT INTO:

SELECT CustomerID,
       SUM(TotalAmount) AS LifetimeValue
INTO dbo.CustomerLifetimeValue
FROM dbo.Orders
GROUP BY CustomerID;

This creates the table and inserts the query result in one step. Afterward, add indexes and constraints explicitly if the new table will live beyond a staging job.

Design for partitioning or compression later

If a table will grow into hundreds of millions of rows, plan for later operations such as partitioning or data compression when you choose the clustered key and filegroup strategy.

Check the result

After running CREATE TABLE, verify the definition:

EXEC sp_help 'dbo.Orders';

Or query the catalog:

SELECT c.name AS column_name,
       t.name AS data_type,
       c.max_length,
       c.is_nullable
FROM sys.columns c
JOIN sys.types t ON c.user_type_id = t.user_type_id
WHERE c.object_id = OBJECT_ID('dbo.Orders')
ORDER BY c.column_id;

Create tables visually in DbSchema

DbSchema is a practical option when you want SQL Server DDL plus diagrams, documentation, and safer review before deployment.

Typical workflow:

  1. connect through the SQL Server JDBC driver
  2. reverse-engineer the schema or start from a blank design in the diagram editor
  3. add columns, keys, defaults, and relationships visually
  4. preview the generated SQL in the SQL editor
  5. compare the model with the live database and deploy via schema synchronization

DbSchema is especially helpful when a table change affects other objects such as views, triggers, or indexes. You can keep the diagram, DDL, and documentation aligned instead of editing each piece manually.

FAQ

How do I create an auto-increment column in SQL Server?

Use IDENTITY(seed, increment), for example OrderID bigint IDENTITY(1,1).

Does SQL Server support CREATE TABLE IF NOT EXISTS?

Not directly. Use IF OBJECT_ID(...) IS NULL before the CREATE TABLE statement.

How do I create a table with a foreign key?

Add a FOREIGN KEY clause inside CREATE TABLE, or add it later with ALTER TABLE. For visual relationship design, DbSchema also helps through diagram and schema views.

What is the SQL Server equivalent of CREATE TABLE AS SELECT?

Use SELECT INTO to create and populate a new table from a query result.

Should I add indexes in the CREATE TABLE statement?

You can define primary keys and unique constraints immediately, but many nonclustered indexes are created afterward with CREATE INDEX. See SQL Server: How to Create an Index.

Conclusion

CREATE TABLE in SQL Server is about more than syntax. The best designs choose the right data types, name constraints clearly, plan for growth, and make relationships explicit from day one.

If you want a faster workflow, DbSchema can model the table visually, generate the SQL Server DDL, connect over JDBC, and keep the schema synchronized with the live database.

DbSchema Database Design & Management

Visual Design with ER Diagrams
DbSchema ER Diagram Features Overview
Visual Design & Schema Diagram

✓ Create and manage your database schema visually through a user-friendly graphical interface.

✓ Easily arrange tables, columns, and foreign keys to simplify complex database structures, ensuring clarity and accessibility.

GIT & Collaboration
Version Control & Collaboration

✓ Manage schema changes through version control with built-in Git integration, ensuring every update is tracked and backed up.

✓ Collaborate efficiently with your team to maintain data integrity and streamline your workflow for accurate, consistent results.

Data Explorer & Query Builder
Relational Data & Query Builder

✓ Seamlessly navigate and visually explore your database, inspecting tables and their relationships.

✓ Build complex SQL queries using an intuitive drag-and-drop interface, providing instant results for quick, actionable insights.

Interactive Documentation & Reporting
HTML5 Documentation & Reporting

✓ Generate HTML5 documentation that provides an interactive view of your database schema.

✓ Include comments for columns, use tags for better organization, and create visually reports.