Database Tables  «Prev  Next»

Lesson 4Creating Databases
ObjectiveDescribe the Elements of a basic SQL-Server Database

Elements of a Database in SQL Server 2025

The previous lesson covered who's allowed to create, modify, or drop a database. Before you actually run CREATE DATABASE, it helps to know exactly what that statement builds. A SQL Server database isn't a single file holding rows and columns; it's a container for a whole set of different object types, each with its own job, sitting on top of a couple of physical files working behind the scenes. This lesson surveys those elements, from the files a database is backed by on disk to the native data types SQL Server 2025 adds for AI-ready workloads, before the next lesson walks through building one hands-on.

The Files Behind Every Database

As the first lesson in this module covered, every database is backed by at least two operating-system files. The primary data file, conventionally given an .mdf extension, stores the database's own schema along with the actual data in its tables. The transaction log file, conventionally given an .ldf extension, records every change made to the database so SQL Server can recover correctly after a crash or roll back an incomplete transaction. A database can also span one or more secondary data files, conventionally given an .ndf extension, once a single file isn't convenient to manage anymore, perhaps to spread data across several physical disks for performance, or to keep a very large database under a single file size limit. Secondary data files are optional; the primary data file and the transaction log file are not; SQL Server won't create a database without both.

Schemas: Grouping Objects Together

A schema is a container that groups related database objects, tables, views, and the other object types covered below, under a common namespace. Rather than managing permissions object by object, a schema lets an administrator grant access to an entire group at once: granting SELECT on a schema grants it on every table and view that schema currently contains, and on any new one added to it later. Every object you create belongs to exactly one schema, whether you name that schema explicitly or let it default to dbo, the built-in default schema present in every database. A table referenced as dbo.Employees is really being referenced by its full two-part name, schema and object together; two different schemas in the same database can each hold their own table named Employees without conflicting, since the schema is what actually distinguishes them.

Tables and Indexes

Tables are the core element of any database: the structure where data actually lives, organized into rows and columns. Every table falls into one of two categories depending on whether it has a clustered index. A table with no clustered index is called a heap, and its rows have no particular physical storage order; a table with a clustered index is simply called a clustered table, and SQL Server physically stores its rows sorted by that index's key.

Indexes exist to speed up data retrieval, letting SQL Server find rows matching a query without scanning the entire table. A clustered index determines the physical storage order of the table's own data, which is why a table can have only one: the data can only be sorted one way at a time. A non-clustered index, by contrast, is a separate structure entirely, one that holds a copy of its key columns plus a pointer back to the actual row, rather than reordering the table itself; a single table can have many non-clustered indexes built against the columns queries filter or sort on most often.

Views

A view is a saved query that presents its results as though they were a table, letting you reference a complex join or calculation by a simple name instead of repeating the underlying SQL every time. An ordinary view stores no data of its own; it stores only the query definition, and SQL Server re-runs that query every time the view is referenced. Indexed views are the one exception to that rule: creating a unique clustered index on a view forces SQL Server to actually materialize and store its result set on disk, much like a table, which can meaningfully speed up queries against a view that aggregates or joins large amounts of data, at the cost of SQL Server having to keep that stored result set in sync whenever the underlying tables change.

Stored Procedures, Functions, and Triggers

These three object types all hold executable T-SQL code inside the database, but each serves a different purpose. A stored procedure is a precompiled, named block of T-SQL that performs one or more operations, inserting rows, updating them, running a report query, and can be called repeatedly from an application without resending the SQL text each time, improving both performance and reusability. A function works similarly but is required to return a value: a scalar function returns a single value, usable anywhere a single value is expected, while a table-valued function returns an entire result set, usable anywhere a table can be referenced. A trigger is a special kind of stored procedure that doesn't get called directly at all; instead, it runs automatically whenever a specific event, an INSERT, UPDATE, or DELETE, occurs against the table or view it's attached to, which makes triggers useful for enforcing business rules or maintaining audit history without relying on every application that touches the table to do it correctly on its own.

