Loops and Branching in Cloud Flows

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 9 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Mastering Logic in Power Automate: Loops and Branching

Introduction: The Logic of Automation

When we talk about automation, we are essentially talking about decision-making. A flow that only executes steps from top to bottom in a straight line is rarely useful for real-world business scenarios. In reality, data is messy, unpredictable, and often requires repetitive processing. This is where loops and branching come into play. They are the fundamental building blocks that transform a static sequence of actions into a dynamic, intelligent system capable of handling complex logic.

Branching allows your flow to ask questions—"Is this invoice over $500?" or "Is the user in the sales department?"—and take different paths based on the answers. Loops, on the other hand, allow your flow to handle collections of data, such as processing every row in an Excel spreadsheet or every item in a SharePoint list. Without these two capabilities, Power Automate would be limited to simple, one-off tasks. By mastering loops and branching, you move from being a user of automation to an architect of business logic.


Not read yet

Part 1: Branching – The Art of Decision Making

Branching is how you implement conditional logic. In Power Automate, the primary mechanism for this is the "Condition" action. A condition acts as a gateway; it evaluates an expression as either true or false and directs the flow down one of two distinct paths.

Understanding the Condition Action

A condition action is essentially an if-then-else statement. You define a value, an operator (such as "is equal to," "contains," or "is greater than"), and a comparison value. Depending on the result of this comparison, the flow branches.

Callout: Branching vs. Switch Actions While the Condition action is perfect for binary decisions (True/False), the "Switch" action is designed for scenarios where you have many possible outcomes based on a single variable. For example, if you are routing requests based on a department field (Sales, HR, IT, Legal), a Switch action is much cleaner and easier to maintain than nesting four or five different Condition actions inside one another.

Practical Example: Approval Routing

Imagine a scenario where you receive a request via a Microsoft Form. If the request is for hardware, it needs to go to the IT department. If it is for software access, it needs to go to the Manager.

  1. Trigger: "When a new response is submitted" in Microsoft Forms.
  2. Get Response Details: Use the ID from the trigger to pull the data.
  3. Condition: Check if the field "Request Type" is equal to "Hardware."
  4. If True: Send an approval email to the IT helpdesk.
  5. If False: Send an approval email to the employee's manager.

This simple branching logic ensures that requests are handled by the correct stakeholders automatically, reducing manual triage time.

Best Practices for Branching

  • Keep it Flat: Avoid nesting conditions more than two or three levels deep. Deeply nested logic becomes incredibly difficult to debug and modify later. If you find yourself nesting too deep, consider using a Switch action or breaking the flow into smaller, child flows.
  • Use Meaningful Names: Do not leave your conditions named "Condition," "Condition 2," and "Condition 3." Rename them to reflect the logic, such as "Check if Invoice Exceeds Approval Limit." This makes the flow readable for anyone who might inherit it.
  • Handle the "False" Path: Always ensure that your "If False" path has a defined outcome. A flow that simply stops or does nothing when a condition is false can lead to silent failures that are difficult to track.

Not read yet

Part 2: Loops – Iteration and Data Processing

Loops are necessary whenever you need to perform an action on multiple items. In Power Automate, there are two primary types of loops: "Apply to each" and "Do until."

The Apply to Each Loop

The "Apply to each" loop is the most common loop you will use. It iterates through an array of items and performs a set of actions for every single item in that array. This is critical when working with data sources like SharePoint lists, Excel tables, or email attachments.

Step-by-Step: Processing SharePoint Items

Suppose you have a SharePoint list called "Project Tasks" and you want to send a reminder email to everyone whose task is marked as "In Progress."

  1. Trigger: A scheduled cloud flow (e.g., every Monday morning).
  2. Get Items: Use the "Get items" action from the SharePoint connector to retrieve all rows from the "Project Tasks" list.
  3. Filter: Add a "Filter array" action to only keep items where "Status" equals "In Progress."
  4. Apply to Each: Add the "Apply to each" action. In the "Select an output from previous steps" field, select the output from your "Filter array" action.
  5. Action: Inside the loop, add a "Send an email (V2)" action. Use the email address from the current item and a customized message.

Note: When you add an action inside an "Apply to each" loop, Power Automate automatically references the "Current item." This means the flow knows exactly which row of data it is currently looking at, allowing you to pull specific values like the Task Name or the Assignee’s email address.

