LESSON 5 OF 14

Table Design and SQL Server Data Types

This lesson covers requirement-based table design, SQL Server data types, NULL handling, IDENTITY columns, and essential constraints through practical examples.

55 dk 106

Introduction

The success of a database application depends not only on the queries that are written, but also on how the data is modeled. A well-designed table stores values in an appropriate form, reduces unnecessary duplication, limits invalid input, and makes later queries easier to understand. An unsuitable data type can cause excessive storage usage, data loss, comparison problems, or application errors.

In this lesson, we will learn how to analyze requirements before creating a table and how to define suitable columns in SQL Server. The focus will be on character, numeric, date-time, bit, and identity-related data types. We will use a small product catalog as a consistent example throughout the lesson.

Questions to answer before creating a table

Before writing CREATE TABLE, clarify the following:

  • Which entity or business concept will be stored? For example, a product, customer, or order.
  • Which attributes describe each record?
  • Which value uniquely identifies one record?
  • Which columns are required and which are optional?
  • What range or format is valid for each value?
  • Will the design remain practical as the amount of data increases?

For this lesson, we will create a table named Products. Each product will have a unique identifier, a product code, a name, a description, a price, a stock quantity, an active flag, and a creation timestamp.

Choosing SQL Server data types

A data type defines the kind of value that a column can store. Selection should be based not only on the sample data available today, but also on realistic future values. Avoid both undersizing a column and selecting a type that is unnecessarily broad.

Character data types

varchar stores variable-length, non-Unicode character data. It can be suitable for data that is limited to a known non-Unicode character set. nvarchar supports Unicode characters and is a safer choice for Turkish text or applications that may support multiple languages.

char(n) is designed for fixed-length character values. It can be appropriate for a value such as a two-letter country code. varchar(n) and nvarchar(n) are generally better for variable-length values such as product names. Using a fixed-length type for such values can waste space and obscure the design intent.

Data typeSuitable useExample
char(2)Fixed-length codeUS
varchar(20)Short non-Unicode textABC-100
nvarchar(150)Unicode or multilingual textÇelik Termos
nvarchar(max)Long text with no small known limitDetailed description

Specify a realistic length whenever possible. Defining every text column as nvarchar(max) may make the design less expressive and can weaken the boundary between normal attributes and genuinely large text.

Numeric data types

SQL Server provides tinyint, smallint, int, and bigint for integer values. int is sufficient for most identifiers and quantity columns. Use bigint only when the expected range requires it. A smaller type can be considered when the business range is known and strictly limited.

Use decimal(p,s), or its equivalent numeric(p,s), for exact decimal values. The precision, p, is the total number of digits, while the scale, s, is the number of digits to the right of the decimal point. For example, decimal(10,2) allows ten total digits, including two fractional digits.

For prices and other financial values, an exact decimal type is usually preferable to a floating-point type. This reduces unexpected rounding differences during calculations and comparisons.

Date and time data types

date stores only a calendar date and is appropriate when time is not relevant, such as a birth date. time stores only a time of day. datetime2 stores both date and time and is a strong general-purpose choice for timestamps.

For a row creation value, define a datetime2 column with a default expression such as SYSDATETIME(). The value is then generated when a new row is inserted, unless the insert explicitly supplies another value.

The bit data type

Use bit for logical states such as active or inactive, subscribed or not subscribed, and enabled or disabled. In ordinary application code, values are commonly represented as 0 and 1.

A nullable bit column can contain 0, 1, or NULL. If the business rule requires a definite yes-or-no answer, define the column as NOT NULL and provide a suitable default.

IDENTITY and key columns

A column that uniquely identifies each row is commonly used as the primary key. SQL Server can automatically generate sequential numeric values with the IDENTITY(seed, increment) property.

IDENTITY(1,1) means that the first generated value is 1 and subsequent values normally increase by 1. IDENTITY helps generate values, but it is not itself a primary key and does not guarantee that values will be gap-free. To enforce uniqueness and prohibit NULL, define the column with a PRIMARY KEY constraint.

CREATE TABLE dbo.Products
(
    ProductID int IDENTITY(1,1) NOT NULL,
    ProductCode varchar(20) NOT NULL,
    ProductName nvarchar(150) NOT NULL,
    Description nvarchar(1000) NULL,
    UnitPrice decimal(10,2) NOT NULL,
    StockQuantity int NOT NULL,
    IsActive bit NOT NULL,
    CreatedAt datetime2(0) NOT NULL,
    CONSTRAINT PK_Products PRIMARY KEY (ProductID),
    CONSTRAINT UQ_Products_ProductCode UNIQUE (ProductCode),
    CONSTRAINT CK_Products_UnitPrice CHECK (UnitPrice >= 0),
    CONSTRAINT CK_Products_StockQuantity CHECK (StockQuantity >= 0)
);

