Skip to content
ConsultEvo

HubSpot SQL Tutorial: Query CRM and Marketing Data with Confidence

HubSpot makes it possible to manage contacts, companies, deals, campaigns, and activity data in one CRM. However, built-in reports do not answer every operational question. When a team needs a more specific view of the data, SQL provides a precise way to select records, apply conditions, combine related objects, and summarize results.

This HubSpot SQL tutorial explains the underlying query concepts and, more importantly, how to use them responsibly. In many cases, HubSpot data is accessed through an export, connected warehouse, reporting database, or analytics tool rather than by running SQL directly inside the CRM. The syntax may vary by platform, but the reasoning remains the same.

The useful sequence is simple: define the business question, identify the relevant data objects, write the smallest query that can answer it, validate the result, and only then turn it into a recurring report or workflow. SQL is valuable because it makes data logic visible. It is not valuable merely because it produces a more technical-looking dashboard.

What SQL adds to HubSpot reporting

HubSpot reports are designed for common CRM and marketing questions. SQL becomes useful when the question crosses objects, requires custom calculations, or needs a level of filtering that is difficult to express in a standard report.

For example, a team may want to compare companies that received a marketing touchpoint with companies that later created a qualified deal. That question may involve contacts, companies, activities, and deals, together with rules about dates and ownership. SQL can make each rule explicit instead of hiding it inside an opaque spreadsheet or manually assembled export.

SQL should make a business question more precise, not compensate for an unclear reporting requirement.

Before writing a query, state the decision the result should support. A useful question is: What will someone do differently if this number changes? If the answer is unclear, the query is probably premature.

The data model behind a HubSpot SQL query

SQL works with structured data. Although the names depend on the system that stores your HubSpot data, the basic relationships are familiar:

  • A table contains a type of record or a set of events.
  • A row represents one record, such as a company, deal, contact, or email event.
  • A column stores one attribute, such as lifecycle stage, owner, amount, or create date.
  • A key identifies a record or connects it to another table.

Do not assume that one HubSpot object maps neatly to one row in every reporting database. A company can have multiple contacts, a contact can have multiple activities, and a deal can change stages over time. Those relationships affect the number of rows returned by a query.

This is one of the most important distinctions in CRM analysis: a record count is not automatically a business count. Counting activity rows may count events, while counting company IDs may count organizations. Decide what the unit of analysis is before selecting a metric.

SQL fundamentals for HubSpot data

SELECT and FROM: choose the data

The SELECT clause identifies the columns you want to return, while FROM identifies the table or view that contains them. A simple query might request a deal identifier, amount, stage, and owner from a deals table.

Start with a small set of fields. Selecting every available column makes it harder to understand the result and can expose duplicated, deprecated, or poorly maintained properties. Specific fields also make the query easier to review when another person needs to maintain it.

WHERE: define the population

WHERE filters rows before they are returned. Typical HubSpot analysis filters by create date, close date, lifecycle stage, deal type, owner, region, or business unit.

Use parentheses when combining AND and OR conditions. Without them, the database may interpret the logic differently from the way a reader expects. Also decide how to handle blank values. A missing industry, owner, or close date may mean that data is incomplete, not that the record belongs in a meaningful “unknown” segment.

ORDER BY and LIMIT: inspect before you scale

ORDER BY sorts results, such as newest deals first or highest-value opportunities first. LIMIT restricts the number of rows returned. Together, they are useful for testing a query on a manageable sample before building a full report.

A limited result is suitable for inspection, not for calculating a business total. If a query uses LIMIT during development, remove it or document it before the result is used operationally.

GROUP BY and aggregate functions: turn rows into measures

Aggregate functions summarize data. COUNT can count records, SUM can total numeric values, and AVG can calculate an average. GROUP BY creates a summary for each category, such as monthly pipeline, deal owner, or lifecycle stage.

Aggregation requires a clear definition. For example, “new deals” might mean deals created during a period, while “won revenue” might mean deals with a closed-won stage and a close date in that period. These are different business states and should not be treated as interchangeable.

Why this matters

A report becomes trustworthy when its metric definitions explain which records are included, which date is used, and what one row represents.

Joining HubSpot objects without distorting the result

Joins connect related tables through shared identifiers. A deal may connect to a company through an association table, or a contact may connect to several activities. The exact structure depends on the export or warehouse model.

An inner join returns records with a match in both sources. A left join keeps all records from the first source and adds matching data where available. A left join can be useful when you want to see every deal, including deals without an assigned company or campaign association.

The main danger is row multiplication. Suppose one company has five contacts and three deals. Joining those records without understanding the relationship can produce fifteen combinations. A later SUM may then overstate revenue, and a COUNT may overstate the number of companies.

Before joining HubSpot objects, ask whether the relationship is one-to-one, one-to-many, or many-to-many.

When a join can create duplicates, first decide whether the analysis needs distinct entities, event rows, or a pre-aggregated summary. Sometimes the safest approach is to summarize activities by company before joining the result to deals. The right query is determined by the business grain, not by the shortest syntax.

A practical sequence for building a HubSpot SQL query

Use this sequence when turning a reporting request into a query. It works for a one-off investigation as well as a recurring dashboard.

01Name the decisionWrite the decision the report supports, such as prioritizing unworked qualified leads or reviewing pipeline coverage by owner.
02Define the grainChoose whether one result row represents a contact, company, deal, activity, campaign, or time period.
03Identify the required fieldsList the identifiers, dates, statuses, ownership fields, and measures needed to answer the question.
04Build and test the smallest queryStart with one table, then add filters, calculations, and joins one at a time.
05Validate against known recordsCheck sample records manually and compare totals with a trusted source before publishing the result.
06Assign an ownerDocument the definition, refresh expectation, and person responsible for investigating exceptions.

