Deploy it: serverless, no passwords
// Azure SQL Database for ShopKart: serverless, Entra ID-only sign-in, auto-pause.
param location string = resourceGroup().location
param env string = 'dev'
@description('Object ID of the Entra ID group that administers the server')
param sqlAdminGroupObjectId string
param sqlAdminGroupName string = 'sg-shopkart-sql-admins'
var suffix = take(uniqueString(resourceGroup().id), 6)
resource server 'Microsoft.Sql/servers@2023-08-01' = {
name: 'sql-shopkart-${env}-${suffix}'
location: location
properties: {
minimalTlsVersion: '1.2'
publicNetworkAccess: 'Disabled' // reach it through a private endpoint (lesson 8)
administrators: {
administratorType: 'ActiveDirectory'
principalType: 'Group'
login: sqlAdminGroupName
sid: sqlAdminGroupObjectId
tenantId: subscription().tenantId
azureADOnlyAuthentication: true // no SQL passwords at all
}
}
}
resource db 'Microsoft.Sql/servers/databases@2023-08-01' = {
parent: server
name: 'shopkart'
location: location
sku: { name: 'GP_S_Gen5', tier: 'GeneralPurpose', family: 'Gen5', capacity: 2 } // serverless, up to 2 vCores
properties: {
autoPauseDelay: 60 // pause after 60 idle minutes: pay only storage
minCapacity: json('0.5')
maxSizeBytes: 34359738368 // 32 GB
}
}
output serverFqdn string = server.properties.fullyQualifiedDomainNamebicep lint sql.bicep โ no warnings
bicep build sql.bicep โ 2 resources: Microsoft.Sql/servers, servers/databases| Setting | Why |
|---|---|
| azureADOnlyAuthentication: true | Only Entra ID identities can sign in; no SQL logins to leak |
| Admin = an Entra group | Admins change by group membership, not by editing the server |
| publicNetworkAccess: Disabled | Reach it through a private endpoint (lesson 8) |
| GP_S_Gen5 + autoPauseDelay: 60 | Serverless: scales to 2 vCores, pauses after an idle hour |
Run the same engine locally
Azure SQL runs the SQL Server engine, so we used Microsoft's official SQL Server 2022 container to run every query in this lesson:
$docker run -d --name shopkart-sql -e ACCEPT_EULA=Y -e MSSQL_SA_PASSWORD="$MSSQL_SA_PASSWORD" \$ -p 1433:1433 mcr.microsoft.com/mssql/server:2022-latest$pip install pymssql
import os, pymssql
# Local SQL Server 2022 in Docker (same engine as Azure SQL Database). Password from an environment variable.
conn = pymssql.connect(server="127.0.0.1", port=1433, user="sa",
password=os.environ["MSSQL_SA_PASSWORD"], autocommit=True)
cur = conn.cursor()
cur.execute("SELECT @@VERSION")
print(cur.fetchone()[0].splitlines()[0])
cur.execute("IF DB_ID('shopkart') IS NULL CREATE DATABASE shopkart")
cur.execute("USE shopkart")Microsoft SQL Server 2022 (RTM-CU28) (KB5125472) - 16.0.4325.4 (X64)Control tables: the watermark, run for real
In our ADF course's incremental-load lesson, the watermark table and procedure couldn't be run. Here they are on a real SQL Server engine:
statements = [
"""CREATE TABLE dbo.orders (
order_id INT PRIMARY KEY,
customer_id INT NOT NULL,
product_id INT NOT NULL,
quantity INT NOT NULL,
unit_price DECIMAL(10,2) NOT NULL,
status VARCHAR(20) NOT NULL,
order_ts DATETIME2 NOT NULL,
updated_at DATETIME2 NOT NULL)""",
# The control objects from the ADF course's incremental-load lesson, now actually run:
"CREATE SCHEMA etl",
"""CREATE TABLE etl.watermark (
table_name VARCHAR(100) PRIMARY KEY,
watermark_value DATETIME2 NOT NULL)""",
"INSERT INTO etl.watermark VALUES ('orders', '1900-01-01')",
"""CREATE PROCEDURE etl.usp_update_watermark @table_name VARCHAR(100), @new_value DATETIME2
AS UPDATE etl.watermark SET watermark_value = @new_value WHERE table_name = @table_name""",
"CREATE INDEX ix_orders_updated_at ON dbo.orders (updated_at)",
]
for s in statements:
cur.execute(s)
cur.execute("SELECT name FROM sys.objects WHERE type IN ('U','P') ORDER BY name")
print([r[0] for r in cur.fetchall()])['orders', 'usp_update_watermark', 'watermark']import csv
def load_day(day):
with open(f"../pyspark/data/orders/orders_{day}.csv") as f:
rows = [(int(r["order_id"]), int(r["customer_id"]), int(r["product_id"]), int(r["quantity"]),
r["unit_price"], r["status"], r["order_ts"], r["order_ts"]) for r in csv.DictReader(f)]
cur.executemany("INSERT INTO dbo.orders VALUES (%d, %d, %d, %d, %s, %s, %s, %s)", rows)
return len(rows)
print(load_day("2026-10-01") + load_day("2026-10-02"), "orders loaded by the app")197 orders loaded by the appNow the watermark pattern itself: two lookups, a count of what Copy would move, then the procedure saves the new watermark.
def incremental_run():
cur.execute("SELECT watermark_value FROM etl.watermark WHERE table_name = 'orders'")
old = cur.fetchone()[0] # Lookup 1: old watermark
cur.execute("SELECT MAX(updated_at) FROM dbo.orders")
new = cur.fetchone()[0] # Lookup 2: new watermark
cur.execute("SELECT COUNT(*) FROM dbo.orders WHERE updated_at > %s AND updated_at <= %s", (old, new))
copied = cur.fetchone()[0] # what the Copy activity would copy
cur.execute("EXEC etl.usp_update_watermark @table_name = 'orders', @new_value = %s", (new,))
print(f"window {old} -> {new}: {copied} rows to copy")
incremental_run()
print(load_day("2026-10-03"), "new orders arrive")
incremental_run()
incremental_run() # nothing new: copies 0window 1900-01-01 00:00:00 -> 2026-10-02 23:57:18: 197 rows to copy
83 new orders arrive
window 2026-10-02 23:57:18 -> 2026-10-03 23:53:32: 83 rows to copy
window 2026-10-03 23:53:32 -> 2026-10-03 23:53:32: 0 rows to copyRun 1 copied all 197 orders (the watermark started at 1900). When the next day's 83 orders arrived, run 2 copied exactly those 83. Run 3 found nothing new. That's the incremental pattern working end to end.
MERGE: upsert from staging
# Status updates arrive in a staging table; MERGE applies them in one statement
cur.execute("CREATE TABLE #updates (order_id INT, status VARCHAR(20))")
cur.executemany("INSERT INTO #updates VALUES (%d, %s)",
[(100002, "RETURNED"), (100003, "DELIVERED"), (999999, "PLACED")])
cur.execute("""
MERGE dbo.orders AS t
USING #updates AS s ON t.order_id = s.order_id
WHEN MATCHED AND t.status <> s.status
THEN UPDATE SET status = s.status, updated_at = SYSUTCDATETIME()
WHEN NOT MATCHED BY TARGET
THEN INSERT (order_id, customer_id, product_id, quantity, unit_price, status, order_ts, updated_at)
VALUES (s.order_id, 0, 0, 1, 0, s.status, SYSUTCDATETIME(), SYSUTCDATETIME())
OUTPUT $action, inserted.order_id, inserted.status;""")
for action, order_id, status in cur.fetchall():
print(action, order_id, status)UPDATE 100002 RETURNED
INSERT 999999 PLACEDOrder 100002 changed to RETURNED, and the unknown order 999999 was inserted. Order 100003 doesn't appear: it was already DELIVERED, and our WHEN MATCHED AND t.status <> s.status condition skips no-op updates, so updated_at (and every downstream incremental load) isn't triggered for nothing. OUTPUT $action tells you exactly what MERGE did.
Columnstore for analytics
# Analytics on a row-store table: add a columnstore index for fast scans and aggregations
cur.execute("CREATE NONCLUSTERED COLUMNSTORE INDEX ncci_orders ON dbo.orders (order_ts, status, quantity, unit_price)")
cur.execute("SELECT name, type_desc FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.orders') ORDER BY index_id")
for name, kind in cur.fetchall():
print(f"{name:<28} {kind}")
cur.execute("""
SELECT CAST(order_ts AS DATE) AS day, COUNT(*) AS orders, SUM(quantity * unit_price) AS revenue
FROM dbo.orders WHERE status = 'DELIVERED' AND order_ts < '2026-10-04'
GROUP BY CAST(order_ts AS DATE) ORDER BY day""")
for row in cur.fetchall():
print(row)PK__orders__46596229DF1CB3E4 CLUSTERED
ix_orders_updated_at NONCLUSTERED
ncci_orders NONCLUSTERED COLUMNSTORE
(datetime.date(2026, 10, 1), 59, Decimal('159019.00'))
(datetime.date(2026, 10, 2), 75, Decimal('150211.00'))
(datetime.date(2026, 10, 3), 65, Decimal('137518.00'))A columnstore index stores columns compressed and separately, like Parquet, which makes scans and aggregations much faster. 1 October now shows 59 delivered orders instead of 60: the MERGE turned order 100002 into a return.
Azure SQL options
| Option | Use for |
|---|---|
| Azure SQL Database (single DB) | Most apps and control databases; serverless or provisioned |
| Hyperscale | Very large databases (up to 128 TB), fast scaling and restores |
| Elastic pools | Many small databases sharing compute |
| Azure SQL Managed Instance | Lift-and-shift of on-prem SQL Server needing instance features (SQL Agent, cross-DB) |
| SQL database in Microsoft Fabric | Operational SQL inside Fabric, mirrored to OneLake automatically |
๐ฏ Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1Azure SQL Database vs SQL Managed Instance?Fresher+
Q2How do pipelines authenticate to Azure SQL securely?1โ3 yrs+
Q3Write an upsert in T-SQL.1โ3 yrs+
Q4Reporting queries slow down the app database. Options?3+ yrs+
Key takeaways
- โAzure SQL is SQL Server as a service: your T-SQL skills apply directly.
- โServerless + Entra-only sign-in = cheap and safe defaults.
- โWe finally ran the ADF course's watermark SQL: 197 โ 83 โ 0 rows.
- โMERGE with a change condition avoids pointless updates.
Frequently asked questions
Is SQL Server in Docker the same as Azure SQL Database?
Azure SQL Database runs the same SQL Server database engine as a managed service, so T-SQL, MERGE, procedures and columnstore behave the same. Differences are around the service: no SQL Agent, cross-database queries are limited, Entra ID authentication, automatic backups and patching, serverless and Hyperscale tiers.
What is serverless Azure SQL?
A compute tier that scales vCores between a minimum and maximum automatically and can auto-pause after a period of inactivity. While paused you pay only for storage; the first connection resumes it (with a short delay).
How should pipelines sign in to Azure SQL?
With Entra ID: the data factory's or Databricks' managed identity added as a database user (CREATE USER [adf-shopkart-dev] FROM EXTERNAL PROVIDER) with only the roles it needs. Turn on Entra-only authentication so no SQL passwords exist.
Should analytics run on Azure SQL?
For small marts and dashboards, yes, especially with columnstore indexes. For large-scale analytics use a lakehouse or warehouse (Databricks, Fabric, Snowflake) and keep Azure SQL for apps, control tables and smaller serving layers.
๐ง Quick check: Azure SQL
1. The second incremental run copied how many rows?
2. Why did order 100003 not appear in MERGE's output?
3. Serverless Azure SQL while auto-paused costs...
4. Best sign-in for ADF to Azure SQL?
Checking your accessโฆ