Constraints

Constraints are rules enforced directly on a table's columns to maintain data integrity, rejecting any row that would violate them rather than leaving invalid data for an application to catch later. The previous module covered these individually in depth, but as a quick reference:
  • PRIMARY KEY: uniquely identifies each row in a table
  • FOREIGN KEY: requires a column's value to match an existing value in another table, enforcing a relationship between the two
  • UNIQUE: requires every value in a column, or combination of columns, to be distinct
  • CHECK: requires a column's value to satisfy a logical expression you define
  • DEFAULT: supplies a value automatically when a row is inserted without one
  • NOT NULL: requires a column to always have a value, rejecting a row that leaves it blank

Users and Roles

Users and roles manage security within a database: controlling which logins can connect to it at all, and once connected, exactly what each one is permitted to do. A database user is the database-level identity tied back to a server-level login, and a role is a named group of permissions that one or more users can be added to, so that an administrator can manage permissions for a whole group of people at once rather than granting the same set of rights to each user individually. The previous lesson covered the specific roles and permissions involved in creating, modifying, and dropping a database itself; the same underlying mechanism extends to every other object covered in this lesson, tables, views, stored procedures, and the rest.

Temporal Tables

A temporal table, more precisely called a system-versioned temporal table, is a table type, introduced back in SQL Server 2016, that automatically retains the previous state of every row whenever it's updated or deleted, rather than simply overwriting or discarding that history. SQL Server manages this by pairing the table you query normally with a second, hidden history table it maintains behind the scenes, and a handful of added T-SQL clauses let you query the table as it existed at any point in the past, which supports both auditing, proving what a row's values were at a given moment, and straightforward recovery from an accidental update without needing a full database restore.

Synonyms

A synonym is simply an alias for another database object, a table, view, stored procedure, or function, possibly one that lives in a different database or even on a different server entirely. Synonyms are useful for abstracting away a long, fully-qualified, or server-specific object name behind a short, stable one: application code can reference the synonym instead of the underlying object's real name, and if that underlying object ever needs to move, only the synonym's definition needs to change, not every piece of code that references it.

Service Broker, Full-Text Search, and CLR Integration

Three more specialized elements round out what a database can contain. Service Broker enables asynchronous, message-based communication, letting one part of a database, or even a separate database entirely, queue a message for another part to process later rather than waiting on it synchronously. Full-Text Search supports linguistic, word-based searching against character data, matching inflected forms of a word or ranking results by relevance rather than requiring an exact substring match, the way an ordinary LIKE comparison does. CLR integration lets compiled .NET code run directly inside the database engine itself, useful for logic that's awkward to express in T-SQL alone; it's disabled by default on a new SQL Server instance, however, and has to be deliberately enabled, partly over the security implications of running external code inside the engine.

Native JSON and Vector Data Types

SQL Server 2025 adds two data types worth calling out specifically, since they go beyond what this list would have included even a couple of versions ago. A native JSON data type now stores and indexes JSON documents directly in a column, validating that what's stored is actually well-formed JSON and allowing it to be queried and indexed more efficiently than the text-based JSON handling earlier versions relied on. A VECTOR data type stores the numeric embeddings used in AI and similarity-search workloads, the kind of vector representation a machine-learning model produces for a piece of text or an image, directly as a native column type rather than requiring an external vector database. Both are covered in more depth in later courses in this series; what matters here is that they're now elements a SQL Server 2025 database can contain, alongside the more traditional object types above.

Viewing a Database's Properties in SSMS

SQL Server Management Studio's Object Explorer offers a GUI alternative to querying sys.databases directly, as the first lesson in this module showed. Right-clicking a database and choosing Properties opens a multi-page dialog; its General page reports the same kind of metadata a query against sys.databases would return:

