Fun with Learning Technology
LearnCoursesQuestionsTracksToolsNewsExplorePractice
Fun with Learning Technology

A new problem, explained clearly, every day.

Subscribe
Learn
  • Lessons
  • Topics
  • News
  • Tools
  • Courses
  • Career tracks
  • Everything
Site
  • About
  • Contact
  • Support
  • Privacy
  • Terms
Get the daily one

One email per new problem. No spam.

Request a tutorial

Requests shape what gets made next.

© 2026 Fun with Learning TechnologyRSS
Home›Courses›Microsoft Azure›Azure SQL Database and Cosmos DB

Data and Analytics

Azure SQL Database and Cosmos DB

Azure SQL Database provides a managed, fully featured relational engine for traditional structured workloads, while Cosmos DB offers a globally distributed, multi-model NoSQL service for massive scale. Understanding the fundamental trade-off between strict relational consistency and massive horizontal availability is critical for architecting modern applications. These services form the backbone of data persistence in Azure, allowing you to choose the exact right balance between schema rigidity and architectural flexibility.

Azure SQL Database: The Relational Foundation

Azure SQL Database is a platform-as-a-service offering built on the industry-standard relational engine, designed to handle transactional workloads where data integrity and consistency are non-negotiable. By abstracting away the underlying infrastructure, it automates backups, high availability, and performance tuning, allowing developers to focus on query optimization and schema design. The core strength of this service lies in its support for ACID properties, ensuring that complex financial or administrative transactions are processed reliably, even in the event of system failures. You should reach for this service when your application requires complex joins, referential integrity across multiple tables, or existing procedural code migration. Because it utilizes a structured schema, it provides a highly predictable performance profile for well-defined queries, making it the bedrock for enterprise business applications that rely on structured reports and stable, consistent data models that do not change frequently.

-- Create a standard relational table for user orders
CREATE TABLE Orders (
    OrderID INT PRIMARY KEY,
    CustomerID INT NOT NULL,
    OrderDate DATETIME DEFAULT GETDATE(),
    TotalAmount DECIMAL(18, 2)
);
-- Insert a sample transaction record
INSERT INTO Orders (OrderID, CustomerID, TotalAmount) 
VALUES (101, 5001, 299.99);

Cosmos DB: Global Distribution and NoSQL Flexibility

Cosmos DB is a globally distributed, multi-model database service designed for scenarios requiring extreme horizontal scale and low-latency access across disparate geographic regions. Unlike traditional databases, it abandons the requirement for a strict, predefined schema, allowing you to store JSON documents that evolve alongside your application. The fundamental innovation here is its ability to provide tunably consistent data replication; you choose the level of consistency—from strong to eventual—that aligns with your application's tolerance for lag versus performance speed. This service is ideal for high-velocity telemetry, global retail product catalogs, or applications requiring near-instant responsiveness for users regardless of their physical location. Because data is partitioned across shards, you must carefully choose a partition key that ensures even distribution of traffic to avoid hotspots. By leveraging this architecture, you gain the capability to handle millions of requests per second while maintaining millisecond response times globally.

// Conceptual JSON document structure for Cosmos DB
{
  "id": "user_profile_001",
  "username": "jdoe",
  "preferences": {
    "theme": "dark",
    "notifications": true
  },
  "lastLogin": "2023-10-27T10:00:00Z"
}

Choosing Between Structured and Unstructured Data

The decision to use Azure SQL Database versus Cosmos DB should primarily be driven by the nature of your data relationships and the expected evolution of your data model. If your data is highly relational, requires deep analytical joins across complex entities, and maintains a fairly static schema, Azure SQL Database provides a robust ecosystem that enforces data quality at the engine level. Conversely, if your application data is semi-structured, highly dynamic, or requires massive global scale where traditional vertical scaling is insufficient, Cosmos DB is the superior choice. The cost of migration from a rigid relational schema to a NoSQL document-based approach is high, so selecting the correct paradigm early in the development lifecycle is critical. Consider the query patterns: if you need to perform ad-hoc reporting and complex set operations, the relational engine is optimized for these tasks, whereas if you need point-lookups and simple range queries at extreme concurrency, the document model is more efficient.

-- T-SQL snippet to retrieve joined relational data
SELECT O.OrderID, C.CustomerName
FROM Orders O
JOIN Customers C ON O.CustomerID = C.CustomerID
WHERE O.TotalAmount > 100;

Performance and Scalability Patterns

Performance in Azure SQL Database is managed via Database Transaction Units or vCores, which provide a predictable resource footprint for your queries. As your load increases, you can scale these resources vertically with minimal downtime, ensuring that large, compute-intensive operations do not starve critical transactional processes. In contrast, Cosmos DB scales by adding Request Units, which represent the consumption of CPU, memory, and IOPS needed to serve a request. Because Cosmos DB is distributed by design, performance is tied to how effectively you partition your data; a well-chosen partition key allows the service to route requests directly to the relevant physical shard without a global broadcast search. You should reason about your data access patterns before deployment: if your queries frequently touch a specific subset of data, align your partitioning strategy to keep that data localized, thereby reducing network latency and improving throughput across all globally distributed replicas.

