MySQL Query Task¶
Overview¶
The MySQL Query Task executes SQL queries against your MySQL database. Use it to read data, create records, update information, or perform complex database operations directly from your workflows.
When to use this task:
- Fetch data from custom database tables
- Create records in external systems
- Update database fields programmatically
- Generate reports from database queries
- Sync data between BaseCloud and other systems
- Perform complex joins and aggregations
- Execute stored procedures
Key Features:
- Full SQL support (SELECT, INSERT, UPDATE, DELETE)
- Parameterized queries for security
- Multiple database connection support
- Result parsing and output fields
- Transaction support
- Prepared statements
- Error handling and rollback
[SCREENSHOT NEEDED: MySQL Query task configuration showing connection and query fields]
Quick Start¶
- Add MySQL Query task to workflow
- Select database connection
- Write SQL query
- Add parameters (if using variables)
- Test query
- Save
Simple Example:
Parameters:{{task_15001_email}} Database Connection¶
Setting Up Connection¶
Configure database credentials in BaseCloud Admin:
- Go to Admin → Database Connections
- Add New Connection
- Enter details:
- Host:
localhostordb.example.com - Port:
3306(default MySQL) - Database:
your_database_name - Username:
db_user - Password:
secure_password - Test Connection
- Save
Connection in Task¶
Select from your configured connections.
Multiple Databases¶
You can query different databases in same workflow:
Task 1: MySQL Query → Database: CRM Database
Task 2: MySQL Query → Database: Accounting Database
Task 3: MySQL Query → Database: Analytics Database
Query Types¶
SELECT - Read Data¶
Fetch records from database.
Single record:
Parameters:{{task_15001_email}} Multiple records:
Parameters:{{task_15001_contact_id}} With JOIN:
SELECT c.name, c.email, o.order_id, o.total
FROM customers c
INNER JOIN orders o ON c.id = o.customer_id
WHERE c.id = ?
{{task_15001_contact_id}} Aggregation:
SELECT
COUNT(*) as total_orders,
SUM(total) as total_revenue,
AVG(total) as avg_order_value
FROM orders
WHERE customer_id = ?
{{task_15001_contact_id}} INSERT - Create Records¶
Add new records to database.
Single insert:
INSERT INTO leads (
email,
first_name,
last_name,
phone,
source,
created_at
) VALUES (?, ?, ?, ?, ?, NOW())
{{task_15001_email}},
{{task_15001_first_name}},
{{task_15001_last_name}},
{{task_15001_phone}},
Website
Insert with return ID:
Returns:task_[ID]_insert_id with new record ID UPDATE - Modify Records¶
Update existing records.
Simple update:
Parameters:{{task_15001_phone}}, {{task_15001_email}} Conditional update:
UPDATE orders
SET status = 'processed', processed_at = NOW()
WHERE order_id = ? AND status = 'pending'
{{task_46001_order_id}} Increment values:
UPDATE customers
SET total_purchases = total_purchases + 1,
lifetime_value = lifetime_value + ?
WHERE id = ?
{{task_46001_order_amount}}, {{task_15001_contact_id}} DELETE - Remove Records¶
Delete records from database.
With condition:
Specific record:
Parameters:{{task_15001_email}} Note: Use DELETE carefully, consider soft deletes instead.
Parameterized Queries¶
Why Use Parameters?¶
Security: Prevents SQL injection attacks Safety: Handles special characters automatically Performance: Query optimization by database
❌ NEVER do this (SQL Injection risk):
✅ ALWAYS do this:
Parameters:{{task_15001_email}} Parameter Syntax¶
Use ? as placeholder in query, then provide values in parameters field.
Single parameter:
Parameters:{{task_15001_contact_id}} Multiple parameters:
Parameters:{{task_15001_contact_id}}, login, {{task_48001_current_datetime}} Order matters: First ? = first parameter, second ? = second parameter, etc.
Parameter Types¶
BaseCloud automatically handles type conversion:
Strings:
Numbers:
Dates:
NULL values:
Output Fields¶
SELECT Queries¶
| Field | Description | Example Value |
|---|---|---|
task_[ID]_rows | Number of rows returned | 15 |
task_[ID]_row_0_column_name | First row, specific column | john@example.com |
task_[ID]_row_1_column_name | Second row, specific column | jane@example.com |
task_[ID]_results_JSON | All results as JSON array | [{...}, {...}] |
Access first row:
Access all rows (use with Loop task):
Check if results exist:
INSERT Queries¶
| Field | Description | Example Value |
|---|---|---|
task_[ID]_insert_id | ID of newly created record | 12345 |
task_[ID]_affected_rows | Rows inserted | 1 |
task_[ID]_success | Query successful | true |
UPDATE/DELETE Queries¶
| Field | Description | Example Value |
|---|---|---|
task_[ID]_affected_rows | Rows modified/deleted | 3 |
task_[ID]_success | Query successful | true |
task_[ID]_changed_rows | Rows actually changed | 2 |
Error Handling¶
| Field | Description | Example Value |
|---|---|---|
task_[ID]_error | Error occurred | true / false |
task_[ID]_error_message | Error details | Table doesn't exist |
task_[ID]_error_code | MySQL error code | 1146 |
Real-World Examples¶
Example 1: Create Lead from Form¶
Workflow: 1. Website Form 2. MySQL Query - Insert lead
Query:
INSERT INTO marketing_leads (
email,
first_name,
last_name,
phone,
company,
message,
source,
utm_source,
utm_campaign,
created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
Parameters:
{{task_55001_email}},
{{task_55001_first_name}},
{{task_55001_last_name}},
{{task_55001_phone}},
{{task_55001_company}},
{{task_55001_message}},
Website Form,
{{task_55001_utm_source}},
{{task_55001_utm_campaign}}
Next steps: 3. Match to Client - Find existing contact in CRM too 4. Email - Send confirmation
Example 2: Daily Sales Report¶
Workflow: 1. Schedule Trigger - Every day at 8 AM 2. MySQL Query - Get yesterday's sales
Query:
SELECT
COUNT(DISTINCT order_id) as total_orders,
COUNT(DISTINCT customer_id) as unique_customers,
SUM(total) as total_revenue,
AVG(total) as avg_order_value,
MAX(total) as largest_order
FROM orders
WHERE DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)
AND status = 'completed'
No parameters needed (static query)
Next steps: 3. Email - Send report
Total Orders: {{task_43001_row_0_total_orders}}
Revenue: R{{task_43001_row_0_total_revenue}}
Average: R{{task_43001_row_0_avg_order_value}}
Example 3: Update Customer Lifetime Value¶
Workflow: 1. Webhook In - Order completed 2. MySQL Query - Calculate total spent 3. Edit Client - Update CRM
Query:
SELECT
customer_id,
COUNT(*) as total_orders,
SUM(total) as lifetime_value,
MAX(created_at) as last_order_date
FROM orders
WHERE customer_email = ?
AND status = 'completed'
GROUP BY customer_id
Parameters: {{task_46001_customer_email}}
Next steps: 3. Edit Client: Update custom_lifetime_value with {{task_43001_row_0_lifetime_value}}
Example 4: Sync External System¶
Workflow: 1. Schedule Trigger - Every hour 2. MySQL Query - Get updated records 3. Loop - Process each record 4. Webhook Out - Sync to external API
Query:
SELECT
id,
email,
first_name,
last_name,
phone,
last_updated
FROM customers
WHERE last_updated > ?
AND synced = 0
ORDER BY last_updated ASC
LIMIT 100
Parameters: {{task_41001_last_sync_time}}
Loop through results:
Loop: {{task_43001_results_JSON}}
For each item:
- Webhook Out: Sync {{task_29001_email}}
- MySQL Query: Mark as synced
Example 5: Check Duplicate Before Insert¶
Workflow: 1. Webhook In - New contact 2. MySQL Query - Check if exists 3. If Task - Check result 4. MySQL Query - Insert or update
First Query (Check):
Parameters:{{task_46001_email}} Condition:
Update Query:
Insert Query:
Advanced Techniques¶
Stored Procedures¶
Call stored procedures:
Parameters:{{task_15001_contact_id}}, {{task_48001_current_date}} Transactions¶
For multiple related operations:
START TRANSACTION;
INSERT INTO orders (customer_id, total) VALUES (?, ?);
UPDATE inventory SET quantity = quantity - ? WHERE product_id = ?;
COMMIT;
Note: Manual transaction control limited. Consider stored procedures for complex transactions.
Subqueries¶
SELECT * FROM orders
WHERE customer_id IN (
SELECT id FROM customers WHERE status = 'VIP'
)
AND created_at > ?
JSON Columns¶
Query JSON data (MySQL 5.7+):
SELECT
id,
metadata->>'$.source' as source,
metadata->>'$.campaign' as campaign
FROM leads
WHERE metadata->>'$.source' = ?
Dynamic Table Names¶
Not supported directly for security.
Workaround: Use If task to choose different queries.
Best Practices¶
Security¶
- Always use parameters - Never concatenate user input
- Limit permissions - Database user should have minimum required access
- Read-only when possible - Use SELECT-only accounts for reporting
- Sanitize output - Don't expose sensitive data in logs
- Encrypt connections - Use SSL for database connections
Performance¶
- Use indexes - Index columns used in WHERE clauses
- Limit results - Add LIMIT clause to large queries
- **Avoid SELECT *** - Specify needed columns
- Cache results - Store in Variable task if reused
- Optimize joins - Use EXPLAIN to analyze query performance
Reliability¶
- Check for errors - Always verify
{{task_x_success}} - Handle empty results - Check
{{task_x_rows}} > 0 - Set timeouts - Don't let queries run forever
- Log operations - Track important database operations
- Test with production data - Use realistic test datasets
Maintainability¶
- Comment complex queries - Explain business logic
- Use consistent naming - Follow SQL naming conventions
- Version schema - Track database schema changes
- Document assumptions - Note expected data formats
- Keep queries simple - Break complex operations into steps
Troubleshooting¶
Query Returns No Results¶
Check: 1. WHERE conditions too restrictive? 2. Data actually exists in database? 3. Parameter values correct? 4. Date format matches database format?
Debug:
View execution history:
- Check parameters sent
- Run query manually in database tool
- Verify {{task_43001_rows}} value
Syntax Error¶
Common causes: 1. Missing comma in column list 2. Unmatched parentheses 3. Reserved keywords not quoted 4. Wrong number of parameters
Error: You have an error in your SQL syntax
Solution: Test query in MySQL Workbench first.
Parameter Count Mismatch¶
Error: Parameter count doesn't match placeholder count
Check: - Number of ? in query - Number of comma-separated parameters - Extra commas in parameters field
Example:
Query: VALUES (?, ?, ?)
Parameters: value1, value2, value3 ✓
Parameters: value1, value2, value3, ✗ (extra comma)
Connection Failed¶
Error: Can't connect to MySQL server
Check: 1. Database server running? 2. Host/port correct? 3. Firewall blocking connection? 4. Database user has access from this IP? 5. Password correct?
Timeout¶
Error: Query timeout after 30 seconds
Causes: - Query too slow (missing indexes) - Database overloaded - Locking issues
Solutions: - Optimize query - Add indexes - Reduce result set size - Increase timeout setting
Insert ID Not Returning¶
Check: - Table has AUTO_INCREMENT primary key? - INSERT actually succeeded? - Correct field name: {{task_43001_insert_id}}
Frequently Asked Questions¶
Can I query multiple tables?¶
Yes, use JOIN:
How do I loop through results?¶
Use Loop task:
1. MySQL Query - Get records
2. Loop - Process {{task_43001_results_JSON}}
3. Inside loop: Access {{task_29001_column_name}}
Can I use multiple databases?¶
Yes, configure multiple connections in Admin, then select appropriate connection per query.
How do I handle NULL values?¶
Parameters automatically handle NULL. In SQL:
What's the query timeout?¶
Default: 30 seconds Maximum: 120 seconds (configurable)
Can I execute multiple statements?¶
Limited support. Use stored procedures or separate tasks.
How do I format dates?¶
Or use Date Formatter task after query.
Can I connect to PostgreSQL or other databases?¶
Currently MySQL/MariaDB only. Other databases: use Webhook Out to call API.
How do I debug failed queries?¶
- View execution history
- Check error message
- Copy query and parameters
- Test in MySQL Workbench
- Check database logs
What happens if query fails mid-workflow?¶
Workflow stops at failed task unless error handling added with If task.
Related Tasks¶
- Loop Task - Process multiple query results
- If Task - Handle query results conditionally
- Variable Task - Store query results
- Code Task - Process complex query results
- Edit Client - Update CRM with query results