Skip to main content

Knowledge Bases

A Knowledge Base (KB) is a governed layer of institutional knowledge that data agents use when they turn a natural-language question into SQL.

The ontology defines what the data means: concepts, relationships, measures. The Knowledge Base records how your organization uses it: how analysts phrase questions, how a business term is really defined, which property or relationship to prefer, and which query patterns have already been reviewed and approved.

Natural-language question  →  Knowledge Base context  →  Governed SQL

This page is the SQL reference for creating and managing Knowledge Bases. To manage them from the UI, see Knowledge Bases in the Timbr Platform.

The whole language is two verbs

CREATE KNOWLEDGEBASE creates a container. ALTER KNOWLEDGEBASE adds, updates or drops the knowledge inside it. Every item carries its settings in an OPTIONS (...) block, so the syntax stays small and consistent.


How a Knowledge Base is used​

When a user asks a data agent a question, Timbr looks up the relevant knowledge in every Knowledge Base bound to that ontology or agent, and gives it to the agent before it writes SQL.

Two kinds of knowledge are looked up in different ways:

ItemLooked up byApplies when
EXAMPLEMatching the user's question against the example's questionThe new question is similar to a question you have already answered
INSTRUCTION, VALIDATION, SELECTION_RULEThe ontology object the rule is attached toThat concept, property, measure, relationship, view or cube is used in the query, however the question was phrased

Depending on how closely the question matches existing knowledge, the agent will:

  1. Reuse approved SQL when a vetted example clearly answers the question.
  2. Use examples as guidance when related examples exist, steering the generated SQL towards proven patterns.
  3. Generate from the ontology alone when nothing relevant exists. The query is still governed and validated.

Throughout, Timbr's permissions apply: users only receive knowledge they are cleared to see, and the SQL runs through the same governance, RBAC and validation as any other Timbr query. Retrieval is fast: relevant knowledge is returned in under a second, inside Timbr, so a Knowledge Base adds no noticeable latency to an agent's answer.


Typical workflow​

StepWhat you doStatement
1. CreateCreate an empty Knowledge Base containerCREATE KNOWLEDGEBASE
2. TeachAdd golden examples and rulesALTER KNOWLEDGEBASE ... ADD
3. BindMake it available to an ontology or to specific agentsALTER ONTOLOGY / ALTER AGENT ... ADD KNOWLEDGEBASE
4. AskUsers ask questions; the relevant knowledge is used automatically–
5. GrowReview suggested improvements from users and agents, and accept the good onesALTER KNOWLEDGEBASE SUGGESTION

The examples on this page use a sample sales ontology with the concepts order, customer and product, the relationships placed_by[customer] and includes_product[product], and the measure total_revenue.


Create a Knowledge Base​

CREATE KNOWLEDGEBASE creates only the container. Examples and rules are added afterwards with ALTER KNOWLEDGEBASE.

Syntax:

CREATE [OR REPLACE] KNOWLEDGEBASE <kb_name> [DESCRIPTION '<description>'];
ClauseRequiredNotes
<kb_name>✓Unique name. Start with a letter or underscore, and use only letters, numbers and underscores.
DESCRIPTIONRecommendedWhat the KB covers and who it is for.

Example:

CREATE KNOWLEDGEBASE finance_kb DESCRIPTION 'Finance & sales analytics KB';

CREATE OR REPLACE updates the description of an existing Knowledge Base without touching its examples, rules or bindings, so it is safe to re-run:

CREATE OR REPLACE KNOWLEDGEBASE finance_kb DESCRIPTION 'Finance & sales analytics KB - revenue, orders and customers';

Drop a Knowledge Base​

DROP KNOWLEDGEBASE [IF EXISTS] <kb_name>;
DROP KNOWLEDGEBASE IF EXISTS finance_kb;
caution

Dropping a Knowledge Base also removes all of its examples, rules and ontology/agent bindings. Use IF EXISTS in scripts so the statement does not fail when the KB is already gone.


Examples (golden set)​

An EXAMPLE is a reusable, question-level pattern that your analysts have approved. Use examples for the questions your users actually ask, and for business terms that need a fixed definition.

Syntax:

ALTER KNOWLEDGEBASE <kb_name> ADD EXAMPLE <example_name>
OPTIONS (
question = '<natural-language question or term>',
[validate_sql = true | false,]
[instructions = '<guidance or definition>']
)
[AS <sql_query>];
OptionRequiredNotes
question✓The question as your users would phrase it, or a business term. An example without a question is rejected.
validate_sql–Default false. When true, the AS query is validated against the ontology when the example is saved.
instructions–Guidance for answering the question, or the definition of a term when there is no SQL.
AS <sql_query>–The approved SQL that answers the question.
target_name, target_typeNot allowedThese options belong to rules. They are rejected on an example.
Write the SQL against the ontology

The AS query should select from ontology concepts through the dtimbr schema (for example dtimbr.order) and use relationships and measures by name, not raw source tables. That keeps the approved pattern tied to the business model: it keeps working when mappings or sources change and it respects the same permissions as any other ontology query. See Querying the Knowledge Graph.

An example can hold a question with SQL, a question with instructions, or all three.

Question with approved SQL​

Use this when there is a known-correct query for the question.

ALTER KNOWLEDGEBASE finance_kb ADD EXAMPLE monthly_revenue
OPTIONS (
question = 'Show total revenue by month',
validate_sql = true,
instructions = 'Only include completed orders. Group by calendar month of order_date.'
)
AS
SELECT DATE_TRUNC('month', order_date) AS month,
SUM(measure.total_revenue) AS revenue
FROM dtimbr.`order`
WHERE order_status = 'completed'
GROUP BY 1
ORDER BY 1;

An example that traverses relationships instead of writing joins:

ALTER KNOWLEDGEBASE finance_kb ADD EXAMPLE top_customers_by_revenue
OPTIONS (
question = 'Who are our top 10 customers by revenue?',
validate_sql = true
)
AS
SELECT `placed_by[customer].customer_name` AS customer_name,
SUM(measure.total_revenue) AS revenue
FROM dtimbr.`order`
WHERE order_status = 'completed'
GROUP BY 1
ORDER BY 2 DESC
LIMIT 10;

Question with a definition (no SQL)​

Use this to pin down what a vague business term means, so every question that uses the term is answered the same way. No SQL is stored; the instructions carry the definition.

ALTER KNOWLEDGEBASE finance_kb ADD EXAMPLE active_customer_definition
OPTIONS (
question = 'active customers',
instructions = 'An active customer is a customer with at least one completed order in the trailing 90 days.'
);
ALTER KNOWLEDGEBASE finance_kb ADD EXAMPLE revenue_definition_question
OPTIONS (
question = 'How is revenue calculated?',
instructions = 'Revenue is the total_revenue measure on completed orders only, unless the user explicitly asks to include other statuses.'
);

Update an example​

UPDATE is a partial update: only the options you specify change, everything else (including the question and SQL) is kept.

ALTER KNOWLEDGEBASE finance_kb UPDATE EXAMPLE monthly_revenue
OPTIONS (
instructions = 'Only include completed orders. Default to the last 12 months when no period is given.'
);

To replace the stored SQL, include a new AS clause:

ALTER KNOWLEDGEBASE finance_kb UPDATE EXAMPLE monthly_revenue
OPTIONS (validate_sql = true)
AS
SELECT DATE_TRUNC('month', order_date) AS month,
SUM(measure.total_revenue) AS revenue
FROM dtimbr.`order`
WHERE order_status = 'completed'
AND order_date >= CURRENT_DATE - INTERVAL '12' MONTH
GROUP BY 1
ORDER BY 1;

Drop an example​

ALTER KNOWLEDGEBASE finance_kb DROP EXAMPLE active_customer_definition;

Rules: INSTRUCTION, VALIDATION, SELECTION_RULE​

Rules attach guidance to a specific ontology object. A rule is used whenever that object takes part in a query, regardless of how the question was worded. Use rules for the conventions analysts apply without thinking: default filters, formats, which date to use, what a term maps to.

Rule typePurposeTypical use
INSTRUCTIONHow to use an object correctlyDefault filters, case handling, required time frames
VALIDATIONA correctness or format checkValue formats, lengths, valid ranges
SELECTION_RULEWhich object or path to choose when several could applyDefault date property, which measure a business term means, which relationship to follow

All three types share the same syntax and options:

