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
    • Recent Topics

    • Cliq iOS can't see shared screen

      Hello, I had this morning a video call with a colleague. She is using Cliq Desktop MacOS and wanted to share her screen with me. I'm on iPad. I noticed, while she shared her screen, I could only see her video, but not the shared screen... Does Cliq iOS is able to display shared screen, or is it somewhere else to be found ? Regards
    • Retainer Invoice.

      Why ZOHO not have facilities to deduct partially advance payment from an invoice.
    • Apply Vendor Credits Automatically

      We are bulk importing Vendor credits in Zoho Books!!! Is there a way to apply vendor credits automatically to the first UNPAID bill of the Vendor?
    • Cant Save Gauge on Creator Page

      How to Save Gauge on Creator Page see movie https://vimeo.com/1116410860?share=copy#t=0
    • Apply Advance option not shown in report

      We are facing an issue in Zoho Expenses. While approving an Expense Report, the "Apply Advance" option is not appearing under the three dots (More Options). Details: Module: Expense Reports Issue: "Apply Advance" option not visible Status of Report: Awaiting
    • Introducing Assemblies and Kits in Zoho Inventory

      Hello customers, We’re excited to share a major revamp to Zoho Inventory that brings both clarity and flexibility to your inventory management experience! Presenting Assemblies and Kits We’re thrilled to introduce Assemblies and Kits, which replaces the
    • Auto Capitalize First Letter of Words

      Hi I am completely new to ZOHO and am trying to build a database. How can i make it when a address is entered into a form field like this: main st it automatically changes is to show: Main St Thank You
    • Follow-up emails via Workflow Automation not staying in the same thread

      Dear Zoho Support Team, I am currently using Workflow Automation in Zoho Campaigns to send follow-up emails. In my test case, I noticed the following behavior: All emails in the automation have the same subject line. If the follow-up email is sent within
    • Client Script refuses to set an initial value in Subform field

      I tried a very simple, 1 line client script to set a default value in a custom subform field when the "Add Row" button is clicked and the user is entering data. It does not work - can someone tell me why? ZDK documentation suggests this should be doable.
    • Formatting of Balance Sheet and Profit & Loss Reports

      The default format of the Balance Sheet and P&L Reports are based on the Account Types and then the individual accounts within the Chart of Accounts. These are then ordered alphabetically under these sub-headings and one is unable to re-order these or
    • Emails Are Not Being Delivered to My Inbox

      Hello Zoho Support Team, I am experiencing an issue with my Zoho Mail account. The most important problem is that emails are not being delivered to my inbox. Details: My Zoho Mail address: info@coreforcelife.com What happens: I am not receiving any incoming
    • Help Center IFrame Issue

      I have had a working Help Center on my website using an iframe for a while. But now for some reason the sign in page gets a refused to connect error. Can someone please help. If I go to the url manually it works correclty
    • Staff rules

      Hi! Do you people know what are the default staff rules when a new booking is created? We have two staff members in my team (me as the admin, and my employee). As we share the same services, I'm wondering how Zoho will pick the staff for new apointments.
    • Comment Templates

      Is it possible to add a template option for comments? We have some agents in the process who's responses require a pre-formatted layout. It would be incredibly handy to have a template for them where they can insert the template and then add their responses
    • [ZohoDesk] Improve Status View with a new editeble kanban view

      A kanban view with more information about the ticket and the contact who created the ticket would be valueble. I would like to edit the fields with the ones i like to see at one glance. Like in CRM where you can edit the canvas view, i would like to edit
    • Adding Markdown text using Zoho Desk API into the Knowledge Base

      Hi Zoho Community members, We currently maintain the documentation of out company in its website. This documentation is written in markdown text format and we would like to add it in Zoho Knowledge Base. Do you know if there is REST API functionality
    • An Exclusive Session for Zoho Desk Users: AI in Zoho Desk

      A Zoho Community Learning Initiative Hello everyone! This is an announcement for Zoho Desk users and anyone exploring Zoho Desk. With every nook and corner buzzing, "AI's here, AI's there," it's the right time for us to take a closer look at how the AI
    • Shared values: From classroom lessons to teaching moments in customer service

      While the world observes Teachers’ Day on October 5, in India, we celebrate a month earlier, on September 5, to mark the birth anniversary of Dr. Sarvepalli Radhakrishnan, a great teacher, renowned scholar, educationist, and advocate for empowerment.
    • Export to excel stored amounts as text instead of numbers or accounting

      Good Afternoon, We have a quarterly billing report that we generate from our Requests. It exports to excel. However if we need to add a formula (something as simple as a sum of the column), it doesn't read the dollar amounts because the export stores
    • Create a list of customers who participated in specific Zoho Backstage events and send them an email via Zoho CRM

      How to create a list of customers who participated in specific Zoho Backstage events and send them an email via Zoho CRM? I was able to do a view in CRM based on customer that registered to an event, but I don't seems to be able to include the filter
    • Zoho Desk blank page

      1. Click Access zoho desk on https://www.zoho.com/desk/ 2. It redirects to https://desk.zoho.com/agent?action=CreatePortal and the page is blank. Edge browser Version 131.0.2903.112 (Official build) (arm64) on MacOS
    • I hate the new user UI with the bar on the left

      How can I reverse this?
    • Constant color of a legend value

      It would be nice if we can set a constant color/pattern to a value when creating a chart. We would often use the same value in different graph options and I always have to copy the color that we've set to a certain value from a previous graph to make
    • Question regarding import of previous deals...

      Good afternoon, I'm working on importing some older deal records from an external sheet into the CRM; however, when I manually click "Add New Deal" and enter the pertinent information, the deal isn't appearing when I look at the "Deals" bar on the account's
    • Client Script also planned for Zoho Desk?

      Hello there, I modified something in Zoho CRM the other day and was amazed at the possibilities offered by the "Client Script" feature in conjunction with the ZDK. You can lock any fields on the screen, edit them, you can react to various events (field
    • One person/cell phone to manage multiple accounts

      Hi. I have a personal Free account to keep my own domain/emails. Now I need to create a Business account to my company's own domain, but I have only one mobile phone number I use to everything. How do I do to manage this? Can I manage a Free domain and
    • Tracking KPIs, Goals etc in People

      How are Zoho People users tracking employee targets in People? For example, my marketing assistant has a target of "Collect 10 new customer testimonials every month". I want to record attainment for this target on a monthly basis, then add it to their
    • Zoho Desk: Ticket Owner Agents vs Teams

      Hi Zoho, We would like to explore the possibility of hiding the ‘Agents’ section within the Ticket Owner dropdown, so that we can fully utilise the ‘Teams’ dropdown when assigning tickets. This request comes from the fact that only certain agents and
    • Can not Use Attachment Button on Android Widget

      this always pops up when I touch the attach button on android widget. going to settings, there is no storage permission to be enabled. if I open the app, and access the attach feature there, I can access my storage and upload normally.
    • Announcing new features in Trident for Mac (1.24.0)

      Hello everyone! Trident for macOS (v.1.24.0) is here with interesting features and thoughtful enhancements to redefine the way you plan and manage your calendar events. Here's a quick look at what's new. Create calendar events from emails. In addition
    • Need Easy Way to Update Item Prices in Bulk

      Hello Everyone, In Zoho Books, updating selling prices is taking too much time. Right now we have to either edit items one by one or do Excel export/import. It will be very useful if Zoho gives a simple option to: Select multiple items and update prices
    • Vendor Master Enhancements for Faster Purchase Entry

      I’d like to suggest a few features that will improve accuracy and speed during purchase voucher entry: Automated Item Tax Preference in Vendor Master Add an option to define item tax preference in the vendor master. Once set, this preference should automatically
    • Mass Mail Statistics - Number of unsent emails

      How do I find out which emails were not sent?
    • Est-il possible d'annuler l'envoi d'un mail automatique ?

      Bonjour, Lorsque je refuse un candidat, il reçois un mail dans les 24h pour l'informer que sa candidature n'est pas retenue. J'ai rejeté un candidat par erreur. Savez-vous s'il possible d'annuler l'envoi de ce mail ? Merci d'avance pour votre aide.
    • Can't change form's original name in URL

      Hi all, I have been duplicating + editing forms for jobs regarding the same department to maintain formatting + styling. The issue I've not run into is because I've duplicated it from an existing form, the URL doesn't seem to want to update with the new
    • embed a form in an email

      Hello, how to embed a form in an email that populates Zoho CRM cases? I would like to send emails to a selected audience offering something. In the same email the recipients - if interested - instead of replying to can fill in a Zoho CRM form that creates
    • Zoho Bookings - Reserve with Google

      Does Zoho Bookings plan to to integrate with Reserve with Google?
    • How to add Zoho demo site page designs to my Zoho Sites website

      Hi, I would like to add the design from the following demo URLs into my current Zoho website. I have already created two new pages on my site, named “Menu2” and “Menu3.” For the “Menu2” page, I want to use the design from this demo: https://naturestjuice-demo.zohosites.com/menu
    • Digest Août - Un résumé de ce qui s'est passé le mois dernier sur Community

      Bonjour chère communauté ! Voici le résumé tant attendu de tout ce qui a marqué Zoho le mois dernier : contenus utiles, échanges inspirants et moments forts. 🎉 Découvrez Zoho Backstage 3.0 : une version repensée pour offrir encore plus de flexibilité,
    • Global Sets for Multi-Select pick lists

      When is this feature coming to Zoho CRM? It would be very useful now we have got used to having it for the normal pick lists.
    • Next Page