Tools And Features Hogql
PostHogOfficialCreated by PostHog
- Skill
- Tool integration
- Data and AI
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
HogQL is PostHog's SQL dialect, designed as a wrapper around ClickHouse SQL to simplify data access and analytics within the PostHog platform. This skill provides the essential reference material for constructing queries, including how to access event and person properties, utilize PostHog-specific functions, and integrate UI-based filters into your SQL insights. It emphasizes performance and efficiency, offering guidelines on aggregation, time-range filtering, and query structure to help users build effective analytics dashboards.
What it does
- Provides syntax patterns for querying events, persons, and sessions.
- Explains how to access event and person properties using specific dot notation.
- Details the use of the {filters} placeholder for dynamic dashboard filtering.
- Lists supported ClickHouse functions and aggregation methods for data analysis.
- Offers performance optimization tips like using uniq() over count(distinct).
- Provides guidance on using cohort and action-based filtering in SQL.
When to use it
- When you need to create custom SQL insights in PostHog.
- When you want to perform complex data analysis beyond standard UI-based reports.
- When you need to optimize existing queries for better performance.
- When you are building dashboards that require dynamic date ranges or user-defined filters.
Advantages
- Simplifies complex ClickHouse SQL for common analytics tasks.
- Enables seamless integration with PostHog's UI-based filtering system.
- Provides access to specialized PostHog functions like windowFunnel and sequenceMatch.
- Promotes efficient query patterns to reduce load on the underlying database.
Usage examples
- “Write a HogQL query to count pageviews by browser.”
- SELECT properties.$browser AS browser, count() FROM events WHERE event = '$pageview' AND {filters} GROUP BY browser
- “How do I count unique users in a HogQL query?”
- Use the uniq() function instead of count(distinct) for better performance, for example: SELECT uniq(person_id) FROM events WHERE {filters}
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/posthog/tools-and-features-hogql/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip tools-and-features-hogql.zip -d .agents/skills
Documentation by PostHog
HogQL queries for PostHog
This skill helps you write HogQL queries for PostHog analytics. HogQL is PostHog's SQL dialect, a wrapper around ClickHouse SQL with simplified property access and PostHog-specific functions.
Reference files
references/expressions.md- Sql expressions - docsreferences/aggregations.md- Supported aggregations - docsreferences/clickhouse-functions.md- Supported clickhouse functions - docsreferences/data-access.md- Accessing data using sql - docsreferences/variables.md- Sql variables - docsreferences/useful-functions.md- Useful sql functions - docsreferences/posthog.md- PostHog table schemas (events, persons, groups, sessions)references/sessions.md- Sessions - docs
Consult the documentation for SQL syntax, available functions, and query patterns.
Key principles
Property access: Use
properties.$property_namefor event properties andperson.properties.$property_namefor person propertiesNull handling: HogQL has simplified null handling compared to raw ClickHouse SQL
Filters placeholder: Use
{filters}in queries to allow UI-based filtering in PostHog dashboardsAggregations: Prefer ClickHouse aggregation functions like
count(),uniq(),avg(),sum()
Common patterns
Event queries
SELECT event, count()
FROM events
WHERE {filters}
GROUP BY event
ORDER BY count() DESCProperty breakdowns
SELECT properties.$browser AS browser, count()
FROM events
WHERE event = '$pageview' AND {filters}
GROUP BY browserPerson properties
SELECT person.properties.email, count()
FROM events
WHERE {filters}
GROUP BY person.properties.emailFramework guidelines
Use properties.$name syntax for event properties, person.properties.$name for person properties
Use bracket notation for special characters like properties['$feature/cool-flag']
For cohorts, filter with person_id IN COHORT 'cohort-name'
For actions, use matchesAction('action-name') in WHERE clauses
Include {filters} placeholder in WHERE clauses to enable UI-based filtering in dashboards
Use {variables.name} for reusable SQL variables across dashboards
Access dashboard date range with {filters.dateRange.from} and {filters.dateRange.to}
ALWAYS include a time range filter - shorter is faster (e.g., timestamp >= now() - INTERVAL 7 DAY)
Prefer uniq() over count(distinct) for counting unique values - it's more efficient
Don't scan the same table multiple times - use materialized views for reusable subsets
Use timestamp-based pagination instead of OFFSET for large datasets
Name queries descriptively for easier debugging in query_log
Use dateTrunc() for time-based grouping (e.g., dateTrunc('day', timestamp))
For funnel queries, use windowFunnel() or sequenceMatch() functions
Test queries in the PostHog SQL editor before using them in insights or the API
Files
- ATTRIBUTION.mdAdded by AutoGineer972 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md3.0 KiB
- references/aggregations.md3.8 KiB
- references/clickhouse-functions.md12.3 KiB
- references/data-access.md4.4 KiB
- references/expressions.md7.8 KiB
- references/posthog.md13.3 KiB
- references/sessions.md12.5 KiB
- references/useful-functions.md13.1 KiB
- references/variables.md2.8 KiB
references/clickhouse-functions.md
Supported ClickHouse functions - Docs
This is an ever-expanding list of enabled ClickHouse functions.
You can find their full definitions in the ClickHouse documentation. Additionally, we include a list of popular ones and their uses in the HogQL expressions and SQL insight documentation.
Most of the type conversion functions are safer versions of the equivalent ClickHouse functions to avoid NULL/zero mistakes. If the function's name includes a leading underscore, then it's not safe and simply calls the underlying ClickHouse function.
Arithmetic
plusminusmultiplydivideintDivintDivOrZeromodulomoduloOrZeropositiveModulonegateabsgcdlcmmax2min2multiplyDecimaldivideDecimal
Arrays and strings in common
emptynotEmptylengthreverseinnotIn
Arrays
arrayrangearrayConcatarrayElementhashasAllhasAnyhasSubstrindexOfarrayCountcountEqualarrayEnumeratearrayEnumerateUniqarrayPopBackarrayPopFrontarrayPushBackarrayPushFrontarrayResizearraySlicearraySortarrayReverseSortarrayUniqarrayJoinarrayDifferencearrayDistinctarrayEnumerateDensearrayIntersectarrayReducearrayReversearrayFilterarrayFlattenarrayCompactarrayZiparrayAUCarrayMaparrayFillarrayFoldarrayWithConstantarraySplitarrayReverseFillarrayReverseSplitarrayRotateLeftarrayRotateRightarrayExistsarrayAllarrayFirstarrayLastarrayFirstIndexarrayLastIndexarrayMinarrayMaxarraySumarrayAvgarrayCumSumarrayCumSumNonNegativearrayProductarrayStringConcatgenerateSeries
Comparison
equalsnotEqualslessgreaterlessOrEqualsgreaterOrEquals
Logical
andorxornot
Type conversions
hexunhextoInttoIntOrZero_toInt8_toInt16_toInt32_toInt64_toUInt64_toUInt128toFloattoFloatOrZerotoFloatOrDefaulttoDecimaltoUUIDtoStringtoBooltoJSONStringtoTypeNameparseDateTimeparseDateTimeBestEffortcityHash64UUIDv7ToDateTime
Dates and times
toDatetoDateTimetoDateTime64toDateTimeUS_toDatetoTimeZonetimeZoneOftimeZoneOffsettoYeartoQuartertoMonthtoDayOfYeartoDayOfMonthtoDayOfWeektoHourtoMinutetoSecondtoUnixTimestamptoUnixTimestamp64MillitoStartOfIntervaltoStartOfYeartoStartOfISOYeartoStartOfQuartertoStartOfMonthtoLastDayOfMonthtoMondaytoStartOfWeektoLastDayOfWeektoStartOfDaytoStartOfHourtoStartOfMinutetoStartOfSecondtoStartOfFiveMinutestoStartOfTenMinutestoStartOfFifteenMinutestoTimetoISOYeartoISOWeektoWeektoYearWeekagedateDiffdateTruncdateAdddateSubtimeStampAddtimeStampSubnowNOWnowInBlockcurrent_timestampcurrent_datetodayyesterdaytimeSlottoYYYYMMtoYYYYMMDDtoYYYYMMDDhhmmssaddYearsaddMonthsaddWeeksaddDaysaddHoursaddMinutesaddSecondsaddQuarterssubtractYearssubtractMonthssubtractWeekssubtractDayssubtractHourssubtractMinutessubtractSecondssubtractQuarterstimeSlotsformatDateTimedateNamemonthNamefromUnixTimestamptoModifiedJulianDayfromModifiedJulianDaytoIntervalSecondtoIntervalMinutetoIntervalHourtoIntervalDaytoIntervalWeektoIntervalMonthtoIntervalQuartertoIntervalYear
Postgres-style date functions
date_partdate_truncmake_timestampdate_bindate_adddate_subtractdate_diffmake_intervalmake_timestampz
Strings
left– operates on UTF-8 characters, not bytes (maps to ClickHouse'sleftUTF8)right– operates on UTF-8 characters, not bytes (maps to ClickHouse'srightUTF8)lengthUTF8leftPadorlpadrightPadorrpadleftPadUTF8rightPadUTF8lowerupperlowerUTF8upperUTF8isValidUTF8toValidUTF8formatreverseUTF8concatsubstringsubstringUTF8appendTrailingCharIfAbsentconvertCharsetbase58Encodebase58DecodetryBase58Decodebase64Encodebase64DecodetryBase64DecodeendsWithstartsWithtrimorbtrimtrimLeftorltrimtrimRightorrtrimencodeXMLComponentdecodeXMLComponentextractTextFromHTMLasciiconcatWithSeparatorrepeatinitcap
Searching in strings
positionpositionCaseInsensitivepositionUTF8positionCaseInsensitiveUTF8multiSearchAllPositionsmultiSearchAllPositionsCaseInsensitivemultiSearchAllPositionsCaseInsensitiveUTF8multiSearchAllPositionsUTF8multiSearchFirstPositionmultiSearchFirstPositionCaseInsensitivemultiSearchFirstPositionCaseInsensitiveUTF8multiSearchFirstPositionUTF8multiSearchFirstIndexmultiSearchFirstIndexCaseInsensitivemultiSearchFirstIndexCaseInsensitiveUTF8multiSearchFirstIndexUTF8multiSearchAnymultiSearchAnyCaseInsensitivemultiSearchAnyCaseInsensitiveUTF8multiSearchAnyUTF8matchmultiMatchAnymultiMatchAnyIndexmultiMatchAllIndicesmultiFuzzyMatchAnymultiFuzzyMatchAnyIndexmultiFuzzyMatchAllIndicesextractextractAllextractAllGroupsHorizontalextractAllGroupsVerticalextractGroupslikeilikenotLikenotILikelocatengramDistancengramDistanceCaseInsensitivengramDistanceCaseInsensitiveUTF8ngramDistanceUTF8ngramSearchngramSearchCaseInsensitivengramSearchCaseInsensitiveUTF8ngramSearchUTF8countSubstringscountSubstringsCaseInsensitivecountSubstringsCaseInsensitiveUTF8countMatchescountMatchesCaseInsensitivehasSubsequencehasSubsequenceCaseInsensitivehasSubsequenceCaseInsensitiveUTF8hasSubsequenceUTF8hasTokenhasTokenCaseInsensitivehasTokenCaseInsensitiveOrNullhasTokenOrNullhasAllTokenshasAnyTokensregexpExtract
Replacing in strings
replacereplaceAllreplaceOnereplaceRegexpAllreplaceRegexpOneregexpQuoteMetatranslatetranslateUTF8
Conditional
ifmultiIf
Mathematical
epiexploglnexp2log2exp10log10sqrtcbrterferfclgammatgammasincostanasinacosatanpowpowerintExp2intExp10coshacoshsinhasinhatanhatan2hypotlog1psigndegreesradiansfactorialwidth_bucket
Rounding
floorceiltruncroundroundBankersroundToExp2roundDurationroundAgeroundDown
Maps
mapmapFromArraysmapAddmapSubtractmapPopulateSeriesmapContainsmapKeysmapValuesmapContainsKeyLikemapExtractKeyLikemapApplymapFiltermapUpdate
Splitting strings
splitByCharsplitByStringsplitByRegexpsplitByWhitespacesplitByNonAlphaalphaTokensextractAllGroupsngramstokens
Bit
bitAndbitOrbitXorbitNotbitShiftLeftbitShiftRightbitRotateLeftbitRotateRightbitSlicebitTestbitTestAllbitTestAnybitCountbitHammingDistance
Bitmap
bitmapBuildbitmapToArraybitmapSubsetInRangebitmapSubsetLimitsubBitmapbitmapContainsbitmapHasAnybitmapHasAllbitmapCardinalitybitmapMinbitmapMaxbitmapTransformbitmapAndbitmapOrbitmapXorbitmapAndnotbitmapAndCardinalitybitmapOrCardinalitybitmapXorCardinalitybitmapAndnotCardinality
URLs
protocoldomaindomainWithoutWWWtopLevelDomainfirstSignificantSubdomaincutToFirstSignificantSubdomaincutToFirstSignificantSubdomainWithWWWportpathpathFullqueryStringfragmentqueryStringAndFragmentextractURLParameterextractURLParametersextractURLParameterNamesURLHierarchyURLPathHierarchyencodeURLComponentdecodeURLComponentencodeURLFormComponentdecodeURLFormComponentnetloccutWWWcutQueryStringcutFragmentcutQueryStringAndFragmentcutURLParameter
JSON
isValidJSONJSONHasJSONLengthJSONArrayLengthJSONTypeJSONExtractUIntJSONExtractIntJSONExtractFloatJSONExtractBoolJSONExtractStringJSONExtractKeyJSONExtractKeysJSONExtractRawJSONExtractArrayRawJSONExtractKeysAndValuesRawJSON_VALUE
Geo
greatCircleDistancegeoDistancegreatCircleAnglepointInEllipsespointInPolygongeohashDecodegeohashesInBoxh3IsValidh3GetResolutionh3GetBaseCellh3EdgeAngleh3EdgeLengthMh3EdgeLengthKmgeoToH3h3ToGeoh3ToGeoBoundaryh3kRingh3HexAreaM2h3HexAreaKm2h3IndexesAreNeighborsh3ToChildrenh3ToParenth3ToStringstringToH3h3IsResClassIIIh3IsPentagonh3GetFacesh3CellAreaM2h3CellAreaRads2h3ToCenterChildh3ExactEdgeLengthMh3ExactEdgeLengthKmh3ExactEdgeLengthRadsh3NumHexagonsh3PointDistMh3PointDistKmh3PointDistRadsh3GetRes0Indexesh3GetPentagonIndexesh3Lineh3Distanceh3HexRingh3GetUnidirectionalEdgeh3UnidirectionalEdgeIsValidh3GetOriginIndexFromUnidirectionalEdgeh3GetDestinationIndexFromUnidirectionalEdgeh3GetIndexesFromUnidirectionalEdgeh3GetUnidirectionalEdgesFromHexagonh3GetUnidirectionalEdgeBoundary
Nullable
isNullisNotNullcoalesceifNullnullIfassumeNotNulltoNullable
Tuples
tupletupleElementuntupletupleHammingDistancetupleToNameValuePairstuplePlustupleMinustupleMultiplytupleDividetupleNegatetupleMultiplyByNumbertupleDivideByNumberdotProduct
Time window
tumblehoptumbleStarttumbleEndhopStarthopEnd
Distance window
L1NormL2NormLinfNormLpNormL1DistanceL2DistanceLinfDistanceLpDistanceL1NormalizeL2NormalizeLinfNormalizeLpNormalizecosineDistance
Window functions
lagorlagInFrameleadorleadInFramerankdense_rankrow_numberfirst_valuelast_valuenth_value
Other
isFiniteisInfiniteifNotFiniteisNaNbartransformformatReadableDecimalSizeformatReadableSizeformatReadableQuantityformatReadableTimeDelta
Community questions
Ask a question
Was this page useful?
HelpfulCould be better
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- PostHog
- Publisher
- PostHog (Official)
- Source
- PostHog/skills · skills/posthog/tools-and-features/skills/hogql · commit a5d30e7
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Also distributed in
- PostHog/skills
AutoGineer is not affiliated with or endorsed by PostHog.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download tools-and-features-hogql.zip