ALTER KNOWLEDGEBASE <kb_name>
ADD { INSTRUCTION | VALIDATION | SELECTION_RULE } <rule_name>
OPTIONS (
target_name = '<ontology object name>',
target_type = 'concept' | 'property' | 'measure' | 'relationship' | 'cube' | 'view',
instructions = '<guidance text>'
);
OptionRequiredNotes
target_name✓The name of the ontology object the rule is attached to. It must exist in the ontology.
target_type✓One of concept, property, measure, relationship, cube, view.
instructions✓The guidance itself.
question, AS <sql>Not allowedRules are not matched by question. These are rejected.
Why rules need a target

Examples are found by matching the user's question. Rules have no question, so target_name and target_type are what tell Timbr where the rule belongs and when to apply it: only when that object is used.

INSTRUCTION​

-- Normalize how a property is filtered
ALTER KNOWLEDGEBASE finance_kb ADD INSTRUCTION customer_name_case
OPTIONS (
target_name = 'customer_name',
target_type = 'property',
instructions = 'Values are stored in mixed case. Always compare customer_name using lower() on both sides.'
);

-- Require a time frame whenever a measure is used
ALTER KNOWLEDGEBASE finance_kb ADD INSTRUCTION revenue_needs_timeframe
OPTIONS (
target_name = 'total_revenue',
target_type = 'measure',
instructions = 'Always aggregate revenue over an explicit period (month, quarter or year). Do not return an all-time total unless the user asks for it.'
);

-- A default filter for a concept
ALTER KNOWLEDGEBASE finance_kb ADD INSTRUCTION completed_orders_default
OPTIONS (
target_name = 'order',
target_type = 'concept',
instructions = 'Unless the user asks otherwise, only include orders where order_status = ''completed''.'
);

VALIDATION​

-- Format guard on a property
ALTER KNOWLEDGEBASE finance_kb ADD VALIDATION account_number_format
OPTIONS (
target_name = 'account_number',
target_type = 'property',
instructions = 'account_number is always 9 characters. Left-pad shorter numeric values with zeros: lpad(value, 9, ''0'').'
);

-- Sanity bound on a measure
ALTER KNOWLEDGEBASE finance_kb ADD VALIDATION revenue_non_negative
OPTIONS (
target_name = 'total_revenue',
target_type = 'measure',
instructions = 'Revenue must be greater than or equal to zero. A negative result indicates refunds were not excluded.'
);

SELECTION_RULE​

-- Default date property for time-based questions
ALTER KNOWLEDGEBASE finance_kb ADD SELECTION_RULE default_order_date
OPTIONS (
target_name = 'order_date',
target_type = 'property',
instructions = 'Use order_date for time filters and grouping, unless the user explicitly names another date such as ship_date.'
);

-- Map a business term to a specific measure
ALTER KNOWLEDGEBASE finance_kb ADD SELECTION_RULE revenue_term
OPTIONS (
target_name = 'total_revenue',
target_type = 'measure',
instructions = 'When the user says "revenue" or "sales", use total_revenue (net of discounts), not gross order amount.'
);

-- Prefer one relationship when several connect the same concepts
ALTER KNOWLEDGEBASE finance_kb ADD SELECTION_RULE customer_of_order
OPTIONS (
target_name = 'placed_by',
target_type = 'relationship',
instructions = 'For "customer of an order", follow placed_by[customer], not billed_to[customer], unless the user asks about billing.'
);
Selection rules choose objects, not joins

In Timbr, relationships are defined in the ontology and traversed by name, so you do not write joins. A selection rule tells the agent which concept, property, measure or relationship to prefer. It should not describe SQL join types such as LEFT JOIN.

Update and drop rules​

UPDATE and DROP work the same for all three rule types. UPDATE is a partial update.

ALTER KNOWLEDGEBASE finance_kb UPDATE INSTRUCTION customer_name_case
OPTIONS (
instructions = 'Compare customer_name using lower() when filtering and when grouping for display.'
);

ALTER KNOWLEDGEBASE finance_kb DROP VALIDATION revenue_non_negative;

Bind a Knowledge Base​

A Knowledge Base has no effect until it is bound to an ontology or to an agent.

Bind to an ontology​

The KB is used for every agent query against that ontology. One KB can be bound to several ontologies, and several KBs can be bound to one ontology.