PropertyWhat It Shows
NameThe database's name
StatusNormal, Restoring, Offline, and the other states a database can be in
OwnerThe database's DBO, covered in the previous lesson
Date CreatedWhen the database was created
Size / Space AvailableCurrent allocated size and how much of it is still free
CollationThe default collation used for text comparisons in this database

The dialog's other pages, Files, Filegroups, Options, and the rest, expose settings covered in more depth in upcoming lessons on modifying a database; the General page shown here is the one you'll check most often just to confirm a database's basic state at a glance.

Creating a Database and Its Transaction Log

Creating a database means more than just naming it. The biggest practical consideration is size, the maximum amount of disk space the database is allowed to consume. SQL Server can grow a database's files automatically as they fill up, and letting it do so is generally the safer default: it's better to have SQL Server allocate more space than strictly necessary than to hit an out-of-space error in the middle of saving data.

Alongside the data file, every database has a transaction log working behind the scenes, used to record the state of the data whenever a query runs inside a transaction, preserving that state from the moment the transaction begins. Transactions themselves are covered in a later course in this series; for now, it's enough to know the log exists and that SQL Server creates one automatically, whether or not you specify it yourself:

CREATE DATABASE SalesDB;
Running that single statement creates both files without any further input:

SalesDB.mdf
SalesDB_log.ldf
The transaction log is what makes several of SQL Server's core guarantees possible: it's what ACID compliance's durability and atomicity properties actually rely on, it's what lets an uncommitted transaction be rolled back cleanly after a failure, and it's what the database recovers from after a crash or an unexpected restart. It also underlies features built on top of ordinary transaction processing, such as transactional replication and log shipping. None of that requires you to do anything extra; SQL Server creates and maintains the log automatically the moment the database exists.

You're not limited to the defaults, though. A fuller form of CREATE DATABASE lets you specify exactly where each file lives, how large it starts out, and how large it's allowed to grow:

CREATE DATABASE SalesDB
ON
( NAME = SalesDB_Data,
  FILENAME = 'C:\SQLData\SalesDB.mdf',
  SIZE = 20MB,
  MAXSIZE = 200MB,
  FILEGROWTH = 5MB )
LOG ON
( NAME = SalesDB_Log,
  FILENAME = 'C:\SQLLogs\SalesDB.ldf',
  SIZE = 10MB,
  MAXSIZE = 100MB,
  FILEGROWTH = 5MB );
The next lesson covers this full syntax in detail, parameter by parameter. In summary: the transaction log is mandatory, SQL Server creates and uses it automatically, and while you can control its size, growth, and location, you can't create a database without one. It's vital for recovery, rollback, replication, and auditing alike.

You can also create a database without writing any T-SQL at all, by right-clicking the Databases node for your server in SQL Server Management Studio's Object Explorer and choosing New Database, which opens the same kind of Database Properties dialog shown above, this time ready to define a new database rather than just display an existing one's settings.

Putting the Elements Together

With a dozen or so different element types covered above, it helps to see them grouped by the role they play before moving on:

CategoryElements
Physical storagePrimary data file (.mdf), secondary data files (.ndf), transaction log file (.ldf)
Data structuresSchemas, tables, indexes, views, constraints
ProgrammabilityStored procedures, functions, triggers
SecurityUsers, roles
Specialized featuresTemporal tables, synonyms, Service Broker, Full-Text Search, CLR integration
SQL Server 2025 additionsNative JSON type, VECTOR type

None of these elements exist in isolation. A table depends on the database's own files to store its data; an index depends on a table to index; a trigger depends on the table or view it's attached to; a role only matters once there are objects to grant permissions against. The next several lessons in this course build on this list one piece at a time, starting with the database itself.

What's Ahead

The next lesson walks through CREATE DATABASE itself, hands-on, now that you know both who's allowed to run it and what it actually builds.
In the next lesson, you will learn how to use Transact-SQL to create a database.

SEMrush Software 4 SEMrush Banner 4