# SQL Server: A Practical Guide to the Database Behind Business Software

Somewhere in most established companies there is a server that nobody outside the IT team thinks about. It runs the accounting package, the HR system, the warehouse software and a few hundred reports that land in inboxes every Monday morning. Very often, the database on it is Microsoft SQL Server.

SQL Server rarely trends on developer forums, yet it quietly runs a large share of business software. If you take a job at a company that uses Microsoft tools, you will meet it. This guide gives you a working knowledge of it: what it is good at, what it costs you, and the habits that separate a healthy server from a slow one.

## What SQL Server is

SQL Server is Microsoft's relational database. It stores data in tables, and you query it with **T-SQL** (Transact-SQL), Microsoft's dialect of SQL with its own procedural extensions.

A few facts that surprise people:

- **It runs on Linux and in containers**, not only on Windows.
- **There are free editions.** Express is free for production use, with limits on database size and hardware. Developer edition has every feature and is free for development and testing only.
- **Azure SQL Database is the same engine** offered as a managed cloud service.

Standard and Enterprise are the paid editions, licensed per processor core or per server and user. Enterprise costs considerably more and unlocks the high-end features.

You can have a server running in a minute with Docker:

```bash
docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=Use-A-Strong-One-1" \
  -p 1433:1433 -d mcr.microsoft.com/mssql/server:2022-latest
```

## Why teams choose it

### One product, many jobs

A SQL Server licence covers more than the database engine. Scheduled jobs (SQL Server Agent), reporting (Reporting Services), data pipelines (Integration Services) and an analytics engine (Analysis Services) come with it. For a company that wants one vendor and one support contract, that matters.

### Tooling that explains itself

SQL Server Management Studio (SSMS) is a free and very complete administration tool. Graphical execution plans show where a query spends its effort. The **Query Store** records the history of every query's performance and plans, so you can answer "what changed on Tuesday?" after the fact.

### Analytics next to transactions

A **columnstore index** stores a table by column instead of by row, which makes aggregations over millions of rows much faster. You can add one to an ordinary table and run reports on live data without a separate warehouse.

### It fits the Microsoft world

Windows sign-in, Active Directory, .NET, Power BI and Excel all connect with little effort. If the rest of your company runs on Microsoft, the pieces line up.

## Where SQL Server fits, and where it does not

**A strong choice for:**

- Line-of-business applications, especially on .NET
- Packaged enterprise software that requires it
- Mixed transaction and reporting workloads on one server
- Organisations already using Windows, Azure and Power BI

**Look elsewhere when:**

- **Budget is tight and the data will outgrow Express.** PostgreSQL and MySQL have no licence fees at any size.
- **You want to avoid tying yourself to one vendor.** T-SQL code and SQL Server features do not move easily to other databases.
- **You need an embedded database inside an app.** That is SQLite's job.
- **Your analytics run to many billions of rows.** A dedicated column store or cloud warehouse will scale further and usually cost less.

## Using it the right way

### Know the T-SQL differences

If you come from PostgreSQL or MySQL, a handful of things will look odd:

```sql
CREATE TABLE dbo.orders (
  id          BIGINT IDENTITY(1,1) NOT NULL PRIMARY KEY,
  customer_id BIGINT NOT NULL REFERENCES dbo.customers (id),
  total       DECIMAL(12,2) NOT NULL CHECK (total >= 0),
  status      VARCHAR(20) NOT NULL DEFAULT 'pending',
  note        NVARCHAR(400) NULL,
  created_at  DATETIME2(3) NOT NULL DEFAULT SYSUTCDATETIME()
);

-- The newest 20 rows: TOP instead of LIMIT
SELECT TOP (20) id, total FROM dbo.orders ORDER BY created_at DESC;

-- Paging
SELECT id, total FROM dbo.orders
ORDER BY created_at DESC
OFFSET 40 ROWS FETCH NEXT 20 ROWS ONLY;
```

- `IDENTITY` is the auto-incrementing column.
- `NVARCHAR` stores Unicode text; write its literals with an `N` prefix, as in `N'Zoë'`. Plain `VARCHAR` depends on the column's collation.
- Use `DATETIME2`, not the older `DATETIME`, which has less precision and a smaller range. Use `DATETIMEOFFSET` when you need the time zone offset stored.
- `dbo` is the default schema. Always write the schema name in front of the table.
- `GO` is not SQL. It is a marker that tools use to split a script into batches.

### Understand the clustered index

Every table should have a **clustered index**: the order in which the rows themselves are stored. By default the primary key becomes the clustered index. A narrow, ever-increasing key such as an `IDENTITY` column is a good choice, because new rows go to the end and every other index carries a copy of that key.

Other indexes are "nonclustered". You can add extra columns to one with `INCLUDE`, so a query is answered from the index alone:

```sql
CREATE NONCLUSTERED INDEX ix_orders_customer_created
  ON dbo.orders (customer_id, created_at DESC)
  INCLUDE (total, status);
```

### Stop readers and writers blocking each other

Out of the box, a self-hosted SQL Server uses locks for reads, so a long report can block updates and the other way round. Turning on read committed snapshot isolation makes readers see the last committed version of a row instead of waiting:

```sql
ALTER DATABASE shop SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK IMMEDIATE;
```

`WITH ROLLBACK IMMEDIATE` disconnects other sessions so the change can apply, so run it in a quiet moment. Azure SQL Database has this setting on by default. It is the proper cure for the blocking that people otherwise paper over with `NOLOCK`.

### Measure before you tune

```sql
ALTER DATABASE shop SET QUERY_STORE = ON;

SET STATISTICS IO, TIME ON;
SELECT TOP (20) id, total FROM dbo.orders
WHERE customer_id = 42
ORDER BY created_at DESC;
```

`STATISTICS IO` reports "logical reads", the number of data pages touched. It is the most honest measure of how much work a query does. An "Index Scan" or "Table Scan" over a large table in the execution plan, where you expected an "Index Seek", usually means a missing or unusable index.

### Add a columnstore index for reports

```sql
CREATE NONCLUSTERED COLUMNSTORE INDEX ncci_orders_reporting
  ON dbo.orders (customer_id, status, total, created_at);
```

Aggregations such as monthly totals can then read a compact column-wise copy of the data.

### Logins, users and roles

SQL Server separates the **login** (who may connect to the server) from the **user** (what that login may do in one database):

```sql
CREATE LOGIN shop_app WITH PASSWORD = 'Use-A-Long-Random-One-1';
GO
USE shop;
GO
CREATE USER shop_app FOR LOGIN shop_app;
ALTER ROLE db_datareader ADD MEMBER shop_app;
ALTER ROLE db_datawriter ADD MEMBER shop_app;
```

Never let an application connect as `sa`, the built-in administrator. Disable `sa` if you can.

### Back up, including the log

```sql
BACKUP DATABASE shop
  TO DISK = N'/var/opt/mssql/data/shop.bak'
  WITH CHECKSUM;

RESTORE VERIFYONLY
  FROM DISK = N'/var/opt/mssql/data/shop.bak'
  WITH CHECKSUM;
```

Each database has a **recovery model**. In `FULL`, the transaction log keeps every change until you back the log up, which is what allows a restore to any point in time. If you choose `FULL`, you must schedule log backups (`BACKUP LOG`), or the log file grows until the disk is full. If you do not need point-in-time recovery, use `SIMPLE`.

`RESTORE VERIFYONLY` checks the file is readable. Only a real restore to another server proves the backup works.

## Common mistakes

- **`WITH (NOLOCK)` everywhere.** It does not just read uncommitted data. It can skip rows or return the same row twice. Use read committed snapshot instead.
- **Full recovery model with no log backups.** The classic cause of a disk filling up overnight.
- **Mismatched string types.** Comparing a `VARCHAR` column to an `NVARCHAR` parameter forces a conversion on every row and can stop an index being used. Make the parameter type match the column.
- **Shrinking databases on a schedule.** Shrinking fragments indexes, and the file just grows again. Leave auto-shrink off.
- **Applications connecting as `sa`.** One leaked connection string gives away the whole server.
- **Functions wrapped around indexed columns.** `WHERE YEAR(created_at) = 2026` cannot use an index on `created_at`. Write a date range instead.
- **Ignoring the Express limits.** Express caps the size of each database. Check the limit for your version before you build a product on it.
- **A random `UNIQUEIDENTIFIER` as the clustered key.** Inserts land all over the table and cause page splits. Use an `IDENTITY` column, or `NEWSEQUENTIALID()` as the column default.

## Quick reference

| Task | Command |
|---|---|
| Connect | `sqlcmd -S host,1433 -U user -d dbname` |
| Server version | `SELECT @@VERSION;` |
| List databases | `SELECT name FROM sys.databases;` |
| List tables | `SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES;` |
| Describe a table | `EXEC sp_help 'dbo.orders';` |
| Table size | `EXEC sp_spaceused 'dbo.orders';` |
| Running requests | `SELECT session_id, status, command, blocking_session_id FROM sys.dm_exec_requests;` |
| Stop a session | `KILL 57;` |
| Refresh statistics | `UPDATE STATISTICS dbo.orders;` |
| Check for corruption | `DBCC CHECKDB ('shop');` |

SQL Server rewards a little structure: a sensible clustered key, snapshot isolation, the Query Store switched on and log backups that match your recovery model. With those in place, it is a calm and capable system.

## Exploring SQL Server with CreamDB

SSMS is excellent, but it is a Windows desktop program. When you are on a Mac, a Chromebook or a tablet, or you simply want a quick look, [CreamDB](https://www.creamdb.com) gives you a SQL Server workspace in the browser, with nothing to install. Azure SQL Database has its own connection type too.

- Browse databases, schemas, tables and views in a tree. Open a table in a grid where paging, sorting and filtering run on the server.
- Write T-SQL in an editor with autocomplete, formatting and history, and export results to CSV, JSON or Excel.
- See the schema as an ER diagram, watch sessions in the Status panel, and read logins, users and roles on a read-only page.
- Ask in plain English and get the T-SQL, a result table and a chart.

The assistant only reads on its own. Any change becomes an approval card you answer, and read-only mode blocks writes on the server. CreamDB is a hosted service, so your SQL Server must be reachable from the internet, ideally with its firewall opened only to the addresses you need.

It is free to start.

