Getting Started with Azure Cosmos DB, Part 3 – SQL Queries

by 

| August 30, 2017 | in

In my first post, we performed some really basic CRUD queries against Azure Cosmos DB. In my second post, we went a little deeper and refined our queries. In this post, we are going to be using SQL to query Cosmos.

Yep, SQL.

First, we will rewrite our count method. Previously, we did something that looked like this:

Now the above code is fine, but can we rewrite it using SQL. Yes we can!

The above code should produce the same results as the first code, but the actual query is written in SQL. See the “select value count(1) from notes” in our previous code.

Anyone with a little SQL background should recognize the code. We are selecting the Count (number of records) in the notes table. Only unique piece of this is we have to put the word value in front of count.

Next, let’s look at our All query. In our previous post, our all query looked something like this:

Now we can rewrite it the All query like this:

The code above is almost identical to the All code except that we use a SQL statement “select * from notes” as the query.

Now this post isn’t exhaustive in terms of what you can do with SQL queries using Azure Cosmos DB, but hopefully it has provided enough insight to get your brain running with ideas.

Warning: Add code samples enable cross partition queries. In a production system, you should be careful when using queries that cross partitions. Breaking our data up into partitions is a good idea from a scalability standpoint.

Complete Code



Related posts