Kaizen 207 - Answering Your Questions | Advanced Queries using COQL API

Kaizen 207 - Answering Your Questions | Advanced Queries using COQL API



Hi everyone, and welcome to another Kaizen week!

As part of Kaizen #200 milestone, many of you shared topics you would like us to cover, and we have been addressing them one by one over the past few weeks. Today, we are picking up one of those requests - a deep dive into advanced queries using Zoho CRM’s COQL APIs.

When you start building complex applications on top of Zoho CRM, you may feel that basic record fetch APIs like GET records are not enough. Business logic often demands far more, like combining data from multiple modules, applying conditional filters, grouping results, or even running aggregate calculations.

This is exactly where COQL (CRM Object Query Language) shines. If you have already used COQL for straightforward queries, this post will help you go further. 

COQL Recap - Why Use It?

COQL is your go-to when you need more than what the standard GET Records API can provide. It gives you:

  • SQL-like flexibility for querying CRM data.
  • Access to related records across multiple modules using lookups and joins.
  • Powerful filtering, aggregation, and sorting well beyond simple searches.

In short: use COQL when you want fine-grained control over results, complex reporting logic, or performance improvements in large data environments.

Understanding COQL Queries

The Query API (COQL) is best when you need flexible record retrieval without chaining multiple API calls or creating custom views.

Instead of building and maintaining complex filters in the UI, you can describe your data needs in one SQL-like query.

For example, with COQL you can:

  • Fetch all products within a certain price range that also have a 5-star rating, sorted by price.
  • Filter deals based on details from a related module, like the Vendor’s status.
  • Pull a precise slice of data on-demand without altering CRM views.

What kind of queries are supported?

COQL currently supports only the SELECT statement, which lets you pick fields, apply conditions, sort results, and control pagination.

A typical query looks like this:

SELECT {field_api_namesFROM {module_api_nameWHERE {field_api_name} {comparator} {valueGROUP BY {field_api_name} ORDER BY {field_api_nameASC/DESC LIMIT {limitOFFSET {offset}

  • FROM - specifies the module to query
  • WHERE - filters records based on conditions

  • GROUP BY - groups records by one or more fields for aggregation
  • ORDER BY - sorts results ascending or descending
  • LIMIT - restricts the number of records returned
  • OFFSET - skips a certain number of records before fetching results

Example:

{

 "select_query" : "select Last_Name, First_Name, Mobile, Final_Score from Leads where Lead_Status 'Not Contacted' order by Final_Score desc limit 5 offset 10"

}


The above query retrieves five Leads who have not been contacted, ordered by Final_Score, skipping the first 10(OFFSET). You can also use the shorthand LIMIT offset, limit:

{

 "select_query" : "select Last_Name, First_Name, Mobile, Final_Score from Leads where Lead_Status = 'Not Contacted' order by Final_Score desc limit 10, 5"

}


Supported Data Types & Operators

COQL supports multiple field types, each with dedicated operators:

Field Type

Supported Operators

Text, Picklist, Email, Phone, Website, Autonumber 

=, !=, like, not like, in, not in, is null, is not null

Lookup

=, !=, in, not in, is null, is not null

Date, DateTime, Number, Currency

=, !=, >=, >, <=, <, between, not between, in, not in, is null, is not null

Boolean

=

Formula

If the return type is:

  1. Decimal/Currency/Date/Datetime: =, !=, >=, >, <=, <, between, not between, in, not in, is null, is not null
  2. String: =, !=, like, not like, in, not in, is null, is not null
  3.  Boolean: =


Queries can be further refined with sorting (ORDER BY) and pagination using LIMIT and OFFSET.

Aggregate functions

COQL supports aggregate functions to summarize data:

  • SUM(field) – total of numeric values
  • MAX(field) – largest value
  • MIN(field) – smallest value
  • AVG(field) – average value
  • COUNT(*) – number of records matching criteria 


Please note that aggregate functions are supported only for numeric data types such as number, decimal, currency, etc.

Wildcards

The % character is supported with the LIKE operator for flexible text matching:

  • '%tech' → values ending with “tech”
  • 'C%' → values starting with “C”
  • '%tech%' → values containing “tech”


With these building blocks, you can already express a wide range of queries. Let’s now move into advanced scenarios where COQL really shines.

Beyond basics: COQL Patterns for real-world scenarios

Once you are comfortable with the basics of COQL, you can start combining them into more powerful query patterns. Some of these go beyond simple filtering and field selection, helping you minimize API calls, handle relationships, and emulate unsupported features.

1. Advanced Filtering & Conditions

Beyond equality, COQL supports operators like LIKEINBETWEEN, and date comparisons.

Example: Fetch Leads from the IT or Finance industry created in the year 2025.

{

 "select_query": "select Full_Name, Industry from Leads where Industry in ('IT', 'Finance') and Created_Time between '2025-01-01T00:00:00+05:30' and '2025-12-31T23:59:59+05:30'"

}


Use case: Run targeted campaigns or segment leads for analysis without multiple API calls.

2. Combining Multiple Conditions

You can query diverse conditions, combining exact, partial matches, and set memberships.

Example: Pre-qualified leads in target industries with company names containing “zylker”:

{

 "select_query": "select First_Name, Last_Name from Leads where (((Lead_Status = 'Pre-Qualified') and (Company like '%zylker%')) and Industry in ('Technology', 'Government/Military'))"

}



Use case: Sophisticated audience segmentation or analytics for campaigns.

3. Fetching related records and their fields using Joins (Dot notation)

COQL allows you to retrieve related records efficiently by navigating lookup relationships using dot notation. This makes it possible to pull in contextual information across modules without chaining multiple API calls.

Single-level join: Fetch contacts and their account names, excluding a specific account:

{

 "select_query": "select Last_Name, First_Name, Account_Name.Account_Name, Owner from Contacts where (Account_Name.Account_Name != 'Zylker') limit 2"

}


Sample use case: Retrieve all contacts along with their associated account names while excluding certain accounts (e.g., competitors or internal test accounts). This avoids multiple queries across modules and helps in cleaner campaign targeting.

Hierarchical / nested join: Fetch contacts whose accounts have a parent account named “Kings”:

{

 "select_query": "select Account_Name, Account_Name.Parent_Account.Account_Name from Contacts where Account_Name.Parent_Account.Account_Name = 'Kings' limit 5"

}


Sample use case: Easily retrieve multi-level relationships such as parent-child accounts for reporting, territory alignment, or hierarchical sales analysis.

Multi-Level Join with Extended Lookup : Fetch contacts, their accounts, the parent accounts of those accounts, and the owner of the parent account:

{

 "select_query": "select Last_Name, First_Name, Account_Name.Account_Name, Account_Name.Parent_Account, Account_Name.Parent_Account.Owner AS 'Parent Account Owner', Owner from Contacts where (Account_Name.Account_Name != 'Zylker') limit 2"

}


Sample use case: Useful in complex account management and escalation scenarios where responsibility spans multiple levels. For instance, sales managers may want to see not just the contact and their account, but also which parent account owner is responsible for the overall relationship. These types of queries are helpful in large enterprises with layered ownership structures.

4. Using Subqueries to detect missing relationships

COQL supports subqueries to filter based on related module data or detect missing relationships.

Example: Find contacts whose accounts have no closed deals:

{

 "select_query": "select Full_Name, Email from Contacts where Account_Name not in (select Account_Name from Deals where Stage = 'Closed Won')"

}


Use case: Identify potential follow-ups, audit compliance, or uncover opportunities.

These types of queries are handy for:

  • Sales follow-ups – identify contacts from accounts that haven’t yet converted.
  • Compliance checks – ensure certain accounts meet deal requirements.
  • Pipeline building – target untouched accounts for new opportunities.

By combining subqueries with conditions like NOT IN, COQL makes it easy to surface hidden opportunities that would otherwise require multiple API calls and custom logic.

NoteSubqueries in COQL can return a maximum of 100 records. If the inner query has more than 100 matches, any extra records are ignored. This means you may get incomplete results in larger datasets. In such cases, it is better to redesign the query using joins or multiple API calls, which can handle broader datasets without this limit.

Advanced COQL Querying: Real-World Patterns

Once you’ve mastered filters, joins, and subqueries, you can combine them for advanced business logic. 

1. Filtering Deals Based on Account Attributes

Generic Use Case:
You want to prioritize deals connected to high-value accounts that meet specific business criteria, such as strong credit ratings or key industries.

Retrieve all deals for accounts that:

  • Have a high credit rating (>750)
  • Belong to a specific industry, e.g., Communications

COQL Query:

{

 "select_query": "SELECT Deal_Name, Amount, Account_Name, Contact_Name.Email FROM Deals WHERE Account_Name in (SELECT id FROM Accounts WHERE Credit_Rating > 750 AND Industry = 'Communications') AND Stage != 'Closed Won'"

}


Dynamically filter deals by account attributes while fetching related contact details in a single query.

2. Emulating MIN/MAX for Date fields

When working with date fields in COQL, a common analytical need is to compare records against the latest date from a related subset. For example, identifying deals that closed before the most recent high-value deal.

Intuitively, one might try to use aggregate functions like MAX() on a date field in a subquery, such as:

{

 "select_query": "SELECT Deal_Name FROM Deals WHERE Closing_Date < (SELECT MAX(Closing_Date) FROM Deals WHERE Amount > 500000)"

}

Warning
However, COQL currently does not support aggregate functions like MAX() or MIN() on Date or DateTime fields. Attempting this will result in errors or unexpected behavior, as COQL aggregates are primarily designed for numeric fields.

Workaround: Using Subquery with ORDER BY and LIMIT

Instead of MAX(), the recommended COQL approach leverages sorting and limiting the result set to a single latest date within a subquery:

{

 "select_query": "select Deal_Name from Deals where Closing_Date < (select Closing_Date from Deals where Amount > 500000 order by Closing_Date desc limit 1)"

}


How this works:

The inner subquery fetches the single most recent Closing_Date where deals exceed $500,000, ordering by date descending and limiting to one record. The outer query then retrieves all deals closed before that date.

This pattern mimics the MAX() date comparison in a manner supported by COQL’s current capabilities. You can apply the same approach with ascending sort order to emulate MIN() as well.

3. Combining Multiple Subqueries for Complex Business Logic

Real-world CRM scenarios often require filtering records based on multiple interconnected conditions across different modules. Consider this sales intelligence use case: you want to identify Contacts who are:

  • Associated with Accounts that have annual revenue greater than $1000000000000
  • Connected to Deals that were created in the previous quarter    

{

 "select_query": "SELECT First_Name, Last_Name, Email, Account_Name.Account_Name FROM Contacts WHERE Account_Name in (SELECT Account_Name FROM Deals WHERE Created_Time >= '2025-06-01' AND Account_Name in (SELECT id FROM Accounts WHERE Annual_Revenue > 1000000000000)) "

}


Query Breakdown:

  • Innermost subquery: (SELECT id FROM Accounts WHERE Annual_Revenue > 1000000000000) identifies high-revenue accounts
  • Middle subquery: (SELECT Account_Name FROM Deals WHERE Created_Time >= '2022-07-02T15:18:31+05:30' AND Account_Name in (...)) filters for accounts with deals created after the specified date that are also high-revenue accounts
  • Main query: Retrieves contact details for all contacts associated with these filtered accounts while fetching the related account names via JOIN


This pattern finds contacts from high-value accounts that have had recent deal activity, combining temporal filtering with revenue-based account qualification in a single efficient query.

Dynamic Account and Deal Performance Analysis

Imagine you need to find all Leads from industries where accounts have historically closed high-value deals (over $100K) and those leads have "Hot" ratings.

This requires filtering leads based on:

  • Industry performance from accounts with successful deals
  • Lead rating criteria
  • Retrieving lead details with industry information


{

 "select_query": "SELECT First_Name, Last_Name, Lead_Source, Company, Industry FROM Leads WHERE Industry in (SELECT Industry FROM Accounts WHERE id in (SELECT Account_Name FROM Deals WHERE Amount > 100000 AND Stage = 'Closed Won') GROUP BY Industry) AND Rating = 'Hot'"

}


What makes this powerful:

  • Inner subquery (SELECT Account_Name FROM Deals WHERE Amount > 100000 AND Stage = 'Closed Won') identifies accounts with successful high-value deals
  • Outer subquery (SELECT Industry FROM Accounts WHERE id in (...) GROUP BY Industry) gets the industries of those successful accounts
  • Groups by Industry to get unique industry values and avoid duplicates
  • Main query finds leads in those proven successful industries with "Hot" ratings.

    Note: Both subqueries in this query are limited to 100 records each. If either the Deals or Accounts module returns more than 100 matches, the additional records are silently ignored. This can lead to incomplete results when working with larger datasets. For scenarios where the inner queries are expected to return more than 100 records, redesign the query using joins or break it down into multiple API calls for complete coverage.


Conclusion

By going beyond simple record fetches, COQL gives you the power to do true analytics and querying. By mastering patterns that range from straightforward joins to complex multi-module subqueries, you can consolidate multiple API calls into a single query, reduce complexity, and streamline performance. At the same time, dynamic filtering across modules facilitates richer business logic, while relationship-aware queries let you build automations that can handle real-world exceptions with precision.

As you implement these patterns, remember that the most powerful COQL queries often combine multiple techniques: JOINs for data enrichment, subqueries for dynamic filtering, and careful aggregation for performance optimization. However, it is equally important to understand COQL's limitations too. Being aware of these limitations will help you design effective workarounds and choose the right approach for your specific use cases. For a comprehensive list of limitations, please refer to our COQL Limitations documentation.

Start with simpler patterns and gradually build complexity as your use cases demand. The investment in mastering COQL will pay you with cleaner code base, better performance, lesser credit consumption, and more sophisticated CRM functionality.

We hope that you found this post on COQL useful. If you have any queries or need further assistance, please feel free to comment below or email us at support@zohocrm.com. We are here to help!



    • Sticky Posts

    • Kaizen #197: Frequently Asked Questions on GraphQL APIs

      🎊 Nearing 200th Kaizen Post – We want to hear from you! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
    • Kaizen #198: Using Client Script for Custom Validation in Blueprint

      Nearing 200th Kaizen Post – 1 More to the Big Two-Oh-Oh! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
    • Celebrating 200 posts of Kaizen! Share your ideas for the milestone post

      Hello Developers, We launched the Kaizen series in 2019 to share helpful content to support your Zoho CRM development journey. Staying true to its spirit—Kaizen Series: Continuous Improvement for Developer Experience—we've shared everything from FAQs
    • Kaizen #193: Creating different fields in Zoho CRM through API

      🎊 Nearing 200th Kaizen Post – We want to hear from you! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
    • Client Script | Update - Introducing Commands in Client Script!

      Have you ever wished you could trigger Client Script from contexts other than just the supported pages and events? Have you ever wanted to leverage the advantage of Client Script at your finger tip? Discover the power of Client Script - Commands! Commands

    Nederlandse Hulpbronnen


      • Recent Topics

      • get file api is returning Junk data

        I am working on extension development where at one point I need to retrieve attachments on records I found out I can use only invokeconnection and not invokeurl in extension development The invoke connection returns the image in raw binary format. When
      • Need help with message box

        End user updates many records at once. Each have unique serial number. They want a confirmation box that says starting number, ending number and qty. Is there any way to do this? I been searching and asking support but seems like no great solution.
      • [Webinar] The Transformative Power of Gen BI

        Traditional decision-making tools are no longer enough. The integration of generative AI into business intelligence (BI) is proving to be a true game changer—enabling businesses to make faster, smarter, and better informed decisions. Early adopters of
      • Backorder process review - Automating Removal of Sales Order from "On Hold" When PO is Received

        Hello Zoho Inventory Team, Currently, sales orders in On Hold status are released only when the bill for the purchase order is created. In our workflow, it would be much more efficient if the sales order could automatically move out of On Hold as soon
      • How to access the saved Query using API?

        I have created a query in setting. Is it possible to access it from a API? What's the endpoint? I tried /v8/queries/important_deals but didnt' work.
      • création d'une base de données

        base de donnee d'un lycée
      • User Session variables to recall after form submit & redirect to menu

        Hey, Forgive me if this is a simple answer I have overlooked. I have built a big onboarding process for my SAAS platform which is built and managed by an external Dev team. I am hoping to embed my new creator app on the SAAS platform. I have a menu page
      • Zoho Writer Merge Template with data from Zoho Analytics Views

        Hello, Is there any way to pull information from Zoho Analytics and put it into a Merge Template? I am trying to create a bulk export of one report that filters on a field to create a single document for each of the filter fields.
      • Having to enter bill before stock shows as available.

        Hi, Am I right in thinking you must create a bill from the purchase order receipt before the goods are available for shipping?
      • Agent Availability Report

        From data to decisions: A deep dive into ticketing system reports Businesses need to track when their support agents check in and check out from work. This report, titled Agent Availability, is one of the static reports that helps managers track the number
      • Writing by Hand in "Write" Notes

        Hi there! I just downloaded this app a few moments ago, and I was wondering if there was a way to write things by hand in "Write" mode instead of just typing in the keyboard. It would make things a bit more efficient for me in this moment. Thanks!
      • AI-driven construction analytics using Zoho Projects Plus

        Construction projects thrive on timelines; if a project is completed on or before the expected time, it makes headlines, but if it gets delayed, the company’s credibility will be at risk. Such projects require precise planning and constant monitoring,
      • Canadian payroll

        Hello ZOHO, is any updates on when payroll for Canada will be available?
      • Unified customer view: Bringing product intelligence into your CRM data

        For businesses today, applications and digital interfaces are the main touch points in the customer journey. While Zoho CRM data already tells who your customers are and what they buy, Zoho Apptics tells you how they interact and engage with your product.
      • Zoho Creator SaaS app with multiple client AND multiple users

        I am close to finalizing a Zoho Creator app that will be used by different companies to manage sale info, and each company can have multiple users using the app. Things were going perfectly until I tried a search on a report. I use a database field in each table to separate the data for each company, which works great. BUT when I do a search, I get to see ALL the data. This means that Company A could easily see the data from Companies B and C via the built-in search. Is there a way to set up the
      • Project Change Orders and Additions

        We are in the process of migrating from QuickBooks Online to Zoho Books. We have Zoho One and like the ability to sync all of our data across everything. And I like that projects work in a way that's less dumb than QuickBooks. I'm trying to figure out
      • Track online, in-office, and client location meetings separately with the new meeting venue option

        Hello everyone! We’re excited to announce meeting enhancements in Zoho CRM that bring more clarity and structure to how meetings are categorized. You can now specify the meeting venue to clearly indicate whether a meeting is being held online, at the
      • Create custom rollup summary fields in Zoho CRM

        Hello everyone, In Zoho CRM, rollup summary fields have been essential tools for summarizing data across related records and enabling users to gain quick insights without having to jump across modules. Previously, only predefined summary functions were
      • Possible to send Zoom AI Companion transcripts and summaries to contacts in CRM?

        Title says it all. Is it possible to send Zoom AI Companion transcripts and summaries to contacts in Zoho CRM?
      • Introducing segments for targeted user engagement

        Hello everyone, We’re excited to announce Segments in Zoho Apptics, a new way to group users based on their behavior, preferences, and app activity. With Segments, you can deliver more meaningful, timely, and relevant experiences to your users. When combined
      • How do I edit the Calendar Invite notifications for Interviews in Recruit?

        I'm setting up the Zoho Recruit Interview Calendar system but there's some notifications I don't have any control over. I've turned off all Workflows and Automations related to the Calendar Scheduling and it seems that it's the notification that is sent
      • Posibility to add Emoticons on the Email Subject of Templates

        Hi I´ve tried to add Emoticons on the Subject line of Email templates, the emoticon image does show up before saving the template or if I add the Emoticon while sending an Individual email and placing it manually on the subject line. Emoticons also show
      • Clarity on extended contract status

        Clarity on “extended” status- How does Zoho “extend” a contract?  E.g. if client extends by 1 month, can the “end date” be adjusted accordingly in Zoho and tagged as “Extended” with a clear audit trail that also captures the client’s email? Note- Email
      • Customizing contract status

        Can we customize/add/remove status on Zoho contracts ourselves or does Zoho needs to do this? Context- There is a long list of status on Zoho but not all of them are relevant for us . There are few status which are missing and needs to be added. E.g-
      • Set Custom Business Calendars and Holidays for Global Teams

        Managing a project across diverse teams means accounting for more than just tasks and deadlines; it means acknowledging how and when each team actually works. Users might follow different working days or observe region-specific holidays that cannot be
      • [Integration edition] Deluge learning series - Integrations between Zoho apps and Third-party services with Deluge | 28 August 2025

        We’re excited to welcome you to the Deluge learning series: Integration edition! The Integration edition will run for three months: Session 1 – Integrating Zoho Apps with Deluge using inbuilt integration tasks Session 2 – Integrating Zoho Apps with Deluge
      • Critical Vulnerability in all major password manager plugins - is Zoho Vault affected?

        Hi Zoho, a security researcher found a critical clickjacking vulnerability in all major browser password managers: DOM-based Extension Clickjacking: Your Password Manager Data at Risk | Marek Tóth Is Zoho Vault affected as well? Apparently the Vault extension
      • Introducing SecureForms in Zoho Vault

        Hey everyone, Let’s face it—asking someone to send over a password or other sensitive data is rarely straightforward. You wait. You nudge. You follow up once, twice—maybe more. And when the information finally arrives, it shows up in the worst possible
      • Tables from ZohoSheets remove images when updated from source

        I have a few tables from a ZohoSheet in a ZohoWriter document that will remove the images in the cells when I refresh from the source. The source still has the images in the table when I go to refresh. After updating from the source, as you can see the
      • Change eMail Template for Event-Invitations

        Hello ZOHO-CRM Team How I can change the eMail Template for Event-Invitations? I work with the German Version of the Free Version. I know how I can modify eMail alerts or Signature Templates, but where I can other eMails modify you send out? Thank you for your answer. Regards, Juerg
      • Inventory Adjustments

        Hi, How to transfer the material from one head to another ? Like materials purchased for manufacturing the laptop need to transfer from consumption inventory (Quantity of raw materials reduced) to destination inventory ( Quantity of Laptop increased)
      • Need Your Insights

        Hi Zoho, I'm confused why the flow only sends to one output. setVariable15 is from a list. It doesn't consider the 2nd entry. Any thoughts?
      • Map Dependency Fields - How can can I limit picklist values from a multi-select Parent field?

        I know the "Map Dependency Fields" feature doesn't allow a multi-select parent field. However, I need the functionality. Can I do it through a deluge function, and would it still support color coding picklists? We need the color coding for quick scanning
      • DYK 1 - Color Palette for Enhanced Visual Identification of Status

        Introducing the Did You Know series of posts. The goal of this series is to familiarize users with certain features or enhancements in Zoho Projects that may not be evident at first glance. The first post in this series deals with color palettes for indicating
      • Invalid field in the COQL query

        Dear Zoho Support! I believe that you already helped me with a similar problem a few years ago. One of my clients has a custom field named "LOB" in the "Deals" Module (see the field's metadata below). The COQL query using this field: : "select id, Deal_Name,
      • Automating Employee Birthday Notifications in Zoho Cliq

        Have you ever missed a birthday and felt like the office Grinch? Fear not, the Cliq Developer Platform has got your back! With Zoho Cliq's Schedulers, you can be the office party-cipant who never forgets a single cake, balloon, or awkward rendition of
      • Transferring domain registration to new registrar and switching email hosting at the same time?

        I need to transfer an existing domain uv cure adhesive that's currently with SiteGround to Porkbun. I also need to move the existing custom email addresses from SiteGround to Zoho Mail. I'm not sure if I should transfer the domain first and then tackle
      • Split deposits

        Can Zoho do split deposits. One deposit, two checks for two separate invoices from different customers. This is one of the most common tasks I can imaging. When I mark the two invoices paid, there are two deposits in bank register. When I try to match,
      • Feedback: Streamlining Note Management in Zoho Notebook

        Dear Team/Support, I would like to share some feedback regarding the note management system that could help improve usability and accessibility for users like myself. Notebook 1 (screenshot attached): Currently, the system does not allow selecting and
      • Deactivate Desk Contact without Deleting Contat

        We have a client who has multiple tenants for regulatory purposes, and as such, has a few users that have email addresses in both tenants. They've then emailed into the ticketing system, so we have multiple contacts (no big deal, we want to keep their
      • Next Page