Notebooks
Create reusable, parameterized prompts organized in structured notebooks for consistent, repeatable analysis workflows.
Production Ready - Full notebook system with AI assistant, scheduling, templates, and collaborative features
Overview
QRY's Notebooks feature is a Jupyter-like environment for AI prompts. Instead of managing prompts in scattered conversations, organize your analysis workflows into structured, documented, and reusable notebooks that you can share with your team.
Notebooks combine five types of cells:
- Markdown cells for documentation
- Prompt cells for parameterized AI queries
- Python cells for direct code execution
- SQL cells for direct database queries
- Result cells for captured outputs
Think of Notebooks as a way to:
- Save and organize your best prompts
- Create parameterized, reusable analysis workflows
- Document your analytical thinking
- Share proven notebooks with colleagues via workspaces
- Schedule recurring analysis tasks with automatic execution
How It Works
Notebook Structure
A notebook consists of five types of cells:
Markdown Cells - Document your analysis with rich text
# Motor Failure Analysis
This notebook analyzes motor temperature patterns to identify potential failures
before they occur. Run this weekly on Monday mornings.
## Methodology
- Temperature threshold: 35°C
- Analysis period: Last 7 days
- Focus: Motors with anomalous patterns
Prompt Cells - Executable, parameterized AI prompts
Analyze temperature anomalies for {{vehicle}} on {{date}}
where temperatures exceed {{threshold}}°C
Python Cells - Direct Python code execution (no AI tokens consumed)
import pandas as pd
import matplotlib.pyplot as plt
# Access data from previous SQL cells
df = sql['sql_1']
df.groupby('region')['revenue'].sum().plot(kind='bar')
plt.title('Revenue by Region')
SQL Cells - Direct database queries (no AI tokens consumed)
SELECT region, SUM(revenue) as total_revenue
FROM sales
WHERE date >= '2025-01-01'
GROUP BY region
ORDER BY total_revenue DESC
Result Cells - Captured outputs (auto-generated after execution)
- Charts and visualizations
- Data tables
- Text insights
- Generated files
Notebook IDE
QRY's notebook editor provides a professional IDE experience with features inspired by VS Code and JupyterLab. Work efficiently with multiple notebooks, keyboard shortcuts, and powerful navigation tools.
IDE Layout
The notebook editor uses a three-panel layout:
┌─────────────────────────────────────────────────────────────┐
│ Tab Bar (open notebooks, drag to reorder) │
├──────────┬────────────────────────────────┬─────────────────┤
│ │ │ │
│ File │ Notebook Content │ Right Rail │
│ Explorer │ (cells, outputs) │ (panel icons) │
│ │ │ │
│ │ ├─────────────────┤
│ │ │ Panel Content │
│ │ │ (contextual) │
└──────────┴────────────────────────────────┴─────────────────┘
Components:
- Tab Bar: Open multiple notebooks simultaneously, drag tabs to reorder, hover for preview
- File Explorer: Browse and open notebooks from your workspace
- Editor Area: Main content area with cells and outputs
- Right Rail: Quick access icons for panels (Outline, Variables, Dependencies, Settings)
- Panel Area: Contextual panels that slide in from the right
Keyboard Shortcuts
Master these shortcuts to work efficiently:
Navigation
| Shortcut | Action |
|---|---|
↑ / ↓ | Navigate between cells |
Cmd+P | Open Command Palette |
Cmd+F | Find in notebook |
Cmd+G | Find next match |
Cmd+Shift+G | Find previous match |
Cell Operations
| Shortcut | Action |
|---|---|
Cmd+Enter | Run current cell |
Shift+Enter | Run cell and move to next |
Cmd+Shift+Enter | Run all cells |
Escape | Exit edit mode / Close dialogs |
View Controls
| Shortcut | Action |
|---|---|
Cmd+B | Toggle sidebar |
Cmd+\ | Toggle split view |
Cmd+Shift+O | Toggle Outline panel |
Cmd+Shift+V | Toggle Variables panel |
Cmd+Shift+D | Toggle Dependencies panel |
Cmd+, | Toggle Settings panel |
Cell Management
| Shortcut | Action |
|---|---|
Cmd+Shift+K | Delete current cell |
Alt+↑ | Move cell up |
Alt+↓ | Move cell down |
Command Palette
Press Cmd+P to open the Command Palette - a VS Code-style quick action menu that provides instant access to all notebook operations.
Features:
- Fuzzy Search: Type any part of a command name to find it
- Recent Commands: Your most-used commands appear at the top
- Categorized Actions: Commands grouped by Navigation, Cells, Run, View, and File
- Keyboard Navigation: Use arrow keys to navigate, Enter to execute
Available Commands:
- Navigation: Go to first/last/specific cell, jump by cell number
- Cells: Add SQL/Python/Markdown/Prompt cells, delete, duplicate, move
- Run: Run current cell, run all, run above/below
- View: Toggle panels, collapse/expand cells
- File: Save notebook, open search
Example Usage:
- Press
Cmd+P - Type "add sql" to filter
- Press Enter to add a new SQL cell
Find & Replace
Press Cmd+F to open the search bar for finding content across all cells.
Features:
- Live Search: Results highlight as you type
- Match Counter: Shows "X of Y matches" with current position
- Navigate Matches: Use
Cmd+G(next) andCmd+Shift+G(previous) - Cell Navigation: Automatically scrolls to and highlights matching cells
- Cross-Cell Search: Searches across all cell types (code, markdown, prompts)
Search Bar Controls:
┌─────────────────────────────────────────────────┐
│ 🔍 [search term________] 3 of 12 ▲ ▼ ✕ │
└─────────────────────────────────────────────────┘
Tab Management
Work with multiple notebooks simultaneously using the tab system.
Features:
- Multiple Notebooks: Open several notebooks in tabs
- Drag & Drop Reorder: Drag tabs to rearrange their order
- Tab Preview: Hover over a tab to see notebook details (cell count, last modified)
- Dirty Indicator: Orange dot shows unsaved changes
- Quick Close: Middle-click to close, or use the X button
- Tab Menu: Right section offers "Close", "Close Others", "Close All"
Visual Indicators:
- Active Tab: White background with blue bottom border
- Inactive Tab: Gray background
- Unsaved Changes: Orange dot next to title
- Drag Handle: Appears on hover for reordering
Cell Collapsing
Collapse cells to focus on specific parts of your notebook.
How to Collapse:
- Click the collapse indicator on the left edge of any cell
- Use Command Palette: "Collapse Current Cell"
Collapsed Cell Preview: Shows a compact summary with:
- Cell type icon
- First line of content (truncated)
- Click to expand
Bulk Actions:
- Collapse All: Hide all cell content for a high-level overview
- Expand All: Show all cell content
Use Cases:
- Focus on specific analysis sections
- Navigate long notebooks quickly
- Hide completed cells while working on new ones
Right Panel Features
Access powerful tools via the right navigation rail.
Outline Panel (Cmd+Shift+O)
Navigate your notebook structure at a glance.
Shows:
- All cells listed with type icons
- Markdown headers extracted as sections
- Cell numbers for quick reference
- Active cell highlighted
Actions:
- Click any item to scroll to that cell
- See notebook structure without scrolling
Variables Panel (Cmd+Shift+V)
Inspect variables and data from executed cells.
Displays:
- SQL cell results with row counts
- Python variables with types and values
- DataFrame previews with shape info
Information Shown:
📊 sql_1 DataFrame (1,000 rows × 5 cols)
📊 sales_data DataFrame (500 rows × 8 cols)
🔢 total_revenue float: 1,234,567.89
📝 report_title str: "Q4 Sales Report"
Dependencies Panel (Cmd+Shift+D)
Visualize data flow between cells.
Shows:
- Which SQL cells produce data
- Which Python cells consume that data
- Connection lines showing dependencies
Dependency Detection:
- SQL cells that create
sql_NDataFrames - Python cells that reference
sql['sql_1']or similar - Clear visualization of data lineage within the notebook
Use Cases:
- Understand complex notebook workflows
- Debug data pipeline issues
- Document cell relationships
Settings Panel (Cmd+,)
Configure notebook-level settings.
Options:
- Datasource selection
- Catalog/Schema configuration
- Prompt chaining settings
- Model selection
- Execution options
Split View
View two parts of your notebook simultaneously with Cmd+\.
Features:
- Horizontal Split: Top and bottom panes
- Resizable Divider: Drag to adjust pane sizes
- Independent Scrolling: Each pane scrolls independently
- Persistent Ratio: Split position remembered across sessions
Use Cases:
- Reference documentation while coding
- Compare cells in different sections
- View results while editing prompts
- Keep SQL visible while writing Python
Controls:
- Toggle: Click button or press
Cmd+\ - Resize: Drag the horizontal divider
- Close: Click minimize button or press
Cmd+\again
Active Cell Tracking
Always know which cell you're working on.
Visual Indicators:
- Left Border: Blue highlight on active cell
- Background: Subtle highlight color
- Outline Panel: Synced highlighting
Auto-Scroll:
- Clicking in Outline panel scrolls to cell
- Keyboard navigation keeps active cell visible
- Search results auto-scroll into view
Datasource Configuration
Configure your database connection in the right panel settings:
- Select datasource
- Choose specific tables (optional)
- Include profiling data
- Configure schema access
This configuration applies to the entire notebook, making it available to all prompt cells.
Variables System
Make your prompts flexible with variables:
Define Variables:
Analyze sales for {{region}} in {{quarter}} {{year}}
where revenue exceeds {{min_revenue}}
Variable Types:
- Text: Free-form input (product names, regions)
- Number: Integer or decimal values (thresholds, IDs)
- Date: Date picker for time ranges
- Table: Dropdown of available tables
- Boolean: Yes/no toggles
- Enum: Predefined options (Q1, Q2, Q3, Q4)
System Variables:
Use built-in date variables that resolve automatically:
| Variable | Example |
|---|---|
{{today}} | 2025-11-05 |
{{yesterday}} | 2025-11-04 |
{{this_week_start}} | 2025-11-04 |
{{this_week_end}} | 2025-11-10 |
{{this_month_start}} | 2025-11-01 |
{{this_month_end}} | 2025-11-30 |
{{last_month_start}} | 2025-10-01 |
{{last_month_end}} | 2025-10-31 |
Example:
Show me sales data from {{last_month_start}} to {{last_month_end}}
AI Generate
The AI Generate feature creates complete notebooks for you. Instead of building from scratch, describe what you need and let AI construct the entire workflow.
How It Works
- Create a new notebook
- Configure your datasource in the right panel
- Click "AI Generate"
- Describe what you want to analyze
Example prompts:
"Create a weekly sales analysis notebook that tracks revenue, top products,
and regional performance with comparisons to previous weeks"
"Build a customer churn analysis notebook that identifies at-risk customers
and suggests retention strategies"
"Generate a data quality monitoring notebook for the customers table that
checks for missing values, duplicates, and data anomalies"
What AI Generate Creates
Based on your prompt and datasource, the AI automatically generates:
- Markdown cells with documentation and context
- Prompt cells with parameterized analysis queries
- Variable definitions extracted from your requirements
- Structured workflow organized logically
Example Output:
Given: "Weekly sales analysis for regional performance"
AI Creates:
# Cell 1 (Markdown)
# Weekly Sales Analysis
This notebook analyzes sales performance across regions...
# Cell 2 (Prompt)
Show total sales for {{region}} from {{week_start}} to {{week_end}}
Compare with previous week and calculate growth percentage.
Variables:
• region: "All Regions" (text)
• week_start: {{this_week_start}} (date)
• week_end: {{this_week_end}} (date)
# Cell 3 (Prompt)
Identify top 10 products by revenue in {{region}} for the week...
Refining Generated Notebooks
After AI generation, you can:
- Edit any cell
- Add more markdown documentation
- Adjust variable definitions
- Add or remove cells
- Modify prompts for your needs
The AI gives you a solid starting point that you can customize.
Python Cells
Python cells execute code directly without consuming AI tokens. They run in a persistent runtime session, allowing you to maintain state across cells.
Features
- Persistent Variables: Variables defined in one cell are available in subsequent cells
- Visualization Support: Matplotlib, Seaborn, and Plotly charts render automatically
- Package Installation: Install packages on-the-fly with
%pip install - File Generation: Create and download CSV, JSON, and other files
- AI Error Diagnosis: Get AI-powered suggestions when code fails
Basic Usage
# Import libraries
import pandas as pd
import matplotlib.pyplot as plt
# Create a DataFrame
df = pd.DataFrame({
'month': ['Jan', 'Feb', 'Mar', 'Apr'],
'sales': [100, 150, 200, 175]
})
# Create a visualization
df.plot(x='month', y='sales', kind='bar')
plt.title('Monthly Sales')
plt.show()
Installing Packages
Install additional packages directly in your notebook:
# Using magic command (recommended)
%pip install scikit-learn xgboost
# Or shell command
!pip install requests
Packages are available immediately after installation—no restart required.
Visualization Output
Python cells automatically capture and display:
| Library | Output Type | Display |
|---|---|---|
| Matplotlib | Static images | Inline PNG |
| Seaborn | Static images | Inline PNG |
| Plotly | Interactive charts | HTML preview with expand button |
AI-Assisted Error Diagnosis
When Python code fails, a "Fix with AI" button appears. Click it to:
- Send your code and error to the AI
- Receive a suggested fix with explanation
- Apply the fix with one click
- Re-run the corrected code
The AI considers your full notebook context, including previous cells and SQL data.
SQL Cells
SQL cells execute queries directly against your configured datasource without consuming AI tokens.
Features
- Direct Execution: Query your database without AI interpretation
- Interactive Results: View results in sortable, filterable tables
- Python Integration: Access SQL results from Python cells via the
sqldictionary - No Token Cost: Direct database queries don't use AI credits
Basic Usage
SELECT
region,
COUNT(*) as customer_count,
SUM(revenue) as total_revenue
FROM customers
WHERE created_at >= '2025-01-01'
GROUP BY region
ORDER BY total_revenue DESC
LIMIT 100
Results display in an interactive table with sorting and pagination.
Datasource Context
SQL cells use the notebook's configured datasource:
- Datasource: Selected in right panel settings
- Catalog/Schema: Optional overrides per notebook
- Permissions: Respects your database access rights
Passing Data Between Cells
One of the most powerful features is passing data from SQL cells to Python cells for further analysis.
Accessing SQL Results in Python
SQL cell results are automatically available in Python cells via the sql dictionary:
# Access by position (first SQL cell)
df = sql['sql_1']
# Access by cell name (if you named your SQL cell "sales_data")
df = sql['sales_data']
# Access by cell UUID
df = sql['550e8400-e29b-41d4-a716-446655440000']
When a Python cell runs, you'll see a summary of available data:
📊 SQL data available: sql['sql_1'] (1,000 rows), sql['sales_data'] (500 rows)
Example Workflow
SQL Cell 1 - Fetch raw data:
SELECT * FROM sales WHERE year = 2025
SQL Cell 2 (named "products") - Fetch reference data:
SELECT * FROM product_catalog
Python Cell - Analyze and visualize:
import pandas as pd
import matplotlib.pyplot as plt
# Get data from SQL cells
sales = sql['sql_1']
products = sql['products']
# Join and analyze
merged = sales.merge(products, on='product_id')
by_category = merged.groupby('category')['revenue'].sum()
# Visualize
by_category.plot(kind='pie', autopct='%1.1f%%')
plt.title('Revenue by Product Category')
plt.show()
The qry Module
Python cells have access to the qry module, which provides direct interaction with your datasource and email capabilities — all without leaving the notebook.
sql(query, **params) — Run a SELECT query
Returns a pandas DataFrame with the query results.
from qry import sql
# Simple query
df = sql("SELECT * FROM customers WHERE region = 'EU'")
# Parameterized query (recommended)
df = sql(
"SELECT * FROM orders WHERE status = :status AND total > :min_total",
status="completed",
min_total=1000
)
print(f"{len(df)} orders found")
df.head()
execute(statement) — Run DDL/DML statements
Executes statements that don't return data (CREATE, ALTER, DROP, GRANT, etc.).
from qry import execute
execute("CREATE TABLE IF NOT EXISTS reports.monthly_summary (month DATE, total DECIMAL)")
execute("GRANT SELECT ON reports.monthly_summary TO analyst_role")
insert(table, df) — Insert a DataFrame into a table
Writes a pandas DataFrame directly to a database table.
from qry import sql, insert
# Read, transform, write back
raw = sql("SELECT * FROM raw_events WHERE event_date = CURRENT_DATE")
summary = raw.groupby('event_type').agg(count=('id', 'size')).reset_index()
insert("analytics.daily_event_counts", summary)
send_email(to, subject, body, attachments=None) — Send an email
Sends HTML emails with optional file attachments. Useful for alerts, reports, and scheduled notifications.
from qry import send_email
# Simple notification
send_email(
to="team@company.com",
subject="Daily report ready",
body="<p>The daily report has been generated.</p>"
)
# Conditional alert based on data
from qry import sql, send_email
anomalies = sql("SELECT * FROM metrics WHERE value > threshold")
if len(anomalies) > 0:
send_email(
to=["alerts@company.com", "manager@company.com"],
subject=f"⚠️ {len(anomalies)} anomalies detected",
body=anomalies.to_html(index=False),
attachments=[{
"filename": "anomalies.csv",
"data": anomalies.to_csv(index=False)
}]
)
send_email requires SMTP to be configured by your administrator in System Settings.
Combining cell results
SQL cell results are available in Python cells via the sql dictionary, keyed by cell name:
# Access results from SQL cells
sales = sql['sql_1'] # First SQL cell
products = sql['products'] # SQL cell named "products"
# Inspect what's available
print(sales.columns.tolist())
print(f"Rows: {len(sales)}, Columns: {sales.shape[1]}")
# Use pandas operations on the results
summary = sales.describe()
top_10 = sales.nlargest(10, 'revenue')
Runtime Sessions
Python cells run in persistent runtime sessions that maintain state across executions.
How It Works
When you run your first Python cell, QRY automatically:
- Creates a dedicated runtime environment for you
- Pre-installs common data science packages (pandas, numpy, matplotlib, etc.)
- Maintains your variables and imports across cells
- Cleans up automatically after inactivity
Session Lifecycle
| Event | What Happens |
|---|---|
| First Python cell run | Runtime starts (may take a few seconds) |
| Subsequent cells | Execute instantly in existing session |
| 30 min inactivity | Runtime automatically stops |
| Return after idle | New runtime starts, previous state cleared |
Pre-installed Packages
Runtimes come with common packages pre-installed:
- Data: pandas, numpy, pyarrow
- Visualization: matplotlib, seaborn, plotly
- Analysis: scipy, scikit-learn
- Utilities: requests, python-dateutil
Install additional packages as needed with %pip install.
Best Practices
Structure your notebooks:
Cell 1 (Python): Imports and setup
Cell 2 (SQL): Fetch data
Cell 3 (Python): Data processing
Cell 4 (Python): Analysis
Cell 5 (Python): Visualization
Keep imports at the top:
# First Python cell - run once
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
Handle long-running operations:
- Large data processing may timeout after 5 minutes
- For heavy workloads, break into smaller cells
- Use sampling for initial exploration
Scheduled Execution
Run notebooks automatically on a schedule - perfect for recurring reports and monitoring.
One-Time Execution
Schedule a notebook to run once:
Name: Q4 Financial Review
Date: 2025-12-31
Time: 09:00 AM
Timezone: US/Eastern
Recurring Execution
Set up repeating schedules:
Daily Reports:
Every day at 8:00 AM
Use {{today}} for the report date
Weekly Analysis:
Every Monday at 9:00 AM
Use {{this_week_start}} to {{this_week_end}}
Monthly Summaries:
First day of each month at 8:00 AM
Use {{last_month_start}} to {{last_month_end}}
Output Options
Save to Notebook - Results appear as a new result cell
Email Report - Send results to specified recipients:
Recipients: team@company.com, manager@company.com
Subject: Weekly Sales Report - {{today}}
Auto-Disable Protection
Notebooks automatically disable after 3 consecutive failures to prevent runaway costs and alert you to issues.
Collaboration
Workspace Sharing
Notebooks automatically share based on workspace membership:
Personal Notebooks - Private to you
- Created in your personal workspace
- Only you can access and edit
- Not visible to other users
Team Notebooks - Automatically shared
- Created in a workspace
- All workspace members can access
- Permissions inherit from workspace settings
- Changes visible to all team members
To share a notebook with your team, simply create it within a workspace or move it to one. All workspace members will have access based on their workspace permissions.
Activity Tracking
Monitor notebook usage:
- Execution history with timestamps
- Variable values used in each run
- Results from previous executions
- Schedule status and logs
Common Use Cases
Weekly Business Reviews
# Markdown Cell
# Weekly Sales Review
Weekly sales analysis for leadership team.
Run every Monday morning before the weekly meeting.
Datasource: Sales DB (configured in right panel)
Tables: orders, customers, products
# Prompt Cell
Analyze sales performance for {{this_week_start}} to {{this_week_end}}:
- Total revenue vs previous week
- Top 10 products by revenue
- Revenue by region
- New customer count
Create visualizations for each metric.
Variables:
• this_week_start: {{this_week_start}} (system variable)
• this_week_end: {{this_week_end}} (system variable)
Schedule:
- Every Monday at 8:00 AM
- Email: leadership@company.com
Data Quality Monitoring
# Markdown Cell
# Daily Data Quality Checks
Automated monitoring for customer database quality issues.
Datasource: Customer DB (configured in right panel)
# Prompt Cell
Check the customers table for data quality issues:
- Records with missing email addresses
- Duplicate phone numbers
- Invalid date formats
- Outliers in age field
Flag any records with issues for review.
Schedule:
- Every day at 2:00 AM
- Output: Save to notebook
- Alert if issues found: data-team@company.com
Customer Health Scoring
# Markdown Cell
# Monthly Customer Health Assessment
Calculate health scores and identify at-risk customers.
Datasource: Customer Analytics DB (configured in right panel)
# Prompt Cell
Calculate customer health scores for {{month}}:
For each customer:
- Purchase frequency (last 90 days)
- Average order value
- Support ticket count
- Last interaction date
Categorize as: Healthy, At-Risk, Critical
Identify top 20 at-risk customers.
Variables:
• month: (text input, e.g., "November 2025")
Schedule:
- First of each month at 9:00 AM
Ad-Hoc Analysis Template
# Markdown Cell
# Time-Series Analysis Template
Reusable template for analyzing trends in any metric over time.
Datasource: Configure as needed (right panel)
# Prompt Cell
Analyze {{table_name}} for time period {{start_date}} to {{end_date}}:
1. Overall trends in {{metric_column}}
2. Peak and low periods
3. Day-of-week patterns
4. Month-over-month comparison
Create visualizations for each pattern.
Variables:
• table_name: (text input)
• start_date: (date picker)
• end_date: (date picker)
• metric_column: (text input)
Best Practices
Organize Your Notebooks
Use Markdown Cells for Documentation:
- Purpose of the notebook
- When to run it
- How to interpret results
- Datasource information
- Contact for questions
Name Notebooks Clearly:
- ✅ "Weekly Sales by Region - Leadership Report"
- ✅ "Customer Churn Analysis - Data Science"
- ❌ "Analysis 1"
- ❌ "Notebook Tuesday"
Version Your Workflows:
- Save snapshot before major changes
- Document what changed and why
- Keep old versions for reference
Write Effective Prompts
Be Specific:
❌ Analyze sales
✅ Calculate total sales, average order value, and customer count
for {{region}} in {{month}}, broken down by product category
Request Exact Outputs:
✅ Create a bar chart showing top 10 products
✅ Export results as a CSV file
✅ Highlight any values that exceed threshold
Structure Complex Prompts:
Analyze customer behavior for {{segment}}:
1. Purchase Patterns
- Frequency of purchases
- Average order value
- Preferred products
2. Engagement Metrics
- Website visits
- Email opens
- Support interactions
3. Recommendations
- Retention strategies
- Upsell opportunities
Use Variables Wisely
Parameterize Dates:
✅ {{start_date}} to {{end_date}}
✅ {{quarter}} {{year}}
✅ {{this_month_start}}
Define Clear Variable Names:
✅ {{revenue_threshold}}
✅ {{customer_segment}}
✅ {{region_name}}
❌ {{x}}
❌ {{temp}}
❌ {{thing}}
Set Sensible Defaults:
region: "All Regions"
threshold: 1000
include_inactive: false
Leverage AI Generate
Starting a New Notebook:
- Use AI Generate to create the initial structure
- Describe your analysis goal clearly
- Let AI handle variable extraction and workflow organization
After Generation:
- Review and refine the generated cells
- Adjust variable defaults to match your needs
- Add additional markdown documentation
- Test with sample data before scheduling
When Sharing:
- Ensure markdown cells explain the notebook's purpose
- Document expected variable values
- Include notes about schedule and outputs
- Add contact information for questions
Examples
Sales Forecasting Notebook
# Markdown Cell
# 📊 Monthly Sales Forecast
Generates 30-day sales forecast using historical data and seasonal patterns.
Run on the last day of each month.
**Datasource:** Sales Analytics (configured in right panel)
**Tables:** daily_sales, products, regions
# Prompt Cell
Analyze historical sales data from {{last_month_start}} to {{last_month_end}}
and create a 30-day forecast for {{next_month}}.
Include:
1. Time series chart with historical and forecast
2. Confidence intervals (80% and 95%)
3. Key drivers and assumptions
4. Products with highest growth potential
5. Regional breakdown
Variables:
• last_month_start: {{last_month_start}} (system variable)
• last_month_end: {{last_month_end}} (system variable)
• next_month: "December 2025" (text input)
• confidence_level: 95 (number)
Schedule:
- Last day of each month at 4:00 PM
- Email: forecasting-team@company.com
Anomaly Detection Notebook
# Markdown Cell
# 🔍 Transaction Anomaly Detector
Identifies unusual transaction patterns for fraud detection.
Runs daily to catch suspicious activity early.
**Datasource:** Transactions DB (configured in right panel)
**Tables:** transactions, customers, merchants
# Prompt Cell
Detect anomalous transactions for {{date}}:
Criteria:
- Transactions > {{amount_threshold}}
- Multiple transactions from same customer within {{time_window}} hours
- Transactions from unusual locations
- First-time high-value purchases
For each anomaly:
- Transaction details
- Customer history
- Risk score (1-10)
- Recommended action
Variables:
• date: {{yesterday}} (system variable)
• amount_threshold: 10000 (number)
• time_window: 1 (number)
Schedule:
- Every day at 1:00 AM
- Output: Save to notebook
- If anomalies found: Email fraud-team@company.com
Troubleshooting
Variables Not Resolving
Issue: Variables show as {{variable}} in results
Solutions:
- Ensure variable is defined in the prompt cell
- Check variable type matches the value
- For dates, use proper format (YYYY-MM-DD)
- System variables require scheduling context
Schedule Not Executing
Issue: Scheduled notebook didn't run
Check:
- Task is enabled (not auto-disabled)
- Execution time hasn't passed
- You still have access to datasources
- No consecutive failures (max 3)
Verify:
View execution history in notebook settings
Check task status: Enabled/Disabled
Review error logs if failed
Permission Errors
Issue: "Access denied" when executing
Solutions:
- Verify datasource permissions
- Check workspace membership
- Ensure tables still exist
- Confirm database is online
AI Assistant Not Responding
Issue: AI enhancement features not working
Check:
- AI models are configured
- You have sufficient credits
- Network connectivity
- Try refreshing the page
Python Cell Issues
Issue: Runtime won't start
Solutions:
- Wait a moment—first run may take 10-15 seconds
- Check your network connection
- Try refreshing the page and running again
Issue: pip install fails
Solutions:
- Check package name spelling
- Verify the package exists on PyPI
- Try installing a specific version:
%pip install pandas==2.0.0
Issue: Import fails after pip install
Solutions:
- Ensure you're using the latest QRY version
- Try running the import in a new cell
- Restart runtime via the Runtime menu
Issue: Visualization not displaying
Solutions:
- Ensure
plt.show()is called for Matplotlib - For Plotly, results appear in an expandable modal
- Check for errors in the cell output
SQL Cell Issues
Issue: Query returns no results
Check:
- Verify the table name and schema
- Check your WHERE clause filters
- Confirm you have access to the datasource
Issue: SQL results not available in Python
Solutions:
- Ensure SQL cell ran successfully before Python cell
- Access via position:
sql['sql_1']for first SQL cell - Check for typos in the cell name
Issue: Timeout on large queries
Solutions:
- Add LIMIT clause to reduce result size
- Use more specific WHERE conditions
- Break into multiple smaller queries
Advanced Features
Chained Prompts
Create intelligent, sequential workflows where each prompt builds on previous results.
What are Chained Prompts?
By default, each prompt cell in a notebook executes independently. When you enable Chained Prompts, each cell automatically receives the context and results from all previous cells, allowing you to build sophisticated multi-step analysis workflows.
How It Works:
Cell 1: "Analyze Q1 sales performance"
↓ Executes independently
Result: "Q1 had $500k in sales, 25% growth..."
Cell 2: "Compare with Q2 and identify trends"
↓ Executes WITH context from Cell 1
↓ AI sees: "Previous analysis showed Q1 had $500k..."
Result: "Q2 reached $625k, continuing the growth trend..."
Cell 3: "Predict Q3 performance based on the trends"
↓ Executes WITH context from Cell 1 and Cell 2
Result: "Based on 25% growth in Q1 and Q2 patterns..."
When to Use Chained Prompts:
✅ Perfect for:
- Multi-step analysis requiring context from previous steps
- Progressive refinement of insights
- Building complex narratives from data
- Exploratory analysis where each step informs the next
- Comparative analysis across time periods or segments
❌ Not needed for:
- Independent, parallel analyses
- Simple one-off queries
- When you want to test different approaches simultaneously
Enabling Chained Prompts:
- Open your notebook
- Click the Settings button (right panel)
- Find the Prompt Chaining section
- Toggle Enable Chained Prompts to ON
- Optionally configure Stop on Error
Configuration Options:
Stop on Error (recommended: ON)
- Enabled: If any cell fails, execution stops immediately
- Disabled: Continues to next cells even if one fails
- Use case: Enable for dependent workflows, disable for independent checks
Multi-Step Analysis Example
Scenario: Quarterly Business Review
# Markdown Cell
# 📊 Quarterly Performance Analysis
Comprehensive analysis building from basic metrics to strategic insights.
Chained Prompts: ENABLED
Stop on Error: ENABLED
# Cell 1 (Prompt)
Analyze Q3 2025 sales performance:
- Total revenue
- Customer acquisition
- Average order value
- Month-by-month breakdown
# Cell 2 (Prompt)
Based on the Q3 analysis, identify the top 3 trends and their potential causes.
For each trend, explain what in the data supports this conclusion.
# Cell 3 (Prompt)
Given the trends identified, what are the key risks and opportunities for Q4?
Provide specific, actionable recommendations for leadership.
# Cell 4 (Prompt)
Create a concise executive summary highlighting:
- Q3 performance vs targets
- Critical trends discovered
- Top 3 recommendations for Q4
Format for a leadership email.
Why This Works:
- Cell 2 references specific numbers from Cell 1
- Cell 3 builds on trends identified in Cell 2
- Cell 4 synthesizes everything into actionable insights
- Each step naturally flows from the previous one
Progressive Data Exploration
Scenario: Customer Churn Investigation
# Markdown Cell
# 🔍 Customer Churn Deep Dive
Investigative workflow for understanding churn patterns.
Chained Prompts: ENABLED
# Cell 1 (Prompt)
Identify customers who churned in {{month}}.
Calculate churn rate and show demographic breakdown.
# Cell 2 (Prompt)
For the churned customers identified above, analyze their behavior
in the 90 days before churning:
- Purchase frequency
- Support tickets
- Feature usage
- Engagement metrics
# Cell 3 (Prompt)
Based on the behavioral patterns found, identify early warning signs
that predict churn. Create a risk scoring framework.
# Cell 4 (Prompt)
Apply the risk framework to current active customers.
List top 20 at-risk customers with specific retention recommendations.
Best Practices for Chained Prompts
Structure Your Workflow:
- Start Broad - Begin with overview/summary analysis
- Go Deeper - Dive into specifics identified in step 1
- Synthesize - Connect findings across steps
- Actionable Output - End with recommendations or next steps
Optimize Context Usage:
- Keep early cells focused and concise
- Each cell should add new insights, not repeat
- Use markdown cells to document the logical flow
- Test the flow manually before scheduling
Prompt Writing Tips:
✅ Reference Previous Results:
"Based on the trends identified above..."
"For the top customers found in the previous analysis..."
"Given the risk factors discovered..."
✅ Build Progressive Complexity:
Cell 1: What happened? (descriptive)
Cell 2: Why did it happen? (diagnostic)
Cell 3: What will happen? (predictive)
Cell 4: What should we do? (prescriptive)
✅ Be Explicit About Connections:
"Using the customer segments from the previous analysis..."
"Focusing on the anomalies detected above..."
Cost and Token Considerations
Important: Chained prompts increase token usage because each cell includes context from previous cells.
Typical Token Growth:
Without chaining (5 cells):
Cell 1: 1,000 tokens
Cell 2: 1,000 tokens
Cell 3: 1,000 tokens
Cell 4: 1,000 tokens
Cell 5: 1,000 tokens
Total: 5,000 tokens
With chaining (5 cells):
Cell 1: 1,000 tokens
Cell 2: 1,500 tokens (+ 500 context)
Cell 3: 2,000 tokens (+ 1,000 context)
Cell 4: 2,500 tokens (+ 1,500 context)
Cell 5: 3,000 tokens (+ 2,000 context)
Total: 10,000 tokens (2x cost)
Cost Optimization Tips:
- Limit workflows to 5-7 cells when possible
- Keep early cell outputs concise
- Use chaining only when context is truly needed
- Consider splitting very long workflows into separate notebooks
- Monitor execution costs in scheduled runs
Error Handling in Chained Workflows
With Stop on Error = ON (Recommended):
Cell 1: Success ✓
Cell 2: Success ✓
Cell 3: Error ❌ (table not found)
Cell 4: Skipped ⊘
Cell 5: Skipped ⊘
- Safe for dependent workflows
- Prevents cascading errors
- Easier to debug
With Stop on Error = OFF:
Cell 1: Success ✓
Cell 2: Success ✓
Cell 3: Error ❌ (table not found)
Cell 4: Success ✓ (uses context from Cell 1-2 only)
Cell 5: Success ✓
- Useful for monitoring multiple independent checks
- One failure doesn't block others
- Review all results after execution
When Chaining vs Independent Cells
Use Chaining When:
- Each step depends on previous results
- Building a narrative or story from data
- Progressive refinement of analysis
- Multi-step decision making
- Creating cohesive reports
Use Independent Cells When:
- Running parallel analyses
- Testing different approaches
- Monitoring unrelated metrics
- Each cell answers a separate question
- Want to retry individual cells without re-running everything
Version Control
Track changes to your notebooks:
- View edit history
- Compare versions
- Restore previous versions
- See who made changes
Export & Import
QRY notebooks support multiple export and import formats for interoperability and backup.
Supported Formats
| Format | Extension | Import | Export | Best For |
|---|---|---|---|---|
| QRY Native | .qrynb | ✅ | ✅ | Full fidelity backup, sharing between QRY instances |
| Jupyter Notebook | .ipynb | ✅ | ✅ | Jupyter Lab/Notebook interoperability |
QRY Native Format (.qrynb)
The .qrynb format preserves all QRY features with full fidelity:
- All cell types: markdown, prompt, python, sql, result
- Prompt cell configuration: variables, model, temperature
- Notebook settings: datasource, catalog, schema, user context
- Cell execution outputs (optional)
- Chaining configuration and tags
Best for:
- Backup notebooks between QRY deployments
- Share complete workflows with colleagues
- Version control (JSON-based, git-friendly)
- Template distribution
Jupyter Notebook Format (.ipynb)
Export to Jupyter for use in Jupyter Lab/Notebook, or import existing Jupyter notebooks.
When importing from Jupyter:
| Jupyter Cell Type | QRY Cell Type |
|---|---|
markdown | markdown |
code (Python) | python |
When exporting to Jupyter:
| QRY Cell Type | Jupyter Cell Type | Notes |
|---|---|---|
markdown | markdown | Direct mapping |
python | code | Direct mapping with outputs |
sql | code | Converted to %%sql magic command |
prompt | markdown | Prompt shown as markdown with metadata |
result | markdown | Output formatted as markdown |
Limitations when exporting to Jupyter:
- Prompt cells lose LLM integration (exported as documentation)
- Variable system not available in Jupyter
- Datasource context not transferred
- AI error diagnosis not available
Best for:
- Sharing Python/SQL code with non-QRY users
- Using analysis in Jupyter environments
- Code review in GitHub (renders .ipynb)
- Integration with other notebook tools
How to Export/Import
Export:
- Open your notebook
- Click the menu (⋮) in the toolbar
- Select Export (.qrynb) or Export (.ipynb)
- File downloads to your browser
Import:
- Go to the Notebooks page
- Click Import Notebook
- Select a
.qrynbor.ipynbfile - Configure workspace and settings
- Click Import
API Integration
Execute notebooks programmatically:
# Execute notebook
POST /api/notebooks/{notebook_id}/execute
{
"variables": {
"region": "EMEA",
"date": "2025-11-05"
}
}
# Schedule notebook
POST /api/notebooks/{notebook_id}/schedule
{
"cron_expression": "0 9 * * 1",
"timezone": "UTC",
"output_type": "email",
"output_emails": ["team@company.com"]
}
Tips for Success
- Start Simple - Begin with one or two prompts, expand as needed
- Document Liberally - Use markdown cells to explain your thinking
- Test Before Scheduling - Run manually first to verify results
- Use AI Generate - Let AI create the initial structure, then customize
- Share via Workspaces - Create notebooks in team workspaces for collaboration
- Iterate Often - Refine prompts based on results
- Configure Datasource First - Set up database connection before generating cells
- Monitor Schedules - Check execution history regularly
Notebooks work great with Python Execution for custom visualizations, Scheduled Tasks for automated workflows, and Git Folders for version control! For complex multi-step ETL pipelines with dependencies, check out Lakeflow.
Check out the User Guide for detailed walkthroughs and examples.