Back to exam

DP-800 Cheatsheet

Developing AI-Enabled Database Solutions

Download free PDF

Design and develop database solutions (35–40%)

Tables, constraints and ingestion

  • **PRIMARY KEY** identifies each row; **UNIQUE** enforces candidate-key uniqueness; **FOREIGN KEY** enforces valid references. Index foreign-key columns when joins and parent changes justify it.
  • **NOT NULL** requires a value. A **DEFAULT** supplies an omitted value; it does not reject explicit NULL. A **CHECK** rejects FALSE, so account explicitly for NULL and UNKNOWN.
  • Validate text JSON with **ISJSON** in a CHECK constraint. Validate required properties separately. A unique ingestion key or indexed payload hash can reject repeated payloads; equivalent JSON can have different byte representations.
  • Choose bounded data types for keys and frequently indexed properties. **IDENTITY** belongs to a table; **SEQUENCE** is an independent number generator. Neither guarantees gapless numbering.

Graph, history and ledger tables

  • SQL graph uses **AS NODE** tables for entities and **AS EDGE** tables for directed relationships. **MATCH(a-(e)->b)** follows an edge from a to b.
  • An exactly two-hop traversal uses separate aliases: **MATCH(a-(e1)->b-(e2)->c)**. Filter the starting node and return the destination; use DISTINCT when several paths reach the same destination.
  • **Temporal tables** retain row history for time-based queries. **Ledger tables** add cryptographic tamper evidence; retain database digests outside the database for independent verification. Auditing records activity and serves a separate purpose.

Partitioning and retention

  • A **partition function** defines boundaries; a **partition scheme** maps partitions to storage. With **RANGE RIGHT**, a boundary belongs to the partition on its right, suiting midnight period starts.
  • Align table and index partitioning for partition maintenance. Date predicates can enable **partition elimination**; partitioning alone does not replace a selective index.
  • **TRUNCATE TABLE ... WITH (PARTITIONS (...))** deallocates selected partitions when restrictions are met. It still needs schema locks. Row-by-row DELETE logs deletions; unqualified TRUNCATE empties the whole table.
  • A **sliding window** retains recent periods using prepared boundaries and partition switching or truncation. Keep empty edge partitions when splitting or merging to reduce data movement.

Rowstore, columnstore and memory

  • **Rowstore B-tree indexes** suit selective lookups, ordered ranges and OLTP. **Clustered columnstore** suits large scans and aggregations, with compression, column elimination and batch processing.
  • A **nonclustered columnstore** adds an analytical copy to a rowstore table for operational analytics. Measure write overhead. A **filtered index** stores a qualifying subset and requires a supported, stable predicate.
  • **Memory-optimized tables** use optimistic concurrency. **DURABILITY = SCHEMA_ONLY** preserves schema but loses rows on restart. A **hash index** suits equality on the complete key; an ordered memory-optimized index supports ranges.

Views, functions and reusable queries

  • A **view** exposes a reusable relational query. An **indexed view** materializes results, beginning with a unique clustered index; it needs SCHEMABINDING, deterministic expressions and required SET options.
  • Aggregate indexed views have extra restrictions, including **COUNT_BIG(*)** for supported GROUP BY definitions. Materialization speeds eligible reads but adds maintenance to writes.
  • A **scalar UDF** declares RETURNS and returns one value; qualify calls with its schema. An **inline TVF** returns a SELECT that callers can join. Multi-statement TVFs can hinder cardinality estimation and optimization.
  • **DATEDIFF** counts datepart boundaries, not completed anniversaries. For complete years, adjust for whether the anniversary has occurred. Use **SYSUTCDATETIME()** for a high-precision UTC timestamp.

Windows, CTEs and correlated queries

  • **ROW_NUMBER() OVER (PARTITION BY CustomerId, Day ORDER BY CreatedAt, TicketId)** ranks each customer's daily rows. Filter row number 1 in an outer query; a unique tie-breaker makes the result deterministic.
  • A running total uses **SUM(Amount) OVER (PARTITION BY AccountId ORDER BY EventTime, EventId ROWS UNBOUNDED PRECEDING)**. Windows preserve detail rows; GROUP BY collapses them.
  • **EXISTS** tests for matching rows without multiplying the outer result. A correlated subquery references the outer row. **WHERE** filters rows; **HAVING** filters groups.
  • A **CTE** names a query expression; it is not inherently materialized. **CROSS APPLY** retains matching right-side rows; **OUTER APPLY** also preserves left rows when the right side is empty.