In this definition, ProductID is an automatically generated key. ProductCode is required and cannot be duplicated. The product name, price, stock quantity, active flag, and creation timestamp are also required. The description is optional.

NULL, NOT NULL, and default values

NULL does not mean an empty string or zero. It represents an unknown, missing, or not-yet-provided value. A product with no description may have NULL in Description. An empty description and an unknown description are not necessarily the same business meaning.

NOT NULL requires every inserted row to have a value for that column. Use it when the column is essential to the meaning of the record. For example, a product without a name may not be a valid product record.

A default value is used when an insert does not provide a value for a column:

ALTER TABLE dbo.Products
ADD CONSTRAINT DF_Products_IsActive
DEFAULT (1) FOR IsActive;

ALTER TABLE dbo.Products
ADD CONSTRAINT DF_Products_CreatedAt
DEFAULT (SYSDATETIME()) FOR CreatedAt;

These statements add defaults to an existing table. Defaults may also be included directly in the original CREATE TABLE definition.

Inserting sample rows

During a normal insert, do not provide a value for the IDENTITY column. SQL Server generates it automatically:

INSERT INTO dbo.Products
    (ProductCode, ProductName, Description, UnitPrice, StockQuantity)
VALUES
    ('THM-001', N'Çelik Termos', N'500 ml paslanmaz çelik termos', 349.90, 25);

INSERT INTO dbo.Products
    (ProductCode, ProductName, UnitPrice, StockQuantity, IsActive, CreatedAt)
VALUES
    ('KBL-010', N'USB-C Kablo', 129.50, 80, 1, SYSDATETIME());

When inserting Unicode text into an nvarchar column, prefix a string literal with N. This makes the intended Unicode representation explicit and protects characters such as those used in Turkish.

To return the generated key and other inserted values, use the OUTPUT INSERTED clause:

INSERT INTO dbo.Products
    (ProductCode, ProductName, UnitPrice, StockQuantity)
OUTPUT INSERTED.ProductID, INSERTED.ProductName
VALUES
    ('MSE-005', N'Kablosuz Mouse', 499.00, 15);

Designing a table in SSMS

  1. In Object Explorer, locate the target database.
  2. Expand Tables, right-click it, and choose New > Table.
  3. Enter the column names in the table designer.
  4. Select an appropriate data type and specify length or precision where required.
  5. Set Allow Nulls according to the business rules.
  6. For an identity column, open Column Properties and set Identity Specification and (Is Identity) to Yes.
  7. To select a primary key, right-click the row selector and choose Set Primary Key.
  8. Save the table with a consistent, meaningful name.

The graphical designer is useful for learning and quick changes. T-SQL is often preferable for repeatability because the definition can be saved, reviewed, placed under source control, and executed consistently in another environment. In production systems, schema changes should be planned and tested.

Common mistakes

  • Storing every value as nvarchar: Numeric and date values stored as text create problems with sorting, calculation, validation, and indexing.
  • Using float for prices: Floating-point types are approximate. Use an appropriate decimal definition for monetary values.
  • Ignoring character length: Explicit lengths document the intended design and help reject invalid values early.
  • Assuming IDENTITY is a key: IDENTITY generates values, while PRIMARY KEY or UNIQUE enforces uniqueness.
  • Confusing NULL with an empty value: Test for NULL with IS NULL or IS NOT NULL, not with = NULL.
  • Failing to encode business rules: Use CHECK constraints when negative prices or quantities must be rejected.
  • Not testing Unicode: Insert multilingual examples and verify that the selected type and string literals preserve the characters.

Short practice exercise

Create a table named Customers in your practice database with the following design:

  • CustomerID: an automatically incrementing primary key
  • FirstName and LastName: required Unicode text
  • Email: required and unique text
  • BirthDate: an optional date
  • IsSubscribed: a bit column with a default of 0
  • CreatedAt: a date-time column defaulting to the current date and time

Insert at least three customers. Leave one birth date as NULL, include a name with a non-ASCII character, and attempt to insert the same email address twice. Explain why the second email insert fails.

Conclusion

Table design begins with understanding the requirements. Character data commonly uses varchar or nvarchar; integer and exact decimal values use suitable numeric types; dates and timestamps use date or datetime2; and logical states use bit. IDENTITY can generate key values, while PRIMARY KEY, UNIQUE, CHECK, NOT NULL, and DEFAULT constraints help preserve data quality.

In the next lessons, we will work more deeply with inserting, updating, and deleting data. Those operations become safer and more predictable when the underlying tables have appropriate data types and clearly defined constraints.

Sources