ALTER ONTOLOGY <ontology_name> ADD KNOWLEDGEBASE <kb_name>;
ALTER ONTOLOGY <ontology_name> DROP KNOWLEDGEBASE <kb_name>;
ALTER ONTOLOGY sales_ontology ADD KNOWLEDGEBASE finance_kb;

Bind to an agent​

The KB is used only by that agent. Use this when different teams or use cases need different knowledge over the same ontology. An agent can have several KBs.

ALTER AGENT <agent_name> ADD KNOWLEDGEBASE <kb_name>;
ALTER AGENT <agent_name> DROP KNOWLEDGEBASE <kb_name>;
ALTER AGENT finance_agent ADD KNOWLEDGEBASE finance_kb;
ALTER AGENT finance_agent ADD KNOWLEDGEBASE sales_kb; -- an agent can have several KBs
ALTER AGENT finance_agent DROP KNOWLEDGEBASE sales_kb; -- finance_kb stays bound
BehaviorDetail
KB does not existADD KNOWLEDGEBASE fails.
Binding already existsADD KNOWLEDGEBASE succeeds without creating a duplicate.
Binding not presentDROP KNOWLEDGEBASE succeeds and does nothing.

Suggestions (propose, then approve)​

Not everyone with useful knowledge should have write access to a governed KB, and agents themselves can spot patterns worth keeping. Suggestions give both a safe path in: the change is proposed, held in a review queue, and only applied once a reviewer accepts it.

Any ADD, UPDATE or DROP statement above becomes a suggestion when you add suggestion = 'true' to its options.

OptionNotes
suggestion'true' holds the change for review instead of applying it.
suggestion_sourceWhere the suggestion came from: llm, user_feedback, ddl or system.
suggestion_rationaleFree text explaining why the change is suggested.

These options only describe the suggestion; they are not stored on the example or rule itself. The normal option rules still apply when the suggestion is created, so an invalid suggestion (for example an EXAMPLE with target_name) is rejected immediately.

-- Suggest a new example
ALTER KNOWLEDGEBASE finance_kb ADD EXAMPLE refunds_by_month
OPTIONS (
question = 'Show total refunds by month',
validate_sql = true,
instructions = 'Only include settled refunds.',
suggestion = 'true',
suggestion_source = 'user_feedback',
suggestion_rationale = 'Asked repeatedly by the finance team with no approved example.'
)
AS
SELECT DATE_TRUNC('month', refund_date) AS month,
SUM(refund_amount) AS refunds
FROM dtimbr.refund
WHERE refund_status = 'settled'
GROUP BY 1
ORDER BY 1;

-- Suggest a partial update to a rule
ALTER KNOWLEDGEBASE finance_kb UPDATE INSTRUCTION revenue_needs_timeframe
OPTIONS (
instructions = 'Always aggregate revenue over an explicit period. Default to fiscal quarters.',
suggestion = 'true',
suggestion_source = 'user_feedback'
);

-- Suggest removing a rule
ALTER KNOWLEDGEBASE finance_kb DROP VALIDATION account_number_format
OPTIONS (suggestion = 'true');

Suggestions are also created automatically: when users give feedback on agent answers, Timbr can turn that feedback into suggested examples and rules for the bound Knowledge Bases.

Review a suggestion​

A reviewer accepts or rejects a pending suggestion by its id (see timbr.sys_knowledgebase_suggestions):

ALTER KNOWLEDGEBASE SUGGESTION <suggestion_id> SET status = 'accepted' | 'rejected' [, reason = '<text>'];
ALTER KNOWLEDGEBASE SUGGESTION 42 SET status = 'accepted';
ALTER KNOWLEDGEBASE SUGGESTION 43 SET status = 'rejected', reason = 'Wrong target concept';
DecisionBehavior
AcceptApplies the change exactly as if an editor had run the statement, with the same validation. If validation fails, the statement returns an error, nothing is changed, and the suggestion stays pending.
RejectRecords the decision and optional reason. The KB is not changed.
Already decidedAccepting or rejecting a suggestion that is no longer pending returns a no such pending suggestion error.

Only status ('accepted' or 'rejected') and reason can be set. Every decision is kept in timbr.sys_knowledgebase_suggestions_history for audit.

