COQL API in Zoho CRM - Part I

COQL API in Zoho CRM - Part I

Hi everyone! Welcome back to another week of Kaizen

This week, we will discuss the COQL Queries in detail.

COQL (CRM Object Query Language) is a powerful query language based on SQL syntax that allows users to write their own queries and fetch records using module API names and field API names. In this post, we will discuss the operators supported by COQL in detail and also provide examples to help you understand better.  Please note that the information in the article holds true for version 4 of Zoho CRM APIs.

When should you use the Query API?

Use Query API when you want to query for a module's data and/or it's look up related data using various comparators, or for records that fall into a custom view without actually creating one. For example, if you want to query for all products in a specific price range, with a 5 star rating and sort the results by price, use the Query API. Similarly you can use Query API to query for records from cross-modules (linked via lookup field), such as filtering products based on the vendor's details. 

What types of queries are supported by COQL?

COQL supports only the SELECT query, which is used to select data from the CRM, based on the conditions specified by the clauses. 

Here is a sample query:
SELECT {field_api_names} FROM {module_api_name} WHERE {field_api_name} {comparator} {logical_operator} {value} ORDER BY {field_api_name} ASC/DESC LIMIT {limit} OFFSET {offset}

What are the clauses & aggregate functions supported by COQL?

WHERE - used to select records based on specific conditions.
FROM - specifies the module from which to fetch the records.
ORDER BY - used to sort the results in ascending or descending order.
LIMIT - used to limit the number of records returned by the query.
OFFSET - used to skip a specified number of records while retrieving the records.


{
 "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"
}


For example, the above query retrieves the Last_Name, First_Name, Mobile and Final_score of all Leads whose status equals 'Not Contacted'. The results will be sorted in descending order based on the Final_Score field, and only the 5 records after skipping the first 10 will be returned.

NOTE : You can also use the syntax "LIMIT offset, limit" to achieve the same result. For 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, 10"
}


Aggregate functions can perform calculations on a set of values and return a single value. 
SUM() - to get the sum of the values of an aggregate field in a module.
MAX() - to get the maximum value of an aggregate field.
MIN() - to get the minimum value of an aggregate field.
AVG() - to get the average value of the values of a field.
COUNT() - to get the number of records that satisfy the criteria.

Wildcard Character Support in COQL

In COQL queries, the only supported wildcard character is %. This % wildcard can be used with the like operator to achieve functionality similar to the contains, starts_with and ends_with operators. For instance, '%tech" queries for field values ending with tech, 'C%' queries for the values starting with C, and '%tech%' translates to contains 'tech'.

Supported field types and Comparators

The following table gives a gist of the field types whose data you can query for, and the comparators for each field type.
Field TypeComparators
Text and Picklist=, !=, 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=

Supported field types and Comparators

1) Text and Picklist Fields

Supported comparators : =, !=, like, not like, in, not in, is null, is not null. Please note that the like operator is used for starts_with, ends_with, contains, and not like operator is used for not contains

Sample Query 1: (=, like, in)

{
    "select_query": "SELECT First_Name, Last_Name FROM Leads WHERE (((Lead_Status = 'Pre-Qualified') and (Company like '%zylker%')) and Industry in ('Technology', 'ERP'))"
}

This SELECT query retrieves the First_Name and Last_Name of all Leads whose Lead_Status is Pre-QualifiedCompany contains zylker, and Industry is either Technology or ERP

Sample Query 2:(not in, like, not null)

{
"select_query": "SELECT First_Name, Last_Name FROM Leads WHERE (((Lead_Status not in ('Closed-Won', 'Closed-Lost')) and (Lead_Source like '%Web%')) and (Skype_ID is not null)) LIMIT 2"
}

This query will return the first name and last name of all leads whose lead status is not Closed-Won or Closed-Lost, whose Lead Source fields contains web, and whose Skype ID field is not empty.

Sample Query 3:( !=, not like, null)

{
    "select_query": "SELECT First_Name, Last_Name, Mobile FROM Leads WHERE (((Lead_Source != 'Webinar') and (City not like '%New York%')) and (Skype_ID is null))"
}

This query retrieves the first name, last name and mobile of leads where the lead source is not a webinar, the city is not New York, and the Skype ID field is empty or null.

2. Lookup Fields