JSON extraction, shaping and indexing

  • **JSON_VALUE** extracts a scalar; **JSON_QUERY** extracts an object or array; **OPENJSON** produces relational rows. Use an explicit WITH schema to control types and extract long text.
  • Text-input **JSON_VALUE** returns nvarchar(4000); oversized scalars need another extraction pattern. **ISJSON** checks syntax, while JSON paths and typed conversion validate the properties the application needs.
  • **FOR JSON PATH** builds nested output. Correlate a child query to each parent and wrap nested JSON with **JSON_QUERY** to prevent double escaping. WITHOUT_ARRAY_WRAPPER suits a result known to contain one object.
  • Index frequently filtered JSON properties through suitably typed **computed columns**. Match the query expression to the indexed expression; use INCLUDE columns to cover returned data. Avoid oversized string index keys.

Regular expressions and fuzzy matching

  • **REGEXP_SUBSTR** extracts a matching substring and returns NULL for no match. **REGEXP_LIKE** tests a pattern; **REGEXP_REPLACE** transforms matches. Extract a JSON scalar before applying text operations.
  • Strip phone formatting with **REGEXP_REPLACE(value, '[^0-9]', '')**. For email subaddressing, remove the plus-tag within the local part while preserving the at-sign and domain. Preserve NULL and handle missing matches explicitly.
  • Regex support and input limits depend on the target engine. Bound text only when the relevant content is guaranteed to fit; a cast to nvarchar(4000) can discard a later match.
  • **EDIT_DISTANCE** measures edits; fewer means closer. **EDIT_DISTANCE_SIMILARITY** returns a similarity score where higher means closer. Fuzzy spelling similarity, full-text keyword matching and embedding-based semantic similarity answer different questions.

Triggers and reliable transactions

  • DML triggers run once per **statement**, so use set-based joins to **inserted** and **deleted**. An AFTER UPDATE timestamp trigger must handle multiple rows and guard its own recursive update path.
  • **UPDATE(column)** reports that an update targeted the column, even if the value stayed the same. Compare inserted and deleted values when actual value changes matter.
  • **DISABLE TRIGGER trigger_name ON DATABASE** suspends a database DDL trigger without dropping it; re-enable after the controlled operation. DDL triggers respond to schema events, not row changes.
  • Combine **SET XACT_ABORT ON**, TRY/CATCH and an explicit transaction. In CATCH, roll back when **XACT_STATE() <> 0**, then **THROW** to preserve error details. XACT_STATE = -1 means the transaction cannot commit.

AI-assisted development and MCP

  • Give **GitHub Copilot** schema definitions and synthetic examples when real data is restricted. Review generated SQL for correctness, expensive scans and destructive operations before execution.
  • SQL executed through the active database connection follows that identity's **database permissions**, including RLS. Azure resource RBAC and GitHub permissions do not substitute for SQL data permissions.
  • **.github/copilot-instructions.md** stores repository guidance. Use personal editor settings for a local opt-out. Applicable instructions and precedence differ by Copilot surface; instructions cannot grant access or override enforced policy.
  • **MCP** exposes authorized tools and live context such as database metadata. Scope VS Code server configuration to **.vscode/mcp.json** for the workspace, use OAuth where supported, and keep credentials out of committed files.

Secure, optimize, and deploy database solutions (35–40%)

Identity, permissions and private connectivity

  • Enable an Azure app's **managed identity**, create its database principal with **CREATE USER [identity] FROM EXTERNAL PROVIDER**, and grant only needed SELECT, DML or EXECUTE permissions. Configure the client for Entra token authentication.
  • A **system-assigned identity** follows its host lifecycle; a **user-assigned identity** can be shared and retained independently. An on-premises app needs a supported Entra flow, such as certificate-based service-principal authentication.
  • **GRANT EXECUTE** authorizes a procedure; **GRANT SELECT** authorizes reads. A column-level DENY can reject a direct query that requests that column. Review procedures and ownership chaining as separate exposure paths.
  • For App Service outbound private database access, combine **VNet integration**, a SQL **private endpoint** and correct private DNS. Disable public network access when required; a private endpoint alone does not disable it.