This sequence prevents a common failure mode: creating a technically valid query that no one can explain, verify, or act on.

Example: analysing HubSpot pipeline data

Consider a hypothetical sales team that wants to identify open deals requiring attention. The business question is not simply “show open deals.” It may be: Which open deals have had no recorded activity in the last fourteen days, have an assigned owner, and are expected to close within the current quarter?

A useful query would need a defined open-stage rule, a close-date window, an activity date, and a decision about which activity types count. It should also avoid counting multiple activity records as multiple deals. The output might contain one row per deal, with the deal owner, amount, expected close date, and most recent qualifying activity date.

The report is only useful if an owner knows what to do with it. For example, the sales manager may review the list in a weekly pipeline meeting, while an operations owner investigates deals that are missing activity dates. The SQL supports the operating rhythm, but it does not replace the decision or the ownership.

Data quality checks before trusting the result

SQL can expose data problems, but it cannot decide whether a property is meaningful. Build simple checks into the analysis process:

HubSpot query validation checklist
  • Confirm that the date field matches the question, such as create date versus close date.
  • Check whether inactive, deleted, test, or duplicate records are included.
  • Compare a sample of output records with the source CRM.
  • Check for blank owners, stages, amounts, or association IDs.
  • Look for duplicate rows after every join.
  • Document the definition of each calculated metric.
  • Confirm who reviews anomalies and how often.

Pay particular attention to historical stage reporting. A current deal stage does not necessarily tell you which stage the deal occupied last month. Historical analysis may require stage-change events or a separate history table. If that history is unavailable, describe the limitation instead of presenting current-state data as a historical trend.

Using SQL thinking even when you do not write the query

Not every HubSpot user needs to become a data engineer. Understanding SQL concepts still improves collaboration with analysts, developers, and RevOps teams. You can describe the required tables, fields, filters, joins, and output grain more clearly. You can also challenge a report that combines incompatible populations or uses an unexplained metric.

SQL thinking improves HubSpot configuration as well. If a lifecycle stage is used as both a marketing status and a sales forecast category, reporting will become ambiguous. If ownership is not consistently assigned, handoffs and accountability will be difficult to measure. If a workflow changes a property without a defined business rule, a query may faithfully report inconsistent data.

For teams reviewing the wider CRM architecture, HubSpot consulting can be relevant when reporting requirements expose problems in pipeline design, property structure, integrations, or automation. Broader CRM consulting may be appropriate when the same data issues span multiple systems.

Use SQL for

Transparent analysis

Investigating relationships, applying explicit logic, validating records, and producing repeatable measures from structured data.

Do not use SQL for

Unclear operating rules

Hiding unresolved definitions, replacing ownership, or creating a dashboard before the team knows which decision it should support.

Where automation and AI fit

Once a metric and its decision rule are stable, automation can deliver the result to the right person or trigger a controlled follow-up. For example, a validated exception report could create a review task when a defined condition is met. Automation should come after the data logic is tested, not before.

AI can also help explain query results, suggest fields, or identify unusual records, but it needs a defined job and a reliable source. It should not be treated as an authority on an ambiguous metric. A useful control is to require the underlying query, filters, and source timestamp to remain visible alongside any AI-generated summary.

More reporting tools do not create a better operating system unless the data definitions, ownership, and follow-up actions are clear.

For examples of connected systems that combine operational data, reporting, and automation, see ConsultEvo’s client work portfolio. The relevant lesson is not a particular tool. It is the need to connect data to a repeatable business process.

How to keep improving your HubSpot SQL skills

Begin with SELECT, FROM, WHERE, ORDER BY, and LIMIT. Then learn aggregation, joins, date logic, conditional expressions, and subqueries. Practise with questions that resemble real CRM decisions rather than isolated syntax exercises.

For each query, save the business question, source tables, filter rules, expected grain, validation method, and owner. This small amount of documentation makes the query easier to maintain when HubSpot properties change or reporting requirements evolve.

The goal of a HubSpot SQL tutorial is not to make every marketer write complex database code. It is to help teams ask better questions, understand how CRM data is structured, catch misleading results, and build reporting that supports decisions with less manual work.

FAQ

Frequently asked questions

Can you run SQL directly inside HubSpot?

It depends on the HubSpot product, account setup, and connected data environment. Many teams run SQL against an exported dataset, data warehouse, reporting database, or analytics platform rather than directly in the CRM.

What HubSpot data is useful for SQL analysis?

Common sources include contacts, companies, deals, owners, activities, marketing events, campaign data, and association records. The available fields and relationships depend on how the data has been exported or modelled.

What is the most common mistake when joining HubSpot data?

The most common mistake is overlooking one-to-many or many-to-many relationships. A join can multiply rows, which may inflate counts and revenue totals unless the query uses the correct grain or pre-aggregates the data.

Do HubSpot marketers need to learn advanced SQL?

Not always. Basic SELECT, filtering, sorting, aggregation, and data-grain concepts are often enough to improve reporting discussions and validate simple analyses. More advanced queries can be handled with an analyst or data engineering partner.

How should a HubSpot SQL report be validated?

Check the date definition, record population, exclusions, joins, duplicate rows, blank values, and metric definitions. Compare a sample with the CRM and assign an owner to investigate exceptions.

ConsultEvo

Make HubSpot reporting easier to trust

If your HubSpot reports depend on unclear properties, inconsistent ownership, or manual data preparation, ConsultEvo can help clarify the process, CRM structure, and reporting logic before automation is added.