The Do Until Loop

The "Do until" loop is slightly different. Instead of running for every item in a list, it runs repeatedly until a specific condition is met. This is ideal for polling tasks or waiting for an external process to complete.

  • Scenario: You have triggered an external process (like an Azure Function or a legacy system API call) that takes a variable amount of time to finish. You want to check the status of that process every minute until it returns a "Success" status.
  • Logic:
    1. Initialize a variable called "Status" as "Pending."
    2. Add a "Do until" loop.
    3. Inside the loop, add a "Delay" action (e.g., 60 seconds).
    4. Call the API to check the status and update the "Status" variable.
    5. Set the "Do until" condition to: "Status" is equal to "Success."

Not read yet

Part 3: Advanced Concepts and Performance

As your flows grow in complexity, you must start thinking about efficiency. Loops, while powerful, can be resource-intensive if not managed correctly.

Concurrency Control

By default, an "Apply to each" loop processes items one after another (sequentially). If you have 500 items and each takes 2 seconds to process, your flow will take over 16 minutes to complete. However, Power Automate allows you to enable "Concurrency Control."

  • How it works: You can tell the loop to process multiple items at once (up to 50 threads).
  • The Benefit: If your action is not dependent on the previous item (e.g., sending an email), you can significantly speed up your flow.
  • The Warning: Be careful with concurrency if your action writes to a shared resource, such as updating a single Excel file row or hitting an API with strict rate limits. Processing 50 items simultaneously might trigger an API rate-limit error, causing the entire flow to fail.

Managing Large Data Sets

When retrieving data from a source like SharePoint or Dataverse, you might encounter "Pagination." If your list has 5,000 items but your "Get items" action only returns 100 at a time, you must enable pagination in the action settings to ensure the loop processes all records.

Warning: The "Apply to Each" Trap A common mistake is to place a "Get items" or "Get file" action inside an "Apply to each" loop. This creates an "N+1" query problem. If you loop through 100 items and call "Get items" for each one, you are making 101 API calls. This will inevitably lead to performance degradation and may hit your connector's daily API limits. Always try to get all the necessary data before entering the loop.


Not read yet

Part 4: Common Pitfalls and Troubleshooting

1. The "N+1" Query Problem

As mentioned above, querying data inside a loop is the primary reason for slow flows. If you need data from a related list, use a "Filter array" or a "Join" approach to collect all required data upfront. If you are working with Dataverse, use OData filters in the "List rows" action to grab exactly what you need in one go rather than fetching everything and filtering it manually.

2. Variable Scope

Variables initialized outside of a loop can be updated inside a loop. However, remember that if you are running your loop in parallel (concurrency), the order in which variables are updated is not guaranteed. If your logic depends on the sequence of operations, you must disable concurrency.

3. Handling Null Values

Loops often fail because they hit a null value when they expected a string or an object. Always include a condition inside your loop to check if the field you are processing is empty before attempting to use it in an action.

4. Timeouts

Cloud flows have a maximum duration (usually 30 days, but individual actions have shorter timeout limits). If a "Do until" loop runs for too long, the flow will time out. Always include a "Timeout" limit in your "Do until" settings to prevent a runaway loop from consuming your execution quota.


Not read yet

Part 5: Comparing Branching and Looping Strategies

Feature Branching (Condition) Looping (Apply to Each)
Purpose Path selection / Decision making Data iteration / Batch processing
Execution Executes one side or the other Executes for every item in a list
Complexity Increases with nesting Increases with nested logic/queries
Performance Constant (minimal impact) High (impacts execution time/API limits)
Best Used For Approvals, routing, logic gates Bulk data updates, report generation

Part 6: Best Practices for Robust Flows

Documentation

Even if you are the only one working on your flow, document your logic. Use the "Notes" feature on individual actions to explain why a specific condition exists. This is particularly important for complex loops that might have subtle triggers or concurrency settings.

Error Handling

Loops are prone to failure. If one item in a list causes an error, the entire flow will stop by default. You can change this behavior by configuring the "Configure run after" setting on the action following your loop. By selecting "has failed" or "is skipped," you can create an error-handling branch that logs the failure to a SharePoint list or sends an alert to the administrator without stopping the rest of the flow.

Testing with Small Samples