tip

In the Timbr Platform, suggestions appear as recommendations on the Knowledge Base page, where they can be reviewed in bulk.


Show Knowledge Bases​

SHOW KBS;                 -- alias: SHOW KNOWLEDGE BASES
SHOW KB EXAMPLES; -- examples across all Knowledge Bases
SHOW KB RULES; -- instructions, validations and selection rules across all Knowledge Bases

System tables​

Knowledge Base metadata can be queried directly.

timbr.sys_knowledgebase​

ColumnDescription
knowledge_baseKB name
descriptionKB description
ontologiesBound ontologies (comma-separated)
agentsBound agents (comma-separated)
active'true' / 'false'
created_on, changed_on, created_by_user, changed_by_userAudit columns
SELECT knowledge_base, description, ontologies, agents
FROM timbr.sys_knowledgebase;

timbr.sys_knowledgebase_examples​

ColumnDescription
knowledge_baseOwning KB
example_nameExample name
questionThe question or term
queryThe approved SQL; NULL for definition-only examples
validate_sql'true' / 'false'
instructionsGuidance or definition
created_on, changed_on, changed_by_userAudit columns
SELECT example_name, question, query, validate_sql, instructions
FROM timbr.sys_knowledgebase_examples
WHERE knowledge_base = 'finance_kb';

timbr.sys_knowledgebase_rules​

ColumnDescription
knowledge_baseOwning KB
rule_nameRule name
rule_typeINSTRUCTION, VALIDATION or SELECTION_RULE
target_nameThe ontology object the rule is attached to
target_typeconcept, property, measure, relationship, cube or view
instructionsThe guidance text
created_on, changed_on, changed_by_userAudit columns
SELECT rule_name, rule_type, target_name, target_type, instructions
FROM timbr.sys_knowledgebase_rules
WHERE knowledge_base = 'finance_kb';

timbr.sys_agents​

The knowledge_bases column lists the KBs bound to each agent (comma-separated).

SELECT agent_name, knowledge_bases FROM timbr.sys_agents;

timbr.sys_knowledgebase_suggestions​

Pending suggestions waiting for review.

ColumnDescription
suggestion_idId used to accept or reject the suggestion
knowledge_baseTarget KB
operationadd, update or drop
rule_typeEXAMPLE, INSTRUCTION, VALIDATION or SELECTION_RULE
rule_nameName of the example or rule
target_type, target_nameRules only
question, query, validate_sqlExamples only
instructionsGuidance text
sourcellm, user_feedback, ddl or system
rationaleWhy it was suggested
created_on, created_by_userWhen and by whom it was suggested

For update suggestions only the changed columns are filled in. For drop suggestions the detail columns are empty.

-- Review queue for a KB, newest first
SELECT suggestion_id, operation, rule_type, rule_name, source, rationale, created_on
FROM timbr.sys_knowledgebase_suggestions
WHERE knowledge_base = 'finance_kb'
ORDER BY created_on DESC;

timbr.sys_knowledgebase_suggestions_history​

Decided suggestions. Contains the same detail columns as the queue, plus:

ColumnDescription
final_statusapplied, rejected or expired
rendered_ddlThe statement that was applied (empty for rejected suggestions)
decision_noteThe reason given by the reviewer
reviewed_by_userReviewer
archived_onWhen the decision was made
-- Decision history for a KB, newest first
SELECT suggestion_id, operation, rule_type, rule_name, final_status,
reviewed_by_user, decision_note, archived_on
FROM timbr.sys_knowledgebase_suggestions_history
WHERE knowledge_base = 'finance_kb'
ORDER BY archived_on DESC;

End-to-end example​

1. Create

CREATE KNOWLEDGEBASE finance_kb DESCRIPTION 'Finance & sales analytics KB';

2. Teach

ALTER KNOWLEDGEBASE finance_kb ADD EXAMPLE monthly_revenue
OPTIONS (
question = 'Show total revenue by month',
validate_sql = true,
instructions = 'Only include completed orders.'
)
AS
SELECT DATE_TRUNC('month', order_date) AS month,
SUM(measure.total_revenue) AS revenue
FROM dtimbr.`order`
WHERE order_status = 'completed'
GROUP BY 1
ORDER BY 1;