Encryption, masking and tenant isolation

  • **TDE** encrypts database files at rest. **Always Encrypted** protects selected column values through an enabled client driver and separately controlled keys; a column master key can be protected by Key Vault.
  • Ordinary **deterministic encryption** supports equality comparisons but reveals repeated values. **Randomized encryption** hides repetition and limits server comparisons. **Secure enclaves** enable additional supported operations under a different trust model.
  • **Dynamic data masking** changes results for users without UNMASK; it does not encrypt stored values or prevent inference. The built-in email mask does not preserve an arbitrary original domain; use a controlled projection for that requirement.
  • **RLS** uses an inline TVF and a security policy. Filter predicates restrict visible rows; block predicates reject prohibited writes. A membership table supports users assigned to multiple fleets or tenants.
  • If a pooled app supplies **SESSION_CONTEXT**, establish and validate trusted tenant context for each connection. Keep filtering inside the database and retrieval path so unauthorized rows never become LLM context.

Isolation, blocking and deadlocks

  • **READ COMMITTED** prevents dirty reads. With **RCSI**, statement reads use row versions; **SNAPSHOT** provides transaction-level versioned reads. Row versioning reduces reader-writer blocking but does not eliminate writer conflicts.
  • **REPEATABLE READ** holds locks on read rows to transaction end; new qualifying rows can still appear. **SERIALIZABLE** also protects key ranges against phantoms, reducing concurrency.
  • Use **sys.dm_exec_requests** for active requests and blocking_session_id; join **sys.dm_exec_sessions** to include idle blockers. **sys.dm_exec_input_buffer** shows submitted commands; **sys.dm_tran_locks** helps identify held and requested locks.
  • A **sleeping session with an open transaction** can retain locks. Diagnose transaction ownership before terminating it; rollback can take time. Blocking is waiting, while a **deadlock** is a dependency cycle with a chosen victim.
  • Keep transactions short and access objects in a consistent order. Retry a deadlock victim's entire transaction with bounded backoff; timeouts and failed commands must not leave transactions open.

Execution plans and index tuning

  • Use a half-open daily range: **CreateDate >= @Day AND CreateDate < DATEADD(day, 1, @Day)**. Keep the indexed column unmodified and parameter types compatible to support a range seek.
  • For a selective customer filter plus date range and ordering, consider **(CustomerId, OrderDate)** as index keys. Include output columns such as Status and Amount to reduce **key lookups**; verify the actual plan.
  • Match index key order to equality, range and ordering needs. A scan can be appropriate for a large result; an index seek alone does not prove an efficient plan.
  • Check estimated versus actual rows, lookup counts, spills, sorts and logical reads. Maintain relevant statistics and assess parameter-sensitive plans before adding indexes or hints.

Query Store and regression recovery

  • **Query Store** persists query texts, plans and runtime statistics. **Query Performance Insight** helps identify resource-heavy queries; compare historical and recent plans and execution counts for the same workload.
  • After confirming a regression, **sys.sp_query_store_force_plan** can restore a known good persisted plan without an application change. Monitor forcing failures and remove the force when the underlying issue is resolved.
  • Aggregate approximate total CPU as **SUM(avg_cpu_time * count_executions)** across relevant runtime rows and plans. Join runtime-stat intervals for the time window and group by query hash when that is the requested unit.
  • Interval aggregates can overlap the requested time boundary. Weight averages by execution count; summing averages alone misstates total work. **DBCC FREEPROCCACHE** discards cached plans rather than selecting a known good plan.