// Example of selecting a partition key in Cosmos DB container
// Choosing 'userId' as the partition key ensures queries for specific
// users are routed efficiently to a single physical partition.
const containerDefinition = {
  id: "UserSessions",
  partitionKey: { paths: ["/userId"] }
};

Security, Governance, and Disaster Recovery

Both services provide comprehensive security features, including identity management through Entra ID, transparent data encryption at rest, and firewall controls to restrict network access to authorized subnets only. For Azure SQL Database, features like dynamic data masking and row-level security allow fine-grained access control, ensuring that sensitive information is visible only to authorized personnel. Cosmos DB provides similar granular control using role-based access, but because it is a document store, security often relies on application-level logic to sanitize and validate input before persistence. Regarding disaster recovery, Azure SQL Database offers active geo-replication to secondary regions with automated failover capabilities to maintain business continuity. Cosmos DB takes a slightly different approach by allowing multi-region writes, where every region is essentially an active participant in the database, offering near-zero recovery time objectives by design. Designing for high availability requires an understanding of these recovery models so your architecture can survive regional outages seamlessly.

-- Enable Transparent Data Encryption (TDE) for Azure SQL
ALTER DATABASE [ProductionDB] SET ENCRYPTION ON;

Key points

  • Azure SQL Database is optimized for structured, relational data requiring strict consistency and complex transactional integrity.
  • Cosmos DB excels in high-scale, globally distributed environments where low latency and flexible JSON schema evolution are prioritized.
  • The choice between these services should depend on the relational complexity of the data and the expected growth of the system.
  • Relational databases use vertical scaling, while Cosmos DB relies on horizontal partitioning across multiple physical shards.
  • Performance in Cosmos DB is governed by Request Units, which measure the cost of database operations on system resources.
  • Partitioning strategy is the single most important factor for maintaining performance in a globally distributed Cosmos DB environment.
  • Azure SQL Database offers mature tools for administrative tasks, including point-in-time restores and advanced security features like masking.
  • Both services provide high-availability options, but they differ significantly in their approach to cross-region replication and write consistency.

Common mistakes

  • Mistake: Choosing Azure SQL Database for heavy unstructured data workloads. Why it's wrong: Relational schemas are rigid and inefficient for polymorphic data. Fix: Use Azure Cosmos DB to leverage schema-agnostic JSON storage.
  • Mistake: Failing to define a proper Partition Key in Cosmos DB. Why it's wrong: Poor partitioning leads to hot partitions, performance bottlenecks, and higher costs. Fix: Choose a high-cardinality property that distributes requests evenly.
  • Mistake: Over-provisioning DTUs or RU/s for idle databases. Why it's wrong: This results in unnecessary monthly spend without performance gains. Fix: Enable Serverless tier for unpredictable traffic or autoscale provisioned throughput.
  • Mistake: Assuming Azure SQL Database automatically handles all application-level connection pooling. Why it's wrong: Improper connection management can lead to exhaustion of socket resources. Fix: Use client-side connection pooling and implement resilient retry logic via transient fault handling.
  • Mistake: Misconfiguring consistency levels in Cosmos DB for read-heavy applications. Why it's wrong: Strong consistency impacts latency and availability compared to eventual or session consistency. Fix: Select the weakest consistency level that still meets your application's business requirements.

Interview questions

What is the primary difference between Azure SQL Database and Azure Cosmos DB in terms of their data models?

Azure SQL Database is a relational database service based on the Microsoft SQL Server engine, which uses a structured schema with tables, rows, and columns to organize data using SQL. In contrast, Azure Cosmos DB is a globally distributed, multi-model NoSQL database service that provides high flexibility by supporting documents, key-value pairs, graphs, and column-family data structures. You choose Azure SQL Database when you need strong ACID compliance and structured relational integrity, whereas you choose Cosmos DB when your application requires massive scalability, low-latency globally distributed data access, and a schemaless design that can evolve rapidly without downtime.

How does scaling differ between Azure SQL Database and Azure Cosmos DB?

Azure SQL Database offers scaling primarily through compute tiers like DTUs (Database Transaction Units) or vCore-based options, where you scale vertically by increasing the resources of a single server instance, or horizontally using read scale-out replicas. Cosmos DB, however, is built for elastic horizontal scale. It scales by partitioning data across multiple logical and physical partitions. You provision Request Units per second (RU/s), and the system automatically distributes your data and throughput across a distributed cluster. This makes Cosmos DB significantly better at handling unpredictable, bursty workloads that require massive throughput across multiple geographical regions simultaneously.

When would you prefer using the serverless tier of Azure SQL Database over the provisioned throughput of Cosmos DB?

You should choose the serverless compute tier of Azure SQL Database when you have intermittent, unpredictable, or low-utilization workloads that do not warrant a constant, expensive compute allocation. Serverless automatically scales compute based on workload demand and bills for the amount of compute used per second. Conversely, while Cosmos DB also offers a serverless mode, you would prefer Azure SQL Database specifically when your application is built on traditional relational foundations, relies heavily on complex T-SQL stored procedures, and needs the ease of management found in an environment that auto-pauses during inactive periods to save on costs.