ALTER KNOWLEDGEBASE finance_kb ADD INSTRUCTION completed_orders_default
OPTIONS (
target_name = 'order',
target_type = 'concept',
instructions = 'Unless the user asks otherwise, only include orders where order_status = ''completed''.'
);

ALTER KNOWLEDGEBASE finance_kb ADD SELECTION_RULE default_order_date
OPTIONS (
target_name = 'order_date',
target_type = 'property',
instructions = 'Use order_date for time filters unless another date is named.'
);

3. Bind

ALTER ONTOLOGY sales_ontology ADD KNOWLEDGEBASE finance_kb;

4. Ask

A user asks: "What was our monthly revenue last year?"

  • The monthly_revenue example closely matches the question and supplies the approved pattern.
  • The completed_orders_default instruction applies because the order concept is used.
  • The default_order_date selection rule makes order_date the time filter.

The agent produces governed SQL such as:

SELECT DATE_TRUNC('month', order_date) AS month,
SUM(measure.total_revenue) AS revenue
FROM dtimbr.`order`
WHERE order_status = 'completed'
AND order_date >= DATE_TRUNC('year', CURRENT_DATE) - INTERVAL '1' YEAR
AND order_date < DATE_TRUNC('year', CURRENT_DATE)
GROUP BY 1
ORDER BY 1;

5. Grow

Review the suggestion queue regularly and accept the suggestions that are correct:

SELECT suggestion_id, operation, rule_type, rule_name, source, rationale
FROM timbr.sys_knowledgebase_suggestions
WHERE knowledge_base = 'finance_kb'
ORDER BY created_on DESC;

ALTER KNOWLEDGEBASE SUGGESTION 42 SET status = 'accepted';

Permissions​

Knowledge Bases are a permissioned resource of their own (knowledgebase):

TaskRequires
Create a Knowledge BaseEDIT on knowledgebase
Add, update or drop examples and rules, or drop the Knowledge BaseEDIT on the Knowledge Base
See the Knowledge Base and its items in the system tablesACCESS on the Knowledge Base

A Knowledge Base the user has no ACCESS to is hidden from timbr.sys_knowledgebase and the related tables. Users who shouldn't edit a Knowledge Base directly can propose suggestions for a curator to review.

GRANT EDIT ON `knowledgebase` TO ROLE `curators`;                -- create Knowledge Bases
GRANT EDIT ON `knowledgebase`.`finance_kb` TO ROLE `curators`; -- curate finance_kb
GRANT ACCESS ON `knowledgebase`.`finance_kb` TO USER `dave`; -- see finance_kb

See Knowledge Bases in Permissions & Roles for the full model and more examples.


Options reference​

Itemquestionvalidate_sqlinstructionsAS <sql>target_nametarget_type
EXAMPLERequiredOptional (default false)OptionalOptionalNot allowedNot allowed
INSTRUCTION / VALIDATION / SELECTION_RULENot allowed–RequiredNot allowedRequiredRequired

suggestion, suggestion_source and suggestion_rationale can be added to any ADD, UPDATE or DROP.


Best practices​

  • One example, one pattern. If a question has two valid SQL answers (for example gross vs. net revenue), create two named examples with clearly different questions rather than one ambiguous example.
  • Use real questions. Write the question the way users actually ask it, including their abbreviations and department terms, not the ontology's object names.
  • Define fuzzy terms once. A definition-only example is the simplest way to fix what "active customer", "churned" or "Q4" means for everyone.
  • Validate approved SQL. Set validate_sql = true for examples with SQL, and write it against dtimbr concepts, relationships and measures.
  • Anchor every rule to a real object. Check that target_name exists in the ontology. Guidance that is not attached to an object cannot be applied.
  • Keep rules short and specific. One rule should state one convention. Split long, multi-topic instructions into several rules.
  • Scope KBs by audience. Create separate Knowledge Bases per domain, team or region when their rules would conflict, and bind each to the right ontology or agent.
  • Route changes through suggestions. Keep write access narrow, and let analysts and agents propose changes that a reviewer approves.
  • Prefer UPDATE over drop-and-recreate. It keeps untouched fields and history intact.
  • Escape single quotes inside option values by doubling them: 'customer''s region', lpad(value, 9, ''0'').