SQL projects and controlled delivery

  • An **SDK-style SQL project** models desired schema and builds a **.dacpac**. Use the target-platform system reference, such as **Microsoft.SqlServer.Dacpacs.Azure.Master**, for Azure SQL system objects; verbose build logs do not fix missing references.
  • Run **dotnet build Database.sqlproj -c Release** and deploy the matching **bin/Release** artifact. Build pull requests before merge; protect the production branch with required checks, review and ownership rules.
  • Fetch the latest main branch, merge or rebase it into the feature branch, resolve conflicts, push, and create the pull request. Use **pull_request** for validation and **workflow_dispatch** for manual workflow starts.
  • Publish with **SqlPackage /Action:Publish** or a SQL deployment action. Keep credentials in protected secrets or use supported federated identity; a stored SQL connection string alone does not imply workload identity authentication.
  • **DeployReport** compares a source model with a target to preview deployment changes. **DriftReport** reports changes since a database's registered baseline. **Extract** captures schema; **Script** generates deployment SQL.
  • Put reference data in an **idempotent post-deployment script** with stable unique keys and guarded inserts or carefully designed upserts. Validate repeated deployment and test schema behavior before production release.

Data API builder and Fabric GraphQL

  • **DAB entities** map tables, views or procedures to API names. The default REST route is **/api/EntityName** on the deployed host; the entity name and configured path need not match the SQL table name.
  • Configure permissions per entity and action. **anonymous** permits unauthenticated callers; **authenticated** requires a validated identity. **read**, **create**, **update**, **delete** and procedure **execute** are distinct permissions.
  • DAB configuration can resolve **@env('MSSQL_CONNECTION_STRING')**. Container Apps secret references populate environment variables; a secret name is not itself a SQL connection string. Expose only intended entities and operations.
  • Container Apps **external ingress** exposes the API publicly; the target port must match the container listener. Healthy process probes do not prove database connectivity: check DNS, firewall, identity and SQL permissions separately.
  • SQL's **0.0.0.0** firewall rule enables access from Azure services broadly, including other subscriptions. It does not provide subscription isolation; use scoped network controls or private connectivity when required.
  • For **Fabric API for GraphQL**, assess both item access and source authorization. The connection identity mode determines whose SQL permissions apply; granting workspace or API access alone does not establish every underlying data permission.

Change-driven integration

  • The **Azure Functions SQL trigger binding** uses **Change Tracking**, enabled at database and table levels, with a primary key. **Sql_Trigger_PollingIntervalMs** controls polling and **Sql_Trigger_MaxBatchSize** limits changes per invocation.
  • A polling interval is not a guaranteed end-to-end deadline. Function startup, backlog and execution time affect latency. Use SQL input bindings for reads and output bindings for writes; these are separate from the trigger binding.
  • **Change Tracking** identifies changed keys and operations; fetch current row values as needed. **CDC** captures change data for incremental consumers. Choose based on whether the consumer needs current state or change history.
  • Enable CDC at database and table levels. **@captured_column_list** selects captured data; **@supports_net_changes = 1** requires a suitable unique key. Consumer checkpoints and retention must prevent missed changes.

Implement AI capabilities in database solutions (25–30%)

Embedding and chunk design

  • **Embeddings** map content into a model-specific vector space. Embed rich descriptive text such as titles, incident narratives and document bodies; keep identifiers, price and category as structured metadata for filtering.
  • **Chunking** limits retrieval size and token use. Split at meaningful headings or paragraphs, use measured overlap, and retain document ID, chunk order and source text so results can be traced and reconstructed.
  • Store embeddings in **VECTOR(n)** columns whose dimensions match the model output. Generate query and document vectors with compatible models and preprocessing; equal dimensions do not make different models comparable.
  • When changing embedding models, **regenerate existing embeddings** and transition query generation consistently. Use a parallel column or table for a controlled cutover; rebuild affected indexes and evaluate retrieval quality.

External models and secure inference

  • **CREATE EXTERNAL MODEL** records an inference location, API format, model purpose and credential. **AI_GENERATE_EMBEDDINGS** generates vectors using the configured external model.
  • Grant the application **EXECUTE ON EXTERNAL MODEL::model_name**, rather than database CONTROL. Separate model administration from inference permission and restrict endpoint access to the required identity.
  • SQL Server can use a supported **local ONNX runtime** for embedding generation without outbound model calls. Provision compatible model, tokenizer and runtime files and required engine settings; a remote endpoint still needs network connectivity.
  • Prefer **managed identity** for supported Azure inference calls. Configure a database-scoped credential or client token flow with the correct audience, model-service role and endpoint; changing the model does not automatically change authentication.

Incremental embedding maintenance

  • Maintain embeddings from **changed source content** using Change Tracking, CDC or another change-driven worker. Avoid regenerating every row when only a small subset changed.
  • Keep remote inference outside the OLTP transaction when possible. A synchronous trigger can add network latency, failures and model cost to every write; a durable asynchronous worker isolates that work.
  • Track document revision, content hash and model identity. Make processing **idempotent**, handle deletions, and publish an embedding only if it still corresponds to the current source revision.
  • Capture the primary key and content needed to embed. Excluding the embedding column from captured data does not by itself filter all irrelevant events; workers must avoid feedback loops and re-embed only meaningful changes.

Exact and approximate vector search

  • **VECTOR_DISTANCE** measures distance between compatible vectors. Order cosine or Euclidean distances ascending for nearer results; calculating distance across every eligible row provides exact neighbors but can be CPU intensive.
  • **VECTOR_SEARCH** supports **approximate nearest neighbor (ANN)** retrieval using a compatible vector index. ANN trades some recall for speed; a normal B-tree or full-text index does not index vector similarity.
  • Keep the index's vector column and **metric** consistent with the query. **Cosine**, **dot** and **Euclidean** have different scoring behavior; normalize vectors only when the model and chosen metric require it.
  • **VECTOR_NORMALIZE** rescales vectors and **VECTORPROPERTY** inspects vector metadata. Neither regenerates embeddings into a new model's semantic space.
  • Match syntax and capabilities to the target engine and index generation. Apply authorization and structured filters, then measure returned candidate count, recall, latency and CPU under realistic concurrent load.

Full-text, hybrid search and rank fusion

  • **CONTAINS** filters full-text matches; **CONTAINSTABLE** returns matching keys and relevance RANK. Full-text search uses linguistic keyword processing; vector search retrieves semantically related content.
  • **Hybrid search** combines the candidate sets or filters and reranks one set. Joining ANN candidates to keyword matches produces an intersection; unioning candidates improves coverage but needs deduplication.
  • **Reciprocal rank fusion (RRF)** combines ranks as a sum of **1 / (k + rank)**. It avoids directly mixing incompatible raw scores and helps fuse independently ranked fields or chunk collections.
  • For a weighted blend, align score direction and scale first: lower vector distance and higher full-text rank cannot be added unchanged. Deduplicate document hits so many small chunks do not unfairly dominate.
  • In **Azure AI Search**, combine search text with vectorQueries and enable **queryType: semantic** plus a semanticConfiguration. Supply enough candidates, commonly vector k = 50, before reranking; top controls returned results.
  • Request **captions: extractive** and **answers: extractive** when needed. Extractive answers require suitable answer-bearing text and are not guaranteed for every query; restrictive filters can reduce the available result count.

Grounded generation and JSON exchange

  • **RAG** retrieves current authorized evidence and supplies it with the question to an LLM. It suits company-specific answers without retraining whenever data changes; retrieval freshness and evidence quality still govern reliability.
  • Retrieve relevant chunks and needed relational facts, preserve source identifiers, and build a bounded prompt. Treat retrieved instructions as untrusted data; ask for evidence-based answers and allow an insufficient-evidence response.
  • Serialize structured context with **FOR JSON PATH** or JSON constructors, then call the supported HTTPS endpoint with **sys.sp_invoke_external_rest_endpoint**. Validate status, response structure and errors before consuming content.
  • Parse a scalar answer with **JSON_VALUE** at the actual response path. Chat-completion bodies commonly use **$.choices[0].message.content**; a REST procedure wrapper may add **$.result**. Use **OPENJSON WITH** for longer scalar text.
  • Embedding responses contain numeric arrays: use **JSON_QUERY** or typed OPENJSON extraction before conversion to VECTOR. Cache reuse must respect tenant authorization, model identity and underlying content freshness.