How do you ensure data consistency in both services?

In Azure SQL Database, consistency is managed via standard relational database isolation levels, ensuring ACID properties where every transaction is strictly consistent, usually following the 'Strong' consistency model. Cosmos DB is unique because it offers five well-defined consistency levels: Strong, Bounded Staleness, Session, Consistent Prefix, and Eventual. By choosing a level like Session, you provide a balance between performance and consistency for single-user scenarios. You choose based on your trade-off needs: if your global application requires absolute immediate consistency across replicas, you select Strong, but if you need higher availability and lower latency, you may opt for Session or Eventual consistency.

Explain how you would implement a globally distributed architecture using these services.

To implement global distribution in Azure SQL Database, you would use Auto-Failover groups, which provide a read-write endpoint that remains the same during a failover, and you manually or automatically sync data to secondary regions. Cosmos DB is 'born global.' You simply add regions to your Azure subscription for your database account, and it automatically replicates data to those regions. For example, if you are using the Cosmos DB .NET SDK, you can set `ApplicationRegion = Regions.WestUS`. The client automatically discovers the closest region, reducing latency significantly compared to the manual replication overhead often required when configuring geo-replication in a relational SQL environment.

Compare the approach to schema management and indexing in Azure SQL Database versus Azure Cosmos DB.

In Azure SQL Database, schema management is strict; you define your tables, data types, and primary/foreign keys upfront, and changes require `ALTER TABLE` statements which can lock tables. Indexing is manually managed via `CREATE INDEX` to optimize query plans. Cosmos DB is schema-agnostic, meaning you can insert JSON documents without a predefined structure. It uses an 'index-by-default' policy where it automatically indexes every attribute in the document, which allows for fast queries without manual tuning. However, you can use an indexing policy to exclude specific paths to save on storage and RU costs, providing a trade-off between flexible development and performance optimization.

All Microsoft Azure interview questions →

Check yourself

1. An application requires ACID compliance for complex transactions and relational modeling. Which service is the optimal choice?

  • A.Azure Cosmos DB using the Core (SQL) API
  • B.Azure SQL Database
  • C.Azure Cosmos DB using the Table API
  • D.Azure Storage Tables
Show answer

B. Azure SQL Database
Azure SQL Database is a relational engine designed for ACID-compliant transactions and complex join operations. Cosmos DB is NoSQL, which prioritizes horizontal scale over complex relational constraints, and the other options lack full ACID support for relational schemas.

2. Which strategy most effectively mitigates a 'hot partition' issue in Azure Cosmos DB?

  • A.Increasing the Request Units (RU/s) of the collection
  • B.Switching the consistency level to Strong
  • C.Choosing a partition key with high cardinality and even distribution
  • D.Implementing a stored procedure for data access
Show answer

C. Choosing a partition key with high cardinality and even distribution
A high-cardinality partition key ensures data is spread across physical partitions, preventing one partition from handling the majority of traffic. Increasing RU/s just masks the issue; consistency levels don't address partitioning; stored procedures can actually exacerbate hot partitions.

3. When migrating an on-premises SQL Server instance to Azure, which deployment option allows for the most compatibility with existing features while minimizing infrastructure management?

  • A.Azure SQL Database (SQL Managed Instance)
  • B.Azure SQL Database (Single Database)
  • C.SQL Server on Azure Virtual Machines
  • D.Azure SQL Edge
Show answer

A. Azure SQL Database (SQL Managed Instance)
Managed Instance provides near 100% surface area compatibility with on-premises SQL Server, including agent jobs and cross-database queries. Single Database has limitations on cross-database logic, and Virtual Machines require significant manual OS patching.

4. An application needs global distribution with low latency writes across multiple regions. Which feature is native to Cosmos DB to support this?

  • A.Multi-master (multi-region writes)
  • B.Database-level sharding
  • C.Read-only replicas configured via a load balancer
  • D.Elastic pools
Show answer

A. Multi-master (multi-region writes)
Cosmos DB supports multi-region writes (multi-master), allowing applications to write to the nearest local region with minimal latency. Elastic pools are for SQL Database density; the other options do not offer native, transparent global write capabilities.

5. Why would an architect choose the 'Serverless' tier for an Azure SQL Database?

  • A.To achieve the highest possible throughput for sustained heavy workloads
  • B.To manage costs for databases with intermittent or unpredictable usage patterns
  • C.To avoid needing a primary-secondary database replica
  • D.To use advanced security features not available in provisioned tiers
Show answer

B. To manage costs for databases with intermittent or unpredictable usage patterns
Serverless automatically scales compute based on workload demand and pauses during inactivity, optimizing cost for intermittent usage. Provisioned tiers are better for sustained workloads, and all tiers provide high availability by default.

Take the full Microsoft Azure quiz →

← PreviousAzure DatabricksNext →Azure Event Hub and Service Bus

Microsoft Azure

19 lessons, free to read.

All lessons →

Track your progress

Sign in to mark lessons done, score quizzes and keep notes.

Open in the app