=, !=, in, not in, is null, is not null are the supported comparators for lookup fields. If you want to get the name of the lookup field in the response, you must include the field API name in the query. Otherwise, the system will return only the ID of the field.

Sample Query 1: (=, not in, !=)

{
 "select_query": "select Last_Name, First_Name, Full_Name, Account_Name, Owner from Contacts where (((Account_Name.Account_Name != 'Zylker') and (Owner = 4876876000000327001)) and Vendor_Name.Vendor_Name not in ('Skytech','SR')) LIMIT 2"
}

This query retrieves the last name, first name, full name, account name, and owner of two contacts whose account name is not Zylker, whose owner ID is 4876876000000327001, and whose vendor name does not contain Skytech or SR.
Sample Response:
{
    "data": [
        {
            "First_Name": "John",
            "Full_Name": "John Wilson  ",
            "Owner": {
                "id": "4876876000000327001"
            },
            "Last_Name": "Wilson  ",
            "Account_Name": {
                "id": "4876876000000333089"
            },
            "id": "4876876000000333182"
        },
        {
            "First_Name": "Josephine",
            "Full_Name": "Josephine Darakjy",
            "Owner": {
                "id": "4876876000000327001"
            },
            "Last_Name": "Darakjy",
            "Account_Name": {
                "id": "4876876000000333090"
            },
            "id": "4876876000000333183"
        }
    ],
    "info": {
        "count": 2,
        "more_records": true
    }
}

In this query, the id of the account is returned but not the name since we have not specified the field API name in the query. To fetch the field name, specify the field API name in the query. Refer to the following sample query to know how.

Sample Query 2:  (in, is null, is not null)

{
    "select_query": "SELECT Deal_Name, Account_Name.Account_Name, Created_Time FROM Deals WHERE (((Account_Name.Account_Name in ('Grayson','Zylker')) and (Owner is not null)) and (Contact_Name is null)) ORDER BY Created_Time DESC LIMIT 2"
}

This query retrieves the Deal Name, Account Name, and Created Time of the 2 most recently created Deals whose Account Name contains Zylker or Grayson, and do not have a Contact Name associated with them but have a Deal Owner associated with them. The results will be ordered in descending order by the Created Time.
 
Sample Response:
{
    "data": [
        {
            "Deal_Name": "Westborne Deal",
            "Created_Time": "2023-04-06T10:04:02+05:30",
            "Account_Name.Account_Name": "Grayson",
            "id": "4876876000003548001"
        },
        {
            "Deal_Name": "Eastwing Deal",
            "Created_Time": "2023-04-05T19:10:55+05:30",
            "Account_Name.Account_Name": "Grayson",
            "id": "4876876000003526011"
        }
    ],
    "info": {
        "count": 2,
        "more_records": true
    }
}