Never test a loop against your entire production database. Create a "test" folder or a "test" SharePoint list with 3-5 items. Run your flow against this small sample to verify your logic. Once you are confident, then point the flow toward your production data. This prevents accidental mass-emailing or mass-deletion of records.

Use Expressions for Complex Logic

Sometimes, a standard Condition action is not enough. You might need to compare dates, perform string manipulation, or check for multiple conditions simultaneously. In these cases, use the "Expression" tab in the dynamic content picker.

  • Example: To check if a date is within the next 7 days, you might use: greater(items('Apply_to_each')?['DueDate'], utcNow()) less(items('Apply_to_each')?['DueDate'], addDays(utcNow(), 7))

By using expressions, you can keep your flow clean and avoid creating massive, sprawling chains of conditions.


Not read yet

Part 7: Practical Scenario – The Automated Batch Processor

Let's synthesize everything we have learned into a single, practical example: Processing a daily report of invoices.

Scenario: You receive a daily CSV file in an email. You need to read the file, check if the invoice amount is over $1,000, and if so, flag it in a tracking system.

  1. Trigger: "When a new email arrives (V3)" with a trigger condition for the subject line "Daily Invoice Report."
  2. Get Attachment: Use the "Get attachment" action.
  3. Parse CSV: Use the "CSV to JSON" action (or a data operation action) to turn the file contents into an array of objects.
  4. Apply to Each: Loop through the array of invoice objects.
  5. Branching (Condition):
    • If True (Amount > 1000): Add a row to a SharePoint "High Value Invoices" list.
    • If False: Add a row to a SharePoint "Standard Invoices" list.
  6. Error Handling: Configure the "Apply to each" to continue on failure so that one corrupt invoice row doesn't stop the entire report from being processed.

This workflow demonstrates the power of combining triggers, data operations, loops, and branching into a cohesive, automated business process.


Not read yet

Part 8: Common Questions (FAQ)

Q: Can I nest loops inside other loops? A: Yes, you can. However, be extremely careful. An "Apply to each" inside an "Apply to each" creates an exponential increase in the number of actions performed. If your outer loop has 100 items and your inner loop has 100 items, you are performing 10,000 total operations. This is a common cause of flow timeouts.

Q: What happens if I rename a field in my data source while a flow is running? A: If you rename a column in SharePoint or a field in a JSON schema, your flow will likely break. Power Automate identifies these fields by their internal names. You will need to update your actions to point to the new field names. Always verify your flow after making structural changes to your data sources.

Q: How do I stop a loop early? A: You cannot "break" a loop in the traditional programming sense within standard cloud flows. If you need to exit a loop early, you usually need to restructure your logic or use a "Terminate" action, which will stop the entire flow.

Q: Are there limits to how many items I can loop through? A: Yes, the "Apply to each" action has a default limit of 100,000 items. While this is rarely hit, you should always design your flows to be efficient. If you are dealing with millions of records, Power Automate may not be the right tool; consider Azure Data Factory or Logic Apps, which are better suited for heavy-duty data processing.


Not read yet

Key Takeaways

  1. Logic is the Foundation: Branching and loops are the primary tools that provide "intelligence" to your flows. Without them, you are limited to static, linear sequences.
  2. Keep Conditions Simple: Use clear naming conventions and avoid deep nesting. When logic gets too complex, switch to a Switch action or break the flow into smaller components.
  3. Optimize Your Loops: Always avoid the N+1 query problem by collecting data before entering a loop. Use concurrency control cautiously to speed up operations that aren't dependent on one another.
  4. Plan for Errors: Assume your flow will fail at some point. Use "Configure run after" to manage errors gracefully, ensuring that one faulty record doesn't bring down your entire process.
  5. Test Before You Deploy: Always test your loops with a small, controlled data set. Never run a loop on a full production dataset without validating the logic first.
  6. Leverage Expressions: Don't be afraid of the Expression builder. It allows for much more sophisticated logic than simple UI-based conditions and keeps your flow design clean and maintainable.
  7. Know Your Limits: Understand the API limits of your connectors and the processing limits of your loops. If you are handling enterprise-scale data, look into more robust, scalable alternatives like Azure Logic Apps.

By mastering these components, you ensure your automations are not only functional but also resilient and scalable. Take the time to practice these patterns in a sandbox environment; the ability to think in loops and branches is the single most important skill for a successful automation developer.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.