This is a style guide for Looker's LookML data modeling language. This style guide, as well as the associated linter, Look At Me Sideways (LAMS), are designed to help make your LookML project more maintainable.
These rules are opinionated, and might imply significant changes to a LookML project that has been developed organically. We've tried to provide rationales throughout so you can come to your own conclusions. However, at their core, these rules are about making your LookML and SQL reusable, self-explanatory, and reliable.
Summary: Implement consistent dimensions to communicate information about views' keys to developers who use the view
pk{n}_{key_name}......, where n is the total number of columns that form the primary key, and which may be omitted if it is 1, and key_name is any descriptive name.
Note: This applies to "regular" views that describe an underlying table, i.e. through a sql_table_name, derived_table, or implicit table name. In some cases, you may have a "field-only view", which would be joined using `join: {sql: ;;}`, for which this rule would not apply.
Rationale: With this naming convention, anyone creating a join can conclusively find the correct logic without having to investigate:
Additionally, anyone reading the join could conclusively verify it.
view: carriers {
sql_table_name: faa.carriers ;;
dimension: carrier_id {
hidden: yes
primary_key: yes
sql:${TABLE}.id;;
}
}
# ^ Altough `primary_key: yes` is used, the
# naming convention has not been followed
explore: flights {
join: carriers {
relationship: many_to_one
sql_on: ${carriers.carrier_id}
= ${flights.carrier_id} ;;
# ^ is this logic right? I
# would need to inspect the
# view definition to confirm
}
}
view: carriers {
sql_table_name: faa.carriers ;;
dimension: pk1_carrier_id {
hidden: yes
primary_key: yes
sql:${TABLE}.id;;
}
}
explore: flights {
join: carriers {
relationship: many_to_one
sql_on: ${carriers.pk1_carrier_id}
= ${flights.carrier_id} ;;
# ^ I know the join cardinality
# must be correct because I see it's
# joining on the primary key
}
}
# Example of a composite primary key
view: membership {
sql_table_name: membership ;;
dimension: pk2_user_id {
hidden:yes
sql:${TABLE}.user_id;;
}
dimension: pk2_group_id {
hidden:yes
sql:${TABLE}.group_id;;
}
dimension: user_x_group {
hidden:yes
primary_key: yes
sql: ${pk2_user_id} || 'x' || ${pk2_group_id} ;;
}
}
explore: invitations {
join: membership {
relationship: many_to_one
sql_on: ${membership.pk2_user_id}
= ${invitations.to_user_id}
AND ${membership.pk2_group_id}
= ${invitations.group_id} ;;
# ^ I can tell there MUST be only one membership
# for each row from the left table. Looks good.
}
}
explore: users {
join: membership {
relationship: many_to_one
sql_on: ${membership.pk2_user_id} = ${users.id} ;;
# ^ Without even examining the view, I can
# tell that something is wrong here!
# (And rule E2 can check this for me)
}
}
pk1_account_id over pk1_id. This way, views that logically share one or more primary keys can be recognized.pk3_a, pk3_b, and pk3_c, NOT pk1_a, pk1_b, and pk1_c.primary_key: yes (if necessary) so Looker can use it for generating symmetric aggregates. This is a small price to pay for the many instances of time saved looking up primary key information when writing/reading explores.{n}pk. This has been changed to reflect the fact that many databases do not allow column names to start with a number.... and the table definition should be defined before any other dimensions.
Rationale: By placing primary keys immediately below a derived table definition, users viewing the view file can more easily verify that the Primary Key Dimensions match the derived table's actual primary keys.
Rationale: The audience for PK information is developers. They use it to inform how to join and consume tables, and they can do so equally well with a hidden field.
Note: If a column that is a primary key should be user facing, you may want to expose it via a separate dimension.
primary_key dimension...unless the view declares that it has no primary key via a pk0_ named dimension.
# Missing a primary_key:yes dimension
view: users {
sql_table_name: users ;;
}
view: users {
sql_table_name: users ;;
dimension: pk1_user_id {
primary_key: yes
hidden: yes
sql: ${TABLE}.user_id ;;
}
}
# Too many primary_key:yes dimensions
view: users {
sql_table_name: users ;;
dimension: pk1_user_id {
primary_key: yes
hidden: yes
sql: ${TABLE}.user_id ;;
}
dimension: id {
primary_key: yes
sql: ${TABLE}.user_id ;;
}
}
view: log_events {
sql_table_name: log_events ;;
dimension: pk0_user_id {
hidden: yes
}
}
primary_key dimension must use or be the Primary Key Dimension(s)In the case of a simple, 1-column primary key, this simply means the Primary Key Dimension and the primary_key:yes dimension are the same dimension
view: users {
sql_table_name: users ;;
dimension: pk1_user_id {
primary_key: yes
hidden: yes
sql: ${TABLE}.user_id ;;
}
}
However, for composite primary keys, you should ensure that the primary_key:yes dimension uses all of the Primary Key Dimensions in its sql:
view: memberships {
sql_table_name: memberships ;;
dimension: pk2_user_id {
hidden: yes
sql: ${TABLE}.user_id ;;
}
dimension: pk2_group_id {
hidden: yes
sql: ${TABLE}.group_id ;;
}
dimension: membership_id {
hidden: yes
primary_key: yes
sql: ${pk2_user_id} || "-" || ${pk2_group_id} ;;
}
}
Summary: Implement fields in ways which (a) maximize the ability of developers to reuse them in the future, and (b) maximize the usability of explores for end users
... unless this is (A) a field-only view, or (B) a tightly coupled view (provide a base explore too!)
Rationale: Inter-view dependencies interfere with the re-use of the view
view: users {...}
view: orders {
...
measure: orders_per_user {
sql: ${count} / NULLIF(${users.count},0)
}
}
explore: orders {} # Errors :(
view: users {...}
view: orders {...}
view: users_orders {
# No need for a sql_table_name or derived_table
measure: orders_per_user {
sql: ${orders.count} / NULLIF(${users.count},0)
}
}
explore: orders {} #Doesn't break like before!
explore: users {
join: orders {...}
join: users_orders {
sql: ;;
# Use `sql` instead of `sql_on` and put some whitespace in it
relationship: one_to_one
view_label: "Orders" #For cleaner explore UI
}
}
view_label.Rationale: Field-level view labels can't be overridden by a join. Prefer view-level view labels.
"Plain" count fields can/should specify a filter of "primary key dimensions (or any non-nullable field) are not null"
Rationale: By default Looker will implement any non-filtered & non-distinct count field as a `COUNT(*)`. Filtering such "plain" counts on PK IS NOT NULL ensures correct counts in all of the following uses of the field: Counting just that table, counting that table when joined on as a one-to-one-or-zero table, counting that table with symmetric aggregates when joined on as a many_to_one table, and counting that table in explores with join paths.
measure: count {
type: count
filters:{
field: pk1_user_id
value: "NOT NULL"
}
}
Note: The LookML filter syntax for "is not null" varies depending on the type of the field. For strings, use -NULL. For numbers, use NOT NULL.
Rationale: User experience. Just do it.
Note: Think about the audience when you write a description. Information for end users can go in the description, whereas information for other developers can go in a LookML comment
number that appear to be IDs or USD currency should specify value_format_name.Non-hidden fields with type: number that represent numeric IDs or USD currency should specify an appropriate value_format_name (unless a custom value_format is already set):
value_format_name: id for numeric ID fields (detected from primary_key: yes or ID-related keywords in the field's name, label, or description).value_format_name: usd or usd_0 for USD currency fields (detected from USD-related keywords in the field's name, label, or description).Rationale: By default, Looker formats type: number fields with thousand separators (e.g., 12,345) and no currency symbol, which is undesirable for numeric IDs and ambiguous for currency amounts.
view: orders {
dimension: user_id {
type: number
sql: ${TABLE}.user_id ;;
}
measure: total_usd {
type: number
sql: ${TABLE}.amount_usd ;;
}
}
view: orders {
dimension: user_id {
type: number
value_format_name: id
sql: ${TABLE}.user_id ;;
}
measure: total_usd {
type: number
value_format_name: usd_0
sql: ${TABLE}.amount_usd ;;
}
}
Long field names or labels are truncated in Looker's Explore field picker and visualization legends, making them harder for users to scan and distinguish. Keep field labels concise (30 characters or fewer by default), and use description for longer explanations.
Note: In LAMS, you can customize the max length for this rule by setting a maxLength option associated with this rule in your manifest file.
dimension: order_status {
type: string
}
dimension: order_status {
label: "Current Fulfillment Status of the Customer Order"
type: string
}
dimension: order_status {
label: "Order Status"
description: "Current fulfillment status of the customer order"
type: string
}
# Providing a custom limit in manifest.lkml
#LAMS
#rule: F9 {options: {maxLength: 40}}
suggest_explore and suggest_dimension must reference available explores and dimensions in the modelWhen a field uses suggest_explore or suggest_dimension to source filter suggestions, Looker's validator may not catch cases where the referenced explore, joined view, or dimension is unavailable in the model.
Ensure that:
suggest_explore is specified, that explore exists in the model, and any suggest_dimension (qualified as view_name.dimension_name or unqualified within the current view) is available in that explore and exists in the target view.suggest_dimension is specified without suggest_explore, an unqualified dimension_name exists in the current view, and a qualified view_name.dimension_name is available in every non-hidden explore where the current view is used.
view: orders {
dimension: customer_id {
type: number
suggest_explore: customer_analytics
suggest_dimension: customers.customer_name
}
}
view: customers {
dimension: customer_name {
type: string
}
}
explore: customer_analytics {
from: customers
}
view: orders {
dimension: customer_id {
type: number
suggest_explore: nonexistent_explore
suggest_dimension: customers.customer_name
}
}
"-NULL" for string fields and "NOT NULL" for numeric fieldsLooker filter expressions handle "NOT NULL" and "-NULL" differently depending on the target field's data type:
type: string, type: zipcode, or default untyped dimensions): "-NULL" checks for SQL IS NOT NULL, whereas "NOT NULL" matches the literal string 'NOT NULL'.type: number): "NOT NULL" checks for SQL IS NOT NULL, whereas "-NULL" is invalid number filter syntax.type: time / type: date, e.g., created_date or created_time): Both "NOT NULL" and "-NULL" compile to IS NOT NULL. Note that raw timeframes (*_raw) cannot be used in filters; filter on a non-raw timeframe such as *_date or *_time instead.See also rule E8 for Explore always_filter and conditionally_filter.
measure: active_emails {
type: count
filters: [email: "-NULL"]
}
measure: positive_or_present_amounts {
type: count
filters: [amount: "NOT NULL"]
}
measure: active_emails {
type: count
filters: [email: "NOT NULL"]
}
measure: present_amounts {
type: count
filters: [amount: "-NULL"]
}
Field alias declarations allow renaming fields while preserving backward compatibility for existing Explores, Looks, and Dashboards. If an alias collides with another field's name or another field's alias in the same view (including expanded dimension_group timeframes or duration intervals), Looker's field resolution becomes ambiguous.
view: orders {
dimension: order_id {
type: string
}
dimension: id {
alias: [order_id] # Conflicts with dimension: order_id
type: string
}
dimension: created {
alias: [legacy_date]
}
dimension: updated {
alias: [legacy_date] # Conflicts with alias on created
}
}
view: orders {
dimension: id {
alias: [legacy_order_id]
type: string
}
dimension_group: created {
type: time
timeframes: [date, week]
alias: [order_created] # Expands to order_created_date, order_created_week
}
}
Summary: Restrict the ways in which you write the SQL for derived tables in order to make them more modular and their results more realiable and understandable.
Note: These rules may seem hard to comply with at first. Although they may represent a large change from your usual way of writing SQL, the change also brings a large positive impact.
Rationale: sql_trigger_value is an older construct and can have subtle timing issues when multiple tables interact.
Rationale: Primary keys define a contract that allows anyone reviewing the logic of a query to evaluate it modularly. Without them, any attempt to troubleshoot a query requires an arbitrarily deep investigation of related subqueries. With them, each query and subquery can be evaluated independently against their declared PK and the declared PK's of the participating tables.
view: user_lifetime {derived_table: {sql:
SELECT
user_id as pk1_user_id
---
COUNT(*) as lifetime_orders,
SUM(amount) as lifetime_spend
FROM orders
GROUP BY user_id ;;}
view: user_lifetime {derived_table: {sql:
SELECT
user_id,
COUNT(*) as lifetime_orders,
SUM(amount) as lifetime_spend
FROM orders
GROUP BY 1 ;;}
derived_table: {sql:
WITH orders AS (
SELECT order_id, SUM(amount) FROM order_items
GROUP BY 1
)
-- ^ The rule applies to CTE's/subqueries as well
SELECT
user_id as pk1_user_id
---
COUNT(*) as lifetime_orders,
SUM(amount) as lifetime_spend
FROM orders
GROUP BY user_id ;;}
...where {n} is the total number of columns in the primary key
view: events_rollup {derived_table: {sql:
SELECT
site as pk2_site,
date as pk2_date,
---
COUNT(*) as events
FROM events
GROUP BY site,date ;;}
Note: If you are using _in_query to generate a dynamic derived table where a column may or may not be present in the derived table's primary key, you should always select a static number of PK columns and conditionally NULL out their values, rather than selecting a dynamic number of columns.
view: dynamic_events_rollup {derived_table: {sql:
SELECT
site as pk2_site,
{% if date.date._in_query %} date as pk2_date, {% endif %}
---
COUNT(*) as events
FROM events
GROUP BY site,date ;;}
view: dynamic_events_rollup {derived_table: {sql:
SELECT
site as pk2_site,
{% if date.date._in_query %} date
{% else %} NULL
{% endif %} as pk2_date,
---
COUNT(*) as events
FROM events
GROUP BY site,date ;;}
derived_table: {sql:
SELECT
COUNT (*) as order_count,
user_id as pk1_user_id
FROM orders
GROUP BY user_id ;;}
view: instance_daily {derived_table: {sql:
SELECT
events.instance_id as pk2_instance_id,
events.event_date as pk2_event_date,
---
events.app_version,
COUNT(*) as events
FROM events
GROUP BY 1,2,3
;;}}
view: instance_daily {derived_table: {sql:
SELECT
events.instance_id as pk3_instance_id,
events.event_date as pk3_event_date,
events.app_version as pk3_app_version,
---
COUNT(*) as events
FROM events
GROUP BY 1,2,3
;;}}
view: instance_daily {derived_table: {sql:
SELECT
events.instance_id as pk3_instance_id,
events.event_date as pk3_event_date,
ROW_NUMBER() OVER (
PARTITION BY events.instance_id, events.event_date
) as pk3_app_version_sequence
---
events.app_version,
COUNT(*) as events
FROM events
GROUP BY 1,2
;;}}
Although the above two "questionable" examples satisfy rules T4 & T6, you will likely find that it is not natural to join them on their entire primary key when you try to use them elsewhere.
view: instance_daily {derived_table: {sql:
SELECT
events.instance_id as pk2_instance_id,
events.event_date as pk2_event_date,
---
MAX(events.app_version) as app_version,
-- Maybe min too depending on business logic
COUNT(*) as events
FROM events
GROUP BY 1,2
Note: This rule requires some reasoning to evaluate, but with proper PK information, can be done within the context of the current query. For example, the 1-to-1 full outer join example coalesces the PK's from the two sides of the join to come up with the effective primary key of the join.
SELECT
sites.pk1_id as pk2_site_id,
dates.pk1_date as pk2_date,
---
daily_rollup.count
FROM sites
CROSS JOIN dates
LEFT JOIN daily_rollup
ON daily_rollup.pk2_site_id = sites.pk2_id,
AND daily_rollup.pk2_site_id = sites.pk2_id
SELECT
sessions.pk1_id as pk1_session_id,
---
sites.name,
dates.is_holiday
FROM sites
CROSS JOIN dates
INNER JOIN sessions
ON sessions.date = sites.pk1_id,
AND sessions.site_id = dates.pk1_id
SELECT
COALESCE(
historical.pk2_site_id,
incremental.pk2_site_id
) as pk2_site_id,
COALESCE(
historical.pk2_date,
incremental.pk2_date
) as pk2_date
---
COALESCE(
incremental.count
historical.count,
) as count
FROM historical
FULL OUTER JOIN incremental
ON incremental.pk2_site_id = historical.pk2_site_id,
AND incremental.pk2_date = historical.pk2_date
... T5/T6 did not use ALL available columns. The window function should have a PARTITION BY of the preceding PK columns (at least one required)
Note: Actually, any window function that produces unique values for each row is acceptable, but this is almost always ROW_NUMBER().
Make sure not to use a RANK-like window function instead of ROW_NUMBER. The former yields duplicate ranks when two rows match. (For example, "Monday, Monday, Tuesday" would have ranks of 1,1,3)
SELECT
user_id as pk2_user_id,
ROW_NUMBER() OVER (
PARTITION BY user_id
ORDER BY id ASC
) as pk2_order_sequence_number,
---
id as order_id
GROUP BY 1,2
SELECT
ROW_NUMBER() as pk1_id,
---
*
FROM (
SELECT site, date, source, count(*) as session_count
FROM sessions
GROUP BY 1,2,3,4
)
I only mention the above example because I've actually seen it used. The primary key for this is simply site,date,source. The ROW_NUMBER added as an afterthough is not a primary key. (In this ruleset, it is disallowed by rules T5/T6 which require one or more columns to precede the window function, if any)
view: user_lifetime {derived_table: {sql:
SELECT
user_id as pk1_user_id
---
COUNT(*) as lifetime_orders,
SUM(amount) as lifetime_spend
FROM orders
GROUP BY user_id ;;}
Note: This does not strictly need to immediately follow the columns required by rules T5 - T7. After, such columns, the PK may continue with 0, 1, or more aggregates, but this is rare, and in most cases such aggregates would not need to be in a primary key.
Rationale: Often, short subqueries are desired for existence or scalar logic that are (a) not reused outside of the current query, and (b) simple enough to read and understand that they can be analyzed in the context of the containing query with little added complexity
view: new_orders {derived_table:{sql:
SELECT
pk1_order_id
FROM orders
WHERE order_date > (SELECT MAX(order_date) FROM order_rollup)
-- ^ This single-column subquery is exempt
;;}}
view: pending_users {derived_table:{sql:
SELECT
pk1_user_id
FROM users
WHERE id IN (SELECT user_id FROM orders WHERE status='Pending')
-- ^ This single-column subquery is exempt
;;}}
Rationale: Since this style of query/subquery simply passes on the PK attributes of the referenced table/query, it's reasonable to save time writing this query and for readers of your query to go find that PK information in that single other table/query.
view: customers {derived_table: {sql:
SELECT *
FROM ${accounts.SQL_TABLE_NAME}
WHERE is_customer = TRUE
;;}}
required_filter (or assert a small row count via a data test)# T3: Table-Backed Views Must Declare Required Filter or Small Row Count
## Why?
Querying large tables without filtering on a partition, sort, or index key can trigger full table scans, inflating query latency and warehouse compute costs.
Declaring #LAMS required_filter: on table-backed views (both native tables via sql_table_name and Persistent Derived Tables) ensures that explorers (see also rule E4) always filter on a selective column.
For small lookup or dimension tables, partition pruning is not beneficial when the table size is below the database's minimum block size (for example, BigQuery's minimum partition/block scan unit or Snowflake micro-partition size). Scanning a single block costs the same regardless of pruning, so for small tables a LookML data test asserting a maximum row count is an accepted alternative to required_filter.
## Sub-rules
- T3.1: Any view backed by a table (sql_table_name or a PDT, excluding ephemeral derived tables and views without a table) that is the base of a non-hidden explore must either declare #LAMS required_filter: or be covered by a LookML test: on that explore asserting a maximum row count.
- T3.2: If #LAMS required_filter: is present on the view, must resolve to a valid field (dimension, dimension group / timeframe, filter, parameter, or measure) in that view.
- T3.3: If #LAMS required_filter: is present and the view is a PDT with a sql definition (excluding sql_create and create_process PDTs), the referenced field's sql must contain ${TABLE}. matching the first entry of sortkeys, indexes, or partition_keys (if any is declared).
## Examples
### Native table (sql_table_name) with required_filter
view: orders {
#LAMS required_filter: created_date
sql_table_name: analytics.orders ;;
dimension_group: created {
type: time
timeframes: [date, week, month]
sql: ${TABLE}.created_at ;;
}
}
### PDT with partition_keys matching required_filter
view: events_pdt {
#LAMS required_filter: event_date
derived_table: {
sql: SELECT event_date, user_id FROM raw.events ;;
datagroup_trigger: daily_etl
partition_keys: ["event_date"]
}
dimension: event_date {
type: date
sql: ${TABLE}.event_date ;;
}
}
### Small lookup table with a row-count data test
view: country_codes {
sql_table_name: ref.country_codes ;;
dimension: code {
sql: ${TABLE}.code ;;
}
measure: count {
type: count
}
}
explore: country_codes {}
test: country_codes_is_small {
explore_name: country_codes
assert: max_rows {
expression: ${country_codes.count} <= 1000 ;;
}
}
# T11: Asserted Uniques / Explicit MIN, MAX, and ANY Aggregates
## Why?
Developers sometimes use MIN(...), MAX(...), or ANY_VALUE(...) when grouping to pick a supposedly uniform value across rows, which silently hides data quality issues if the value is not actually unique. Rather than assuming the value is representative, either assert uniqueness (for example, by checking MIN(x) <> MAX(x)) or alias the column to make clear that it is a min, max, or arbitrary sample value.
## Rule
In a derived_table's SELECT list, unguarded MIN(...), MAX(...), and ANY(...) / ANY_VALUE(...) expressions must be aliased to a name containing one of the allowed fragments:
- MIN: min, minimum, first, earliest
- MAX: max, maximum, last, latest
- ANY / ANY_VALUE: any, sample
Expressions that assert uniqueness by comparing MIN(...) and MAX(...) inside a CASE or ERROR(...) guard are allowed with any alias.
### Options
You can configure additional allowed alias fragments (for example, in other languages) in manifest.lkml:
``lkml
#rule: T11 {
# options: {
# min_fragments: ["minimo", "primeiro"]
# max_fragments: ["maximo", "ultimo"]
# any_fragments: ["qualquer"]
# }
#}
``
## Examples
view: user_accounts {
derived_table: {
sql:
SELECT
user_guid AS pk1_user_guid,
MIN(account_id) AS account_id
FROM events
GROUP BY user_guid
;;
}
}
view: user_accounts {
derived_table: {
sql:
SELECT
user_guid AS pk1_user_guid,
CASE WHEN MIN(account_id) <> MAX(account_id)
THEN ERROR("Non-unique account_id for user_guid")
ELSE MIN(account_id)
END AS account_id,
MIN(created_at) AS first_created_at,
MAX(created_at) AS latest_created_at,
ANY_VALUE(region) AS sample_region
FROM events
GROUP BY user_guid
;;
}
}
# T14: Persisted Derived Tables Should Not Use Liquid or Dynamic SQL
## Why?
Triggered persistent derived tables (PDTs) do not have the explore query context needed to evaluate dynamic Liquid logic, and even persist_for derived tables do not behave as expected with dynamic SQL. Ephemeral (non-persisted) derived tables may use Liquid/dynamic SQL freely.
Note: {{_model._name}} is allowed because it is static within the context of a model.
## Rule
Any derived_table with persistence (persist_for, datagroup_trigger, sql_trigger_value, interval_trigger, create_process, sql_create, or materialized_view) must not contain Liquid tags ({% ... %}) or expressions ({{ ... }}) in its SQL, except {{_model._name}}.
## Examples
view: user_orders_pdt {
derived_table: {
datagroup_trigger: daily_etl
sql:
SELECT user_id, COUNT(*) AS order_count
FROM orders
WHERE {% condition date_filter %} created_at {% endcondition %}
GROUP BY 1
;;
}
}
view: user_orders_ephemeral {
derived_table: {
sql:
SELECT user_id, COUNT(*) AS order_count
FROM orders
WHERE {% condition date_filter %} created_at {% endcondition %}
GROUP BY 1
;;
}
}
view: user_orders_pdt {
derived_table: {
datagroup_trigger: daily_etl
sql:
SELECT user_id, COUNT(*) AS order_count
FROM {{_model._name}}.orders
GROUP BY 1
;;
}
}
# T15: Avoid Unqualified UNION (Prefer UNION ALL)
## Why?
Developers often write UNION instead of UNION ALL unintentionally, triggering an expensive sort/deduplication across all columns. If deduplication is actually required, make that intent explicit with UNION DISTINCT or an accompanying comment such as UNION /*DISTINCT*/.
## Rule
SQL in derived_table or sql_table_name must not use bare UNION. Use UNION ALL, UNION DISTINCT, or include an accompanying comment immediately after UNION (e.g., UNION /*DISTINCT*/).
## Examples
view: combined_events {
derived_table: {
sql:
SELECT id, event_type FROM web_events
UNION
SELECT id, event_type FROM mobile_events
;;
}
}
view: combined_events {
derived_table: {
sql:
SELECT id, event_type FROM web_events
UNION ALL
SELECT id, event_type FROM mobile_events
;;
}
}
view: deduplicated_events {
derived_table: {
sql:
SELECT id, event_type FROM web_events
UNION /*DISTINCT*/
SELECT id, event_type FROM mobile_events
;;
}
}
${view_name.field_name}
explore: orders {
join: users {
relationship: many_to_one
sql_on: ${users.1pk_id} = ${orders.user_id} ;;
}
}
explore: orders {
join: users {
relationship: many_to_one
sql_on: users.id = orders.user_id ;;
}
}
Note: Sometimes you may want to make joins dynamic using _in_query. This requires you to reference fields to join on IF the view is _in_query but NOT use the substitution operator since that forces the view to be in the query.
This is relevant for any 1:1, 1:m, m:1, 1:0or1 joins. In other words, any non-many-to-many join (which you should only be using with great caution).
By default (strict_mode: no), E2 accepts joins constrained on pk{n}_ dimensions, a primary_key: yes dimension (including composite primary key dimensions whose sql combines multiple referenced columns), or all columns in a derived table's GROUP BY or SELECT DISTINCT list. Set options: { strict_mode: yes } in manifest.lkml to require the pk{n}_ naming convention.
join: users {
relationship: many_to_one
sql_on: ${pk1_user_id} = ${orders.user_id} ;;
}
join: users {
relationship: many_to_one
sql_on: ${users.id} = ${orders.user_id} ;;
# ^ I can only _hope_ that this is right, or spend time verifying it
}
join: dates {
relationship: many_to_many
sql_on: ${dates.pk1_date} >= $[users.created_date} AND ${dates.pk1_date} <= $[users.deleted_date} ;;
}
required_filter must declare an always_filter referencing that field# E4: Explores Must Enforce Base View Required Filter
## Why?
When a table-backed view declares #LAMS required_filter: (see rule T3), that declaration documents which field should be filtered to avoid expensive full-table scans. Rule E4 ensures that every non-hidden explore based on that view enforces the filter via always_filter.
## Rule
For any non-hidden explore whose base view (explore.from, explore.view_name, or the explore's own name) declares #LAMS required_filter: , the explore must declare an always_filter referencing (qualified as , , or unqualified).
## Example
view: orders {
#LAMS required_filter: created_date
sql_table_name: analytics.orders ;;
dimension_group: created {
type: time
timeframes: [date, week, month]
sql: ${TABLE}.created_at ;;
}
}
explore: recent_orders {
from: orders
always_filter: {
filters: [recent_orders.created_date: "7 days"]
}
}
# E5: Avoid Multiplicative Fanout in Explores
## Why?
Joining multiple independent one_to_many branches from the same explore (or using many_to_many joins) can cause multiplicative fanout, making queries slow and creating spurious many-to-many relationships between unrelated entities. While Looker's symmetric aggregates can still compute accurate measures in some cases, the resulting cross-product of rows often confuses users and degrades query performance.
## Rule
Within an explore:
1. No join may declare relationship: many_to_many.
2. When one_to_many joins are connected as a directed graph to the joins or base explore referenced in their join condition (sql_on, sql, or foreign_key), the one_to_many subgraph may have at most one leaf node (i.e., a linear one_to_many chain is allowed, but branching one_to_many paths are not).
## Examples
orders and favorites are both joined one_to_many from users, forming two leaf nodes in the one_to_many subgraph:
explore: users {
join: orders {
relationship: one_to_many
sql_on: ${users.id} = ${orders.user_id} ;;
}
join: favorites {
relationship: one_to_many
sql_on: ${users.id} = ${favorites.user_id} ;;
}
}
A linear one_to_many chain (users -> orders -> order_items) has only one leaf node (order_items):
explore: users {
join: orders {
relationship: one_to_many
sql_on: ${users.id} = ${orders.user_id} ;;
}
join: order_items {
relationship: one_to_many
sql_on: ${orders.id} = ${order_items.order_id} ;;
}
}
Or refactor branching one_to_many joins using a unioned bridge table (user_join_paths) so only one one_to_many join is needed from users (see A Cure for the One-to-Many Blues for a detailed walkthrough of this refactoring pattern):
explore: users {
join: user_join_paths {
relationship: one_to_many
sql_on: ${users.id} = ${user_join_paths.user_id} ;;
}
join: orders {
relationship: one_to_one
sql_on: ${user_join_paths.order_id} = ${orders.id} ;;
}
join: favorites {
relationship: one_to_one
sql_on: ${user_join_paths.favorite_id} = ${favorites.id} ;;
}
}
foreign_key based join, do not use a *-to-many relationshipNote: Specifying join logic using sql_on is usually preferred to using foreign_key, as sql_on is more general-purpose.
If you do use foreign_key to specify your join logic, Looker will implicitly join this declared foreign key against the primary key of the joined table. As such, the resulting join should be a many_to_one join (or rarely one_to_one if you use the primary key of the base view as the foreign key in the join)
explore: orders {
join: users {
foreign_key: user_id
relationship: many_to_many
}
}
explore: orders {
join: users {
foreign_key: user_id
relationship: many_to_one
}
}
# Joins are already implicitly many_to_one by default, so this is ok
explore: orders {
join: users {
foreign_key: user_id
}
}
# In some cases, one_to_one is appropriate
explore: orders {
join: orders_derived_table {
foreign_key: pk1_order_id
relationship: one_to_one
}
}
Among other reasons to favor brevity, long explore names/labels will be truncated in Looker's Explore picker UI. Help maintain a good experience for end users by keeping Explore names at or below 25 characters.
Note: In LAMS, you can customize the max length for this rule by setting a maxLength option associated with this rule in your manifest file.
explore: orders {}
explore: orders {
label:"Data Warehouse: BigQuery > Schema: Business > Datamart: eCommerce > Facts > Orders"
}
explore: orders {
label: "Orders"
description: "Data Warehouse: BigQuery > Schema: Business > Datamart: eCommerce > Facts > Orders"
}
# Providing a custom limit in manifest.lkml
#LAMS
#rule: E7 {options: {maxLength: 50}}
always_filter and conditionally_filter should use "-NULL" for string fields and "NOT NULL" for numeric fieldsLooker filter expressions handle "NOT NULL" and "-NULL" differently depending on the target field's data type:
type: string, type: zipcode, or default untyped dimensions): "-NULL" checks for SQL IS NOT NULL, whereas "NOT NULL" matches the literal string 'NOT NULL'.type: number): "NOT NULL" checks for SQL IS NOT NULL, whereas "-NULL" is invalid number filter syntax.type: time / type: date, e.g., created_date or created_time): Both "NOT NULL" and "-NULL" compile to IS NOT NULL. Note that raw timeframes (*_raw) cannot be used in filters; filter on a non-raw timeframe such as *_date or *_time instead.See also rule F11 for filtered measures.
explore: orders {
always_filter: {
filters: [orders.status: "-NULL", orders.amount: "NOT NULL"]
}
}
explore: orders {
always_filter: {
filters: [orders.status: "NOT NULL", orders.amount: "-NULL"]
}
}
A key principle to avoid overwhelming users and to help them quickly find what they need is to limit the number of available options at any given time. Besides entirely hiding things, the best way to do this is by adding hierarchy.
This section provides a set of rules across different objects to suggest introducing hierarchy whenever the number of object/sub objects grows large.
Wrap a view's identifying dimensions (ID, name, etc) in square brackets to visually distinguish them and hoist them to the top of the field picker. This may be done either directly on the dimension's label, or on a group label.
Rationale: This provides a visual hint to explore users about the subject and structure of each view.
For views without primary keys or identifiers, there are no fields to hoist. If a view declares 0 primary keys via a pk-naming convention, LAMS will not require any hoisting.
Note: LAMS will not identify which fields should be hoisted, just suggest that some should be hoisted when none are found.
Note: LAMS configuration can specify different prefixes/sufixes to use instead of the suggested square brackets by specifying the desired characters in prefix and suffix options. Simply make sure to use a prefix that sorts higher than other typically used characters
# Providing a custom format in manifest.lkml
#LAMS
#rule: H1 {options: {prefix: " 🔑" suffix: ""}}
When the number of dimensions/measures in a view's field picker exceeds 20, use `group_label` to reduce clutter.
Note: LAMS configuration can specify a different threshold to use instead of 20:
# Providing options in manifest.lkml
#LAMS
#rule: H2 {options: {threshold: 30}}
When already using group_label (or when having a number of dimension groups), if the number of groups under a view's field picker exceeds 10, use label prefixes to sort and organize groups. Separate the prefix with " > " to visually indicate hierarchy.
# Labels below aligned to help illustrate field picker
dimension: annual_contract_value { group_label: "ACV" ...}
dimension: widgets_annual_contract_value {group_label: "ACV" ...}
dimension_group: close_date { group_label: "Close" ...}
dimension: incremental_acv { group_label: "IACV" ...}
dimension: widgets_incremental_acv { group_label: "IACV" ...}
dimension_group: start_date { group_label: "Start" ...}
dimension: total_contract_value { group_label: "TCV" ...}
dimension: widgets_tv { group_label: "TCV" ...}
...
# Labels below aligned to help illustrate field picker
dimension_group: close_date { group_label: "Dates > Close" ...}
dimension_group: start_date { group_label: "Dates > Start" ...}
dimension: annual_contract_value { group_label: "Value > ACV" ...}
dimension: widgets_annual_contract_value {group_label: "Value > ACV" ...}
dimension: incremental_acv { group_label: "Value > IACV" ...}
dimension: widgets_incremental_acv { group_label: "Value > IACV" ...}
dimension: total_contract_value { group_label: "Value > TCV" ...}
dimension: widgets_tv { group_label: "Value > TCV" ...}
Note: LAMS configuration can specify a different threshold to use instead of 10, and a different delimiter to use:
# Providing options in manifest.lkml
#LAMS
#rule: H3 {options: {threshold: 12 delimiter: ": "}}
When already using group_label and/or sorting groups, if the number of options under a view's field picker still exceeds 30, group fields into your available groups more proactively.
Rationale: The prior two rules provide a first line of defense by alerting developers to available features they may not know to use. However, if after making those options available, the number of options presented to a user at a time is still too large, this rule encourages developers to explicitly target reducing that overall number. Accordingly the threshold is set slightly higher.
Wrap an explore's base view in square brackets to visually distinguish it and hoist it to the top of the field picker.
The rule may be ignored for explores that have no joins, and for hidden explores.
Rationale: Many or most explores in Looker follow a snowflake schema - a central fact table, and a number of many-to-one dimensional joins. Hoisting the main view that the explore represents to the top of the field picker helps visually reinforce the central/primary nature of that view within the explore.
explore: orders {
view_label: "[Orders]"
...
Note: LAMS configuration can specify different prefixes/sufixes to use instead of the suggested square brackets. Make sure to use a prefix that sorts higher than other typically used characters
# Providing custom options in manifest.lkml
#LAMS
#rule: H5 {options: {
# prefix: " 📊"
# suffix: ""
# enforceHidden: yes
#}}
When the numer of views in an explore's field picker exceeds 20, use label prefixes to sort and organize views.
explore: orders {
join: user {}
join: first_orders {
view_label: "User > First Order"
}
join: first_orders {
view_label: "User > First Order"
}
...
Note: LAMS configuration can specify a different delimiter and/or threshold.
# Providing custom options in manifest.lkml
#LAMS rule: H6 {options: {threshold: 10 delimiter: ": "}}
Note: To enable the linter to effectively enforce whitespace-related rules, you may have to consider how conditional comments (e.g. `#LAMS`) will be pre-processed. The parser will preserve whitespace before the comment on each line, and will consume the comment character (#), the conditional comment token, and up to one space or tab character. For multi-line commented blocks, it will visually appear that there is one additional level of indentation. See test project #33 for an example.
Each LookML block within a file should add one level of indentation for any inner line breaks, except for the line containin the block's closing brace, which should be at the prior indentation.
The parser rule surfaces errors reported by lookml-parser. P0 and P1 are enabled by default (unless disabled via rule: P { enabled: no }); schema validation errors (P2–P4) require opting in via rule: P {} in manifest.lkml:
PARSE_ERROR — Generic parser error other than the specific codes below (enabled by default).SYNTAX_ERROR — LookML syntax error (after expanding any #LAMS conditional comments). Includes a hint with expected syntax context when available (enabled by default).DUPLICATE_SINGULAR_PROPERTY — A singular LookML property was declared more than once in the same block (opt-in via rule: P {}).INVALID_PROPERTY_TYPE — A LookML property value does not match the expected schema type (opt-in via rule: P {}).MISSING_REQUIRED_PROPERTY — A required LookML property is missing from a block (opt-in via rule: P {}).In some circumstances, the linter may run into errors while running that are recoverable, and may report them along with its rule findings.