In the same query, if you want to use the Account ID instead of the name, replace ((Account_Name.Account_Name in ('Grayson','Zylker')) with ((Account_Name in (4876876000001236083, 4876876000002799001)) to include the IDs instead of the field API names and the account names.
{
    "select_query": "SELECT Deal_Name, Account_Name.Account_Name, Created_Time FROM Deals WHERE (((Account_Name in (4876876000001236083, 4876876000002799001)) and (Owner is not null)) and (Contact_Name is null)) ORDER BY Created_Time DESC LIMIT 2"
}

3. Date, DateTime, Number, Currency Fields

=, !=, >=, >, <=, <, between, not between, in, not in, is null, is not null are the supported comparators for these fields.

Sample Query 1: (between, <, >)

{

    "select_query": "SELECT Deal_Name, Amount, Stage, Probability FROM Deals WHERE (((Closing_Date between '2023-01-01' and '2023-03-31') and (Probability < 99)) and (Amount > 10000))"

}

This query retrieves the deal name, amount, stage, and probability of all deals whose closing date is between January 1, 2023 and March 31, 2023, and whose probability is less than 99 and amount is greater than 10000.

Sample Response:
{
    "data": [
        {
            "Deal_Name": "Chapman Deal",
            "Amount": 2500000,
            "Probability": 97,
            "Stage": "Closed Won",
            "id": "4876876000003550011"
        }
    ],
    "info": {
        "count": 1,
        "more_records": false
    }
}

Sample Query 2: (<=, !=, >=)

{
    "select_query": "SELECT Product_Name, Qty_in_Stock, Vendor_Name, Cost_Price FROM Products WHERE (((Sales_End_Date <= '2023-04-30') and (Qty_in_Stock != 0)) and (Cost_Price >= 500))"
}

This query retrieves the product name, quantity in stock, vendor name, and cost price for all products whose sales end date is on or before April 30, 2023, whose quantity in stock is not zero, and whose cost price is greater than or equal to 500. Since Vendor_Name is a lookup field, only the ID will be returned in the response.
Sample Response
{
    "data": [
        {
            "Cost_Price": 2000,
            "Vendor_Name": {
                "id": "4876876000001039017"
            },
            "Product_Name": "Sigma",
            "Qty_in_Stock": 30,
            "id": "4876876000001036109"
        }
    ],
    "info": {
        "count": 1,
        "more_records": false
    }
}

Sample Query 3: (not between, is not, >)

{
    "select_query": "SELECT Last_Name, First_Name, Referred_By.Full_Name FROM Leads WHERE (((Final_Score not between 10 and 20) and (Annual_Revenue is not null)) and (No_of_Employees > 200)) LIMIT 1"
}

This COQL query selects the last name, first name, and the full name of the lead's referred by field, for one lead whose final score is not between 10 and 20annual revenue is not null and whose number of employees is greater than 200
Sample Response
{
    "data": [
        {
            "First_Name": "Chau",
            "Last_Name": "Kitzman",
            "id": "4876876000000333403",
            "Referred_By.Full_Name": "Simmons Truhlar"
        }
    ],
    "info": {
        "count": 1,
        "more_records": true
    }
}

Sample Query 4: (>, not in, =, is null)

{
   "select_query":"SELECT PO_Number, PO_Date, Status, Discount FROM Purchase_Orders WHERE (((PO_Date = '2023-04-06') and (Due_Date not in ('2023-04-10','2023-04-11', '2023-04-12'))) or ((Discount > 10) and (Requisition_No is null)))"
}

This query selects the PO_Number, PO_Date, Status, and Discount from the Purchase_Orders module where the PO_Date is equal to '2023-04-06' and Due_Date is not any of '2023-04-10', '2023-04-11', or '2023-04-12'; OR Discount is greater than 10 and Requisition_No is null. In this query, we have used both AND and OR operators to combine the clauses.
Sample Response
{
    "data": [
        {
            "Status": "Created",
            "PO_Date": "2022-05-10",
            "Discount": 9990,
            "PO_Number": "PO-JL-3876",
            "id": "4876876000001125176"
        },
        {
            "Status": "Created",
            "PO_Date": "2023-04-06",
            "Discount": 370.37,
            "PO_Number": "PO-DA-1932",
            "id": "4876876000003561019"
        }
    ],
    "info": {
        "count": 2,
        "more_records": false
    }
}

We hope you found this post useful and that it has given you a better understanding of COQL queries. In our next post, we will discuss the rest of the field types, aggregate functions with more examples, and provide more queries to help you get started.

If you have any questions or feedback, please let us know in the comments below, or write to us at support@zohocrm.com. We would love to hear from you! 

Additionally, if you have any questions about the COQL API or how to construct a query, kindly let us know in the comments.

Additional Reading:


    • Recent Topics

    • Can't delete/hide related lists

      Hi, Maybe I'm missing something, but I can't seem to find where I delete or hide related lists in a module. When I go to a record and click the little arrow on the right next to the related list, I only get the option to select what fields in that list
    • Make Widgets Clickable or Copiable

      Hi, I created a KPI Widget in Zoho Analytics whose content I would like the users that see my dashboard could copy or click and be redirected elsewhere. Yes, I'm aware I can create a Text Box for that instead of a Widget, but the problem is that the link
    • Custom API - Need to create a string return value, not only MAP

      @Support: When creating a Custom API it only allows a return from a function of MAP type. The service I'm using requires a string return, how can this be achieved?
    • Automate data upload process like reports

      I'll start with the end in mind.  I want to basically keep certain creator tables updated with data that are in a sql database/tables in our office (employees, active jobs, employee positions) so I can reference that data and not have to duplicate it by hand every time someone adds a new job or employee in the office desktop software.  Here are some thoughts I had about how to do this, but am unsure as to whether any of them are actually possible and how to go about it from there: Is there any way
    • Address Autofill

      Hi I'm having issues with the address autofill tutorial (https://zurl.co/rGXQ). I have followed each step in the tutorial, but when i paste the code into a workflow/function, i'm getting the following error code: Improper code format Correct format :
    • Sync custom module ID to Lead module

      Hello, I am trying to sync Contract ID (custom module) from Deal module. I have an existing function that whenever a contract is created, it will automatically creating deals based on the frequency of the contract. Now i am having problem to show the
    • In Kiosk, please support "File upload field" in the "Field Update" action

      Hello. Supporting "File upload field" in the "Field Update" actions would be a great addition to Kiosk Studio. I would appreciate it if you could evaluate it. Saludos,
    • can I link a contacts to multiple accounts

      can I link a contacts to multiple accounts
    • Change Last Name to not required in Leads

      I would like to upload 500 target companies as leads but I don't yet have contact people for them. Can you enable the option for me to turn this requirement off to need a Second Name? Moderation update (10-Jun-23): As we explore potential solutions for
    • For security reasons your account has been blocked as you have exceeded the maximum number of requests per minute that can originate from one account.

      Hello Zoho Even if we open 10-15 windows in still we are getting our accounts locked with error " For security reasons your account has been blocked as you have exceeded the maximum number of requests per minute that can originate from one account. "
    • Zoho Creator - Zoho Analytics

      I am facing an issue in Zoho Analytics where I am still seeing deleted data from the Zoho Creator form I created. Could you please look into this and let me know what needs to be done?
    • The Social Wall: November 2024

      Hey everyone, As we move into December, we're excited to share all the updates that went live in Social during November. View, monitor, and respond to your WhatsApp and Telegram messages from Inbox Take your communication a step further by integrating
    • Launching CPQ for Zoho CRM! An in-built solution for bespoke quote management

      Hello everyone, We are thrilled to announce the public release of CPQ (Configure, Price, Quote) for Zoho CRM, which is a fundamental block in sales management. NOTE: CPQ was a public early access feature from March 2023 — January 2024. Since February
    • Add an action to set agent as a member of a team in zoho desk

      Hi, Please add an action to zoho flow to set agent as a member of a team in zoho desk (add to a team or remove from a team). Regards, Ram
    • Power of Automation :: Automatically set the dependency between Parent task and the respective sub tasks

      A custom function is a software code that can be used to automate a process and this allows you to automate a notification, call a webhook, or perform logic immediately after a workflow rule is triggered. This feature helps to automate complex tasks and
    • Registration in community

      Namaste I am from Shimla, But there is no option selection of shimla.
    • Spell Check default language

      Hello All, Is it possible to set the Spell Check default language? I can't find it in the settings. Thanks a lot! Levente
    • Function #4: Schedule Customer Statements

      Regularly sending statements to customers is an imperative part of many business processes as it helps foster strong customer relationships and provides timely guidance on payments. While you can generate the statement of accounts and have it sent over
    • Music files on Zoho Docs

      1) Uploaded a ma3 music file from Itunes.  When I click on the link, i go to the page and see a music player but it doesn't play.  Clicking on the play arrow does nothing.  How to fix???? 2) Also, when i put up a .zip file  and goto the page, anyone download it.  That's fine. But with a music file, all I get is that non functional player with no way to simply download the song. Do I have to zip every song so it can be downloaded?
    • 5名限定 課題解決型ワークショップイベント Zoho ワークアウト開催のお知らせ (12/19)

      ユーザーの皆さま、こんにちは。Zoho ユーザーコミュニティチームの藤澤です。 12月開催のZoho ワークアウトについてお知らせします。 参加登録はこちら: https://us02web.zoom.us/meeting/register/tZAqdOCrrDMtGdL3w__UraUPaZxJpeS_wcyt ━━━━━━━━━━━━━━━━━━━━━━━━ Zoho ワークアウトとは? Zoho ユーザー同士で交流しながら、サービスに関する疑問や不明点の解消を目的とした「Zoho ワークアウト」を開催します。
    • Restrict Employees Access to Zoho Support

      Dear Zoho Support Team, Greetings! I am the focal point for all Zoho-related matters in our organization, and I would like to request the following features to help us streamline and centralize our support interactions. We request that zoho one support
    • How to import timesheets or entries into a projecgt

      How can one import timesheets into a project via a csv file?
    • Automatic License Management Upon User Deactivation in Zoho One

      Dear Zoho Team, We would like to propose a feature enhancement for Zoho One regarding license management. Currently, when a user is deactivated, their license is not automatically downgraded or removed from our account. Zoho explains this behavior by
    • Shared Snippets Everyone

      Hi, Now that the Shared Snippets have been released and I think will be the most used feature implemented in 2023 :) Creating and Using Snippets in Ticket Responses - Online Help | Zoho Desk Maintain consistency in ticket responses with shared snippets
    • Introducing parent-child ticketing in Zoho Desk [Early access]

      Hello Zoho Desk users! We have introduced the parent-child ticketing system to help customer service teams ensure efficient resolution of issues involving multiple, related tickets. You can now combine repetitive and interconnected tickets into parent-child
    • How to suppress display of "USD" of currency field?

    • When is Zoho Vault getting fuzzy search?

      Seeing posts on here dating back as far as 3 years complaining about Vaults search functionality. It’s terrible. Please include fuzzy search, and sorting of results according to “most applicable”; not just alphabetically.
    • Automation#22 Track Ticket Duration at Specific Status

      Hello Everyone! Welcome back to the Community Learning Series! Today, we explore how Zylker Techfix, a gadget servicing firm, boosted productivity by tracking the time spent at a particular ticket status in Zoho Desk. Zylker Techfix customized Zoho Desk’s
    • Self-Support Portal invites

      I'm a one man operation and I'm using the free version of the Zoho Desk for now, but I am in need of help. When I do test tickets, I get a reply from the system inviting me to join the Self Service portal. I don't plan on using that, so I wonder if there
    • Lookup field in User module cannot look up to custom modules!

      Hi there, Expense has been great so far but it's sad to see that a simple thing such as allowing a lookup to custom modules from the Users module is not yet implemented. Hope to see this in the next release. Do you have any plan for that?
    • Tip #10: Automatically add tags to Zoho CRM records using form responses

      You may be using tags to filter records, create reports based on specific tags, or let your sales team to know which clients to give priority to. Don't skip tagging for the crm records added via forms. The tags can be set to be automatically captured during the form submission. How it works When you set up a configuration to push form entries into CRM, you can add a tag to them automatically. The tag value can vary based on the respondent's input (captured using form fields), or you can include a
    • Understanding response time

      We have the following set up for our SLA. When a contact first writes in, the response due and resolution due dates are set. When one of our agents responses, the response due goes away. When a ticket gets a response from the contact, it appears to reset
    • Publish multiple languages at once in Knowledge Base

      Does anyone know if it is possible to publish multiple translated articles at the same time? My knowledge base has about 35 languages, and while I have them set up to automatically translate, I still have to go in and select each language and manually
    • Canvas and Related lists

      Hi, As much as I like canvas, when adding in a asection with related lists,it doesnt mimic the same functionality as the standard view within the CRM e.g left hand panel will show the module and total number of records. Is there a way of indicating this
    • Email address ZOHO suggestions in replying - how to delete unwanted suggestions?

      Hi, I have some "unwanted" email addresses suggestions by ZOHO, and made some mistakes by replying for some tickets already. How can I clear this in ZOHO directly, I deleted all web browser history and cookies . Did not help :/ Below example, where one
    • Copy Widget to another Dashboard

      I can see the option to clone a widget to the same dashboard but is it possible to copy it to another dashboard?
    • Subform edits don't appear in parent record timeline?

      Is it possible to have subform edits (like add row/delete row) appear in the Timeline for parent records? A user can edit a record, only edit the subform, and it doesn't appear in the timeline. Is there a workaround or way that we can show when a user
    • CRM x WorkDrive: File storage for new CRM signups is now powered by WorkDrive

      Availability Editions: All DCs: All Release plan: Released for new signups in all DCs. It will be enabled for existing users in a phased manner in the upcoming months. Help documentation: Documents in Zoho CRM Manage folders in Documents tab Manage files
    • Zoho Learn vs. Trainer Central

      Hi, I'm currently using Zoho One with a WordPress-based website and WooCommerce to manage my online courses. I would like to know what is the difference between Zoho Learn and Trainer Central and if it's possible for these two platforms to replace WP
    • How to Display a Logo Image on a Public Form?

      I would like to display a logo image in the header of a form. To achieve this, I added an Add Notes field to the form. The code below works perfectly for Zoho users accessing the form. However, when the form is made public, the image does not load properly:
    • Next Page