skills/cosmosdb-nosql-query-generation/SKILL.md
Generate, explain, edit, and fix Azure Cosmos DB for NoSQL (SQL API) queries. Use whenever you need to produce a syntactically correct, safe Cosmos DB NoSQL query — for example when the user asks to generate, write, edit, fix, or explain a Cosmos DB NoSQL query. Provides the NoSQL dialect rules, safety rules, and few-shot examples. Covers SELECT/VALUE/DISTINCT/TOP, array-unwind JOINs, subqueries, WHERE/BETWEEN/IN/LIKE, GROUP BY and aggregates, ORDER BY and ORDER BY RANK, OFFSET/LIMIT, the full built-in function reference, and how Cosmos DB NoSQL differs from T-SQL / PostgreSQL / MySQL.
npx skillsauth add microsoft/vscode-cosmosdb cosmosdb-nosql-query-generationInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
The single source of truth for writing syntactically correct, safe Azure Cosmos DB for NoSQL (SQL API) queries. This skill is host-agnostic — it covers only the query language itself. Apply these rules whenever you produce a Cosmos DB NoSQL query.
Ground yourself on the real schema first. Never invent property names, types, or casing. When a container schema, sample document, or query history is available, use the exact property names from it. If you have no schema, inspect the data first (for example
SELECT TOP 1 * FROM c) rather than guessing.VS Code Query Editor: when running inside VS Code against the active Cosmos DB Query Editor, the
cosmosdb-nosql-query-editorskill drives the editor tools (read context, sample schema, apply, and run the query) and delegates all query-language rules to this skill.
ERROR: followed by a brief explanation (e.g.
ERROR: This request requires generating Python code, which is not supported.).ERROR: Cannot replay previous queries. Please provide a new query description.ERROR: This is not a query-related prompt. Please describe the data you want to query.SELECT. Never emit INSERT, UPDATE,
DELETE, DROP, etc.-- ... for a single line or /* ... */ for
multiple lines. Never emit bare prose, bullet lists, or markdown fences around or
between query lines.-- ... and block comments /* ... */ are valid and skipped by the
parser. Do not use # or // — they are not valid."..." or single quotes '...' (both accepted).
Single quotes are ONLY for string values, never around property names.c["propertyName"]. Otherwise use dot notation: c.propertyName.{alias}.{property}. The default container alias is c (e.g.
SELECT c.name FROM c). Rename with FROM Products p or FROM Products AS p.@name (e.g. WHERE c.id = @id, TOP @n, OFFSET @skip LIMIT @take).!= for inequality (not <>, not IS NOT) and = for equality (not ==).||. Coalesce is ?? (right-associative): c.discount ?? 0.
Ternary is cond ? a : b. Arithmetic: + - * / %. Bitwise: & | ^ ~ << >>.SELECT * returns the full document and is valid only when the FROM clause declares
exactly one alias. Never use SELECT * with a JOIN — project specific properties.SELECT VALUE expr unwraps to a scalar/array stream. Use it for scalar projections and
aggregates. Do NOT combine AS with SELECT VALUE (SELECT VALUE c.name AS n is
invalid).SELECT DISTINCT ... removes duplicate rows. For all unique values of a property use
SELECT DISTINCT VALUE c.propertyName FROM c, not SELECT DISTINCT c.propertyName.SELECT TOP n ... limits returned rows. n must be an integer literal or @parameter
— never a float or property reference. Combine: SELECT DISTINCT TOP 3 c.category FROM c.SELECT {"id": c.id, "label": c.name} FROM c. Array literals:
SELECT [c.price, c.rating] FROM c.AS aliasName or expr aliasName; format aliases in camelCase.SELECT TOP 1 * FROM c.FROM c, FROM Products p) or a subquery:
FROM (SELECT c.id, c.price FROM c WHERE c.inStock = true) sub.JOIN is not a relational join — it is an array unwind
(cross-product with an array property of the same document):
JOIN alias IN c.arrayProperty. Multiple JOINs are allowed.JOIN ... IN c.array or
EXISTS(SELECT VALUE ... FROM x IN c.array WHERE ...). Direct dotted access like
c.items.name will not match array elements.ARRAY(SELECT VALUE ... FROM i IN c.items),
FIRST(SELECT VALUE ... ORDER BY ...), LAST(SELECT VALUE ...), and
(SELECT VALUE COUNT(1) FROM i IN c.items).EXISTS(SELECT VALUE ... FROM ... WHERE ...) returns a boolean; negate with
NOT EXISTS(...).= != < <= > >=. Logical: AND OR NOT.BETWEEN low AND high (operand evaluated once). NOT BETWEEN
is supported. When combining BETWEEN with logical AND, wrap the BETWEEN in
parentheses, otherwise the parser consumes the trailing AND as the BETWEEN
separator: WHERE (c.price BETWEEN 10 AND 100) AND c.category = "Books".IN (v1, v2, ...) and NOT IN (...) for set membership (the list cannot be empty).LIKE / NOT LIKE use % (any sequence) and _ (single character) wildcards.IS_NULL, IS_DEFINED, IS_STRING, IS_NUMBER, IS_INTEGER, IS_BOOL,
IS_ARRAY, IS_OBJECT, IS_PRIMITIVE, IS_DATETIME, IS_FINITE_NUMBER. Use
NOT IS_DEFINED(c.brand) for "missing property".id), assume string filters are
case-insensitive: pass the case-insensitivity flag to Contains, StartsWith,
EndsWith, StringEquals, etc., or use the *CI variants. Do not normalize with
LOWER/UPPER inside CONTAINS.GROUP BY groups by one or more expressions: GROUP BY c.category, c.inStock.HAVING.COUNT, SUM, AVG, MIN, MAX, CountIf, MakeList, MakeSet.SELECT VALUE COUNT(1) FROM c (scalar). Do NOT
alias with AS, do NOT use COUNT(*) or COUNT(c) (both invalid). With GROUP BY,
COUNT(1) AS cnt is valid:
SELECT c.category, COUNT(1) AS cnt FROM c GROUP BY c.category.DISTINCT inside COUNT (COUNT(DISTINCT ...) is unsupported).ORDER BY expr [ASC|DESC] [, expr2 [ASC|DESC] ...]. Default is ASC.c.propertyName). Do NOT
order by computed columns, SELECT aliases, subquery aliases, or aggregate results, and
do NOT order by when the FROM clause is a subquery.ORDER BY c.category ASC, c.price DESC), but
multi-property or mixed-direction ORDER BY requires a composite index. Prefer
single-property ORDER BY; add a SQL comment noting the composite-index requirement when
multi-property ORDER BY is necessary.ORDER BY c.shipping.address.city ASC.ORDER BY RANK <scoreFunction>(...) where the operand is a
function call: FullTextScore(c.body, "term"), VectorDistance(c.embedding, @query),
or RRF(FullTextScore(...), VectorDistance(...)) for hybrid search. ASC/DESC are
NOT allowed with ORDER BY RANK, and it cannot be combined with regular ORDER BY keys.OFFSET n LIMIT m — both clauses are required together. n and m must be integer
literals or @parameter (no floats).SELECT ... FROM c ORDER BY c.createdAt DESC OFFSET @skip LIMIT @take.COUNT, SUM, AVG, MIN, MAX, CountIf, MakeList, MakeSet.Contains, StartsWith, EndsWith, StringEquals, ContainsAllCI,
ContainsAllCS, ContainsAnyCI, ContainsAnyCS, Concat, Length, Lower, Upper,
Substring, Left, Right, Trim, LTrim, RTrim, Replace, Replicate,
Reverse, IndexOf, LastIndexOf, SubstringBefore, SubstringAfter,
LastSubstringBefore, LastSubstringAfter, StringJoin, StringSplit, RegexMatch,
RegexExtract, RegexExtractAll, ToString.ARRAY_LENGTH, ARRAY_CONTAINS(arr, value [, partial]),
ARRAY_CONTAINS_ALL, ARRAY_CONTAINS_ANY, ARRAY_SLICE, ARRAY_CONCAT, ARRAY_SUM,
ARRAY_AVG, ARRAY_MIN, ARRAY_MAX, ARRAY_MEDIAN. Use ARRAY_LENGTH (not COUNT)
for array size.SetUnion, SetIntersect, SetDifference, SetEqual.Abs, Ceiling, Floor, Round, Trunc, Sign, Sqrt, Square,
Power, Exp, Log, Log10, Pi, Rand, Sin, Cos, Tan, Asin, Acos,
Atan, Atn2, Cot, Degrees, Radians, NumberBin.IntAdd, IntSub, IntMul, IntDiv,
IntMod, IntBitAnd, IntBitOr, IntBitXor, IntBitNot, IntBitLeftShift,
IntBitRightShift.GetCurrentDateTime, GetCurrentTimestamp, GetCurrentTicks,
GetCurrentDateTimeStatic, GetCurrentTimestampStatic, GetCurrentTicksStatic (the
*Static variants are evaluated once per query — useful inside indexed predicates),
DateTimeAdd, DateTimeDiff, DateTimePart, DateTimeBin, DateTimeFormat,
DateTimeFromParts, DateTimeToTimestamp, TimestampToDateTime, DateTimeToTicks,
TicksToDateTime, Year, Month, Day.IS_NULL, IS_DEFINED, IS_STRING, IS_NUMBER, IS_INTEGER,
IS_BOOL, IS_ARRAY, IS_OBJECT, IS_PRIMITIVE, IS_DATETIME, IS_FINITE_NUMBER.ToString, StringToNumber, StringToBoolean, StringToNull,
StringToArray, StringToObject, ObjectToArray.IIF(cond, a, b), Choose(index, v1, v2, ...),
DocumentId(c), Hash(value).ST_DISTANCE, ST_WITHIN, ST_INTERSECTS, ST_AREA, ST_ISVALID,
ST_ISVALIDDETAILED.FullTextContains, FullTextContainsAll, FullTextContainsAny
(boolean, used in WHERE); FullTextScore(c.field, "term") — usable ONLY inside
ORDER BY RANK. Requires a full-text index on the field.VectorDistance(c.embedding, @vec) — usable in SELECT (projected
score) or inside ORDER BY RANK. Requires a vector index. RRF(score1, score2, ...)
combines score functions inside ORDER BY RANK for hybrid search.StringEquals (not STRINGEQUALS),
DateTimeDiff, DateTimeAdd, GetCurrentDateTime, RegexMatch, CountIf,
MakeList, MakeSet, VectorDistance, FullTextScore, etc.DATEDIFF, DATEADD, DATEPART, GETDATE, COALESCE (use ??), ISNULL,
NULLIF, CAST/CONVERT, LEN (use LENGTH), CHARINDEX, PATINDEX, FORMAT.
There is no DateTimeSubtract (use DateTimeAdd with a negative value) and no
DateTimeFromTimestamp (use TimestampToDateTime).GetCurrentDateTime returns the current UTC time as an ISO 8601 string;
GetCurrentTimestamp returns milliseconds since the Unix epoch._ts (Cosmos system field) is the last-updated timestamp in seconds. Only
reference _ts if the schema confirms it or no schema is available. When comparing
_ts with a millisecond timestamp, divide by 1000.udf. prefix: udf.functionName(args). Only use UDFs
if the user explicitly references them.-- All documents
SELECT * FROM c
-- Filter
SELECT * FROM c WHERE c.status = "active"
-- Range with parentheses + IN
SELECT * FROM c WHERE (c.price BETWEEN 10 AND 100) AND c.category IN ("Electronics", "Books")
-- Array unwind
SELECT c.id, item.name FROM c JOIN item IN c.items WHERE item.quantity > 2
-- Group + aggregate
SELECT c.category, AVG(c.rating) AS avgRating FROM c GROUP BY c.category
-- Pagination
SELECT * FROM c ORDER BY c.createdAt DESC OFFSET @skip LIMIT @take
-- Scalar count
SELECT VALUE COUNT(1) FROM c WHERE c.inStock = true
-- Vector ranking
SELECT TOP 10 c.id FROM c ORDER BY RANK VectorDistance(c.embedding, @query)
-- Full-text ranking
SELECT TOP 10 c.id, c.title FROM c WHERE FullTextContains(c.title, "cosmos") ORDER BY RANK FullTextScore(c.title, "cosmos")
-- Hybrid search
SELECT TOP 10 c.id FROM c ORDER BY RANK RRF(FullTextScore(c.body, "cosmos"), VectorDistance(c.embedding, @vec))
SELECT * FROM c WHERE c._ts >= DateTimeToTimestamp(DateTimeAdd('day', -1024, GetCurrentDateTime()))/1000
SELECT (SELECT VALUE MIN(price) FROM price IN c.priceHistory) AS minPrice FROM c WHERE c.id = 'dfa2375b-95b7-43a5-9d59-5f5ffcdb1447'
SELECT c.name, ARRAY(SELECT VALUE f.username FROM f IN c.customerRatings) AS usernames FROM c
SELECT k.name AS keyword, COUNT(k) AS occurrence FROM c JOIN k IN c.keywords GROUP BY k.name
SELECT VALUE COUNT(1) FROM c WHERE EXISTS (SELECT VALUE t FROM t IN c.production_companies WHERE StringEquals(t.name, 'Eon Productions', true))
SELECT * FROM c WHERE c.countryOfOrigin NOT IN ('USA', 'Canada', 'Mexico')
tools
Drive the active Azure Cosmos DB for NoSQL Query Editor in VS Code from natural language. Use whenever the user asks in natural language to show / find / list / count / filter data "in this container", "in my container", or in the active Cosmos DB Query Editor (for example: "show me all trucks in this container", "find active users", "count documents by type"), or to generate, edit, or explain a query for the active editor. This skill orchestrates the VS Code Language Model tools that read editor context, sample the container schema, apply a query, and run it; it delegates all Cosmos DB NoSQL query-language rules, syntax, functions, and examples to the cosmosdb-nosql-query-generation skill.
development
Azure Cosmos DB performance optimization and best practices guidelines for NoSQL, partitioning, queries, and SDK usage. Use when writing, reviewing, or refactoring code that interacts with Azure Cosmos DB, designing data models, optimizing queries, or implementing high-performance database operations.
development
Generate multiple radically different interface designs for a module using parallel sub-agents. Use when user wants to design an API, explore interface options, compare module shapes, or mentions "design it twice".
development
Detects and fixes accessibility issues in React/Fluent UI webviews. Use when reviewing code for screen reader compatibility, fixing ARIA labels, ensuring keyboard navigation, adding live regions for status messages, or managing focus in dialogs.