Skip to content

Nesting Conditional & Logical Operators

This page shows how M’s logical operators work in custom columns and in filters, and how to combine them with if … then … else to build nested conditions.

M has three logical operators, written in lower case:

  • and, which is true only when both tests are true
  • or, which is true when either test is true
  • not, which reverses a test

The first examples use a single column of numbers:

An Excel table with one column, Data, holding 100, 200, 300, 400 and 500

Each operator can drive a custom column that returns TRUE or FALSE for every row. On the Add Column tab, choose Custom Column for each of these.

A column named AND, which tests for values between 90 and 350:

The Custom Column dialog with the new column name AND and the formula [Data] > 90 and [Data] <350

A column named OR, which tests for values below 140 or above 350:

The Custom Column dialog with the new column name OR and the formula [Data] < 140 or [Data] > 350

A column named NOT, which tests for values that are not below 250:

The Custom Column dialog with the new column name NOT and the formula not([Data] < 250)

The query now shows the result of each test against each value:

The Data column with AND true for 100 to 300, OR true for 100, 400 and 500, and NOT true for 300 to 500

The same logic is available when filtering. Open the filter menu on the Data column, choose a number filter, and switch the Filter Rows dialog to Advanced. Each clause added with Add Clause can be joined to the one before it with And or Or, which makes fairly complex filters possible without writing any M:

The Filter Rows dialog in Advanced mode, with two clauses on the Data column joined by Or, and an Add Clause button

Logical operators can also sit inside the test of an if expression, which takes this form:

if logical test then result if true else result if false

An if expression can itself be the result of another, which is what nesting means here.

The next example is a table of savings accounts:

An Excel table of five accounts with Tenure (Years), Balance, Main Account and Rate columns

The interest on each account is calculated with a custom column named Interest, whose formula nests one if inside the else of another and uses and in each test:

The Custom Column dialog for Interest, where a main account with tenure of 5 or more years earns Balance times Rate, a main account with tenure under 5 years also earns Balance times Rate, and any other account earns Balance times Rate times 0.75

In this formula, a main account earns the full rate and any other account earns three-quarters of it. Both tenure branches give the same result, so here they show how the nesting is written rather than changing the answer. Giving one branch a different calculation would make tenure count.

The Interest column appears at the end of the table:

The accounts table with a new Interest column showing 37.5, 75, 400, 500 and 675