MongoDB

SELECT Statements

A SELECT statement can consist of the following basic clauses.

  • SELECT

  • INTO

  • FROM

  • JOIN

  • WHERE

  • GROUP BY

  • HAVING

  • UNION

  • ORDER BY

  • LIMIT

SELECT Syntax

The following syntax diagram outlines the syntax supported by the SQL engine of the provider:

SELECT {

[ TOP <numeric_literal> | DISTINCT ]

{

*

| {

<expression> [ [ AS ] <column_reference> ]

| { <table_name> | <correlation_name> } .*

} [ , ... ]

}

[ INTO csv:// [ filename= ] <file_path> [ ;delimiter=tab ] ]

{

FROM <table_reference> [ [ AS ] <identifier> ]

} [ , ... ]

[ [

INNER | { { LEFT | RIGHT | FULL } [ OUTER ] }

] JOIN <table_reference> [ ON <search_condition> ] [ [ AS ] <identifier> ]

] [ ... ]

[ WHERE <search_condition> ]

[ GROUP BY <column_reference> [ , ... ]

[ HAVING <search_condition> ]

[ UNION [ ALL ] <select_statement> ]

[

ORDER BY

<column_reference> [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ]

]

[

LIMIT <expression>

[

{ OFFSET | , }

<expression>

]

]

} | SCOPE_IDENTITY()

<expression> ::=

| <column_reference>

| @ <parameter>

| ?

| COUNT( * | { [ DISTINCT ] <expression> } )

| { AVG | MAX | MIN | SUM | COUNT } ( <expression> )

| NULLIF ( <expression> , <expression> )

| COALESCE ( <expression> , ... )

| CASE <expression>

WHEN { <expression> | <search_condition> } THEN { <expression> | NULL } [ ... ]

[ ELSE { <expression> | NULL } ]

END

| <literal>

| <sql_function>

<search_condition> ::=

{

<expression> { = | > | < | >= | <= | <> | != | LIKE | NOT LIKE | IN | NOT IN | IS NULL | IS NOT NULL | AND | OR | CONTAINS | BETWEEN } [ <expression> ]

} [ { AND | OR } ... ]

Examples

  1. Return all columns:

    SELECT * FROM [CData].[Sample].Customers

  2. Rename a column:

    SELECT [CompanyName] AS MY_CompanyName FROM [CData].[Sample].Customers

  3. Cast a column's data as a different data type:

    SELECT CAST(Balance AS VARCHAR) AS Str_Balance FROM [CData].[Sample].Customers

  4. Search data:

    SELECT * FROM [CData].[Sample].Customers WHERE Country = 'US'

  5. Return the number of items matching the query criteria:

    SELECT COUNT(*) AS MyCount FROM [CData].[Sample].Customers

  6. Return the number of unique items matching the query criteria:

    SELECT COUNT(DISTINCT CompanyName) FROM [CData].[Sample].Customers

  7. Return the unique items matching the query criteria:

    SELECT DISTINCT CompanyName FROM [CData].[Sample].Customers

  8. Summarize data:

    SELECT CompanyName, MAX(Balance) FROM [CData].[Sample].Customers GROUP BY CompanyName

    See Aggregate Functions below for details.

  9. Retrieve data from multiple tables.

    SELECT restaurants.name, zips.city FROM restaurants INNER JOIN zips ON restaurants.address_zipcode = zips.C_id

    See JOIN Queries below for details.

  10. Sort a result set in ascending order:

    SELECT City, CompanyName FROM [CData].[Sample].Customers ORDER BY CompanyName ASC

  11. Restrict a result set to the specified number of rows:

    SELECT City, CompanyName FROM [CData].[Sample].Customers LIMIT 10

  12. Parameterize a query to pass in inputs at execution time. This enables you to create prepared statements and mitigate SQL injection attacks.

    SELECT * FROM [CData].[Sample].Customers WHERE Country = @param

Aggregate Functions

COUNT

Returns the number of rows matching the query criteria.

SELECT COUNT(*) FROM [CData].[Sample].Customers WHERE Country = 'US'

COUNT(DISTINCT)

Returns the number of distinct, non-null field values matching the query criteria.

SELECT COUNT(DISTINCT City) AS DistinctValues FROM [CData].[Sample].Customers WHERE Country = 'US'

AVG

Returns the average of the column values.

SELECT CompanyName, AVG(Balance) FROM [CData].[Sample].Customers WHERE Country = 'US' GROUP BY CompanyName

MIN

Returns the minimum column value.

SELECT MIN(Balance), CompanyName FROM [CData].[Sample].Customers WHERE Country = 'US' GROUP BY CompanyName

MAX

Returns the maximum column value.

SELECT CompanyName, MAX(Balance) FROM [CData].[Sample].Customers WHERE Country = 'US' GROUP BY CompanyName

SUM

Returns the total sum of the column values.

SELECT SUM(Balance) FROM [CData].[Sample].Customers WHERE Country = 'US'

JOIN Queries

The Provider for MongoDB supports joins of a nested array with its parent document and joins of multiple collections.

Joining Nested Structures

The provider expects the left part of the join is the array document you want to flatten vertically. Disable SupportEnhancedSQL to join nested MongoDB documents. This type of query is supported through the MongoDB API.

For example, consider the following query from MongoDB's restaurants collection:

SELECT [restaurants].[restaurant_id], [restaurants].name, [restaurants.grades].*FROM [restaurants.grades]JOIN [restaurants]WHERE [restaurants].name = 'Morris Park Bake Shop'

See Vertical Flattening for more details.

Joining Multiple Collections

You can join multiple collections just like you would join tables in a relational database. Set SupportEnhancedSQL to True to execute these types of joins. The following examples use the restaurants and zips collections available in the MongoDB documentation.

The query below returns the restaurant records that exist, if any, for each ZIP code:

SELECT z.city, r.name, r.borough, r.cuisine, r.[address.zipcode]FROM zips zLEFT JOIN restaurants rON r.[address.zipcode] = z._id

The query below returns records from both tables that match the join condition:

SELECT z.city, r.name, r.borough, r.cuisine, r.[address.zipcode]FROM restaurants rINNER JOIN zips zON r.[address.zipcode] = z._id

Date Literal Functions

The following date literal functions can be used to filter date fields using relative intervals. Note that while the <, >, and = operators are supported for these functions, <= and >= are not.

L_TODAY()

The current day.

SELECT * FROM MyTable WHERE MyDateField = L_TODAY()

L_YESTERDAY()

The previous day.

SELECT * FROM MyTable WHERE MyDateField = L_YESTERDAY()

L_TOMORROW()

The following day.

SELECT * FROM MyTable WHERE MyDateField = L_TOMORROW()

L_LAST_WEEK()

Every day in the preceding week.

SELECT * FROM MyTable WHERE MyDateField = L_LAST_WEEK()

L_THIS_WEEK()

Every day in the current week.

SELECT * FROM MyTable WHERE MyDateField = L_THIS_WEEK()

L_NEXT_WEEK()

Every day in the following week.

SELECT * FROM MyTable WHERE MyDateField = L_NEXT_WEEK()

Also available:

  • L_LAST/L_THIS/L_NEXT MONTH

  • L_LAST/L_THIS/L_NEXT QUARTER

  • L_LAST/L_THIS/L_NEXT YEAR

L_LAST_N_DAYS(n)

The previous n days, excluding the current day.

SELECT * FROM MyTable WHERE MyDateField = L_LAST_N_DAYS(3)

L_NEXT_N_DAYS(n)

The following n days, including the current day.

SELECT * FROM MyTable WHERE MyDateField = L_NEXT_N_DAYS(3)

Also available:

  • L_LAST/L_NEXT_90_DAYS

L_LAST_N_WEEKS(n)

Every day in every week, starting n weeks before current week, and ending in the previous week.

SELECT * FROM MyTable WHERE MyDateField = L_LAST_N_WEEKS(3)

L_NEXT_N_WEEKS(n)

Every day in every week, starting the following week, and ending n weeks in the future.

SELECT * FROM MyTable WHERE MyDateField = L_NEXT_N_WEEKS(3)

Also available:

  • L_LAST/L_NEXT_N_MONTHS(n)

  • L_LAST/L_NEXT_N_QUARTERS(n)

  • L_LAST/L_NEXT_N_YEARS(n)

Last updated