Chat Flow
Flow Builder
Blocks
Database
MySQL

MySQL Integration Block

The MySQL block provides seamless integration with MySQL databases, enabling standard CRUD operations, custom SQL queries, and advanced features like transactions and JSON data handling for robust data management in your workflows.

Configure a valid MySQL connection string and credentials before setting up the block to ensure secure connectivity.

Features

  • CRUD Operations: Execute SELECT, INSERT, UPDATE, and DELETE operations with intuitive configuration.
  • Custom SQL Queries: Run any valid MySQL statement for maximum flexibility.
  • Storage Engine Support: Works with InnoDB, MyISAM, and other engines.
  • Response Mapping: Map query results to bot variables.
  • Connection Pooling: Optimize connection management for performance.
  • Transaction Support: Ensure ACID-compliant operations.

Configuration

Database Connection

  1. Credentials Setup:

    • Host and Port: Specify the MySQL server address (default port: 3306).
    • Database Name: Target database for operations.
    • Username and Password: Provide authentication credentials.
    • Character Set: Use utf8mb4 for full Unicode support (default).
  2. Connection String Format:

    mysql://username:password@host:port/database?charset=utf8mb4

Enable SSL/TLS in the connection string (e.g., ?ssl=true) for secure data transfer, especially for cloud-hosted databases.

Flow Editor Setup

  1. Drag the MySQL block from the Integrations category into your flow.
  2. Select an operation (e.g., SELECT, INSERT, UPDATE, DELETE, Custom Query).
  3. Enter the connection string, database name, table, and operation-specific parameters.
  4. Test in the Indite editor’s preview mode to verify connectivity and query execution.
⚠️

Validate the connection string and query syntax in preview mode to catch errors before deployment.

CRUD Operations

SELECT Operation

Query tables or views with flexible filtering, grouping, and sorting options.

Configuration Options:

  • Table/View: Select the target table or view.
  • Columns: Specify columns or use SELECT *.
  • WHERE Conditions: Filter rows with conditions.
  • GROUP BY: Aggregate data by columns.
  • HAVING: Filter grouped results.
  • ORDER BY: Sort results by columns.
  • LIMIT/OFFSET: Enable pagination.

Example Queries:

-- Retrieve recently active customers with contact details
SELECT customer_id, first_name, email, signup_date
FROM customers
WHERE status = 'active'
AND signup_date >= DATE_SUB(NOW(), INTERVAL 60 DAY)
ORDER BY signup_date DESC
LIMIT 100;
 
-- Aggregate employee data by department for salary analysis
SELECT
  department,
  COUNT(*) as employee_count,
  AVG(salary) as avg_salary,
  MAX(salary) as max_salary
FROM employees
WHERE active = true
GROUP BY department
HAVING COUNT(*) > 10
ORDER BY avg_salary DESC;

INSERT Operation

Add records with support for bulk inserts and duplicate key handling.

Configuration Options:

  • Table: Target table for insertion.
  • Column Mapping: Map bot variables to table columns.
  • Bulk Insert: Insert multiple rows in one query.
  • Duplicate Handling: Use ON DUPLICATE KEY UPDATE for conflicts.
  • Auto-increment: Handle AUTO_INCREMENT columns automatically.

Example Queries:

-- Insert a single order with customer and product details
INSERT INTO orders (customer_id, product_id, quantity, order_date, status)
VALUES (101, 202, 3, NOW(), 'pending');
 
-- Bulk insert user settings with conflict resolution
INSERT INTO user_settings (user_id, setting_key, setting_value)
VALUES
  (1, 'language', 'en'),
  (1, 'timezone', 'UTC'),
  (2, 'language', 'es')
ON DUPLICATE KEY UPDATE
  setting_value = VALUES(setting_value),
  updated_at = NOW();

UPDATE Operation

Modify records with conditional updates and multi-table joins.

Configuration Options:

  • Table: Target table for updates.
  • SET Clauses: Define new column values.
  • WHERE Conditions: Specify rows to update.
  • JOIN Operations: Update with data from related tables.
  • LIMIT: Restrict the number of updated rows.

Example Queries:

-- Deactivate customers with no recent purchases
UPDATE customers
SET status = 'inactive', last_updated = NOW()
WHERE last_purchase < DATE_SUB(NOW(), INTERVAL 3 MONTH);
 
-- Prioritize orders for premium customers
UPDATE orders o
JOIN customers c ON o.customer_id = c.customer_id
SET o.priority = 'urgent'
WHERE c.membership = 'gold'
AND o.status = 'pending';

DELETE Operation

Remove records with precise conditions and referential integrity.

Configuration Options:

  • Table: Target table for deletion.
  • WHERE Conditions: Define rows to delete.
  • JOIN Deletes: Delete from multiple tables.
  • LIMIT: Restrict deletion count.
  • Foreign Key Handling: Manage cascading deletes.

Example Queries:

-- Delete expired user sessions
DELETE FROM sessions
WHERE expires_at < NOW()
AND last_active < DATE_SUB(NOW(), INTERVAL 48 HOUR)
LIMIT 500;
 
-- Delete cancelled orders and their items
DELETE o, oi
FROM orders o
JOIN order_items oi ON o.order_id = oi.order_id
WHERE o.status = 'cancelled'
AND o.created_at < DATE_SUB(NOW(), INTERVAL 6 MONTH);

Custom SQL Queries

Execute advanced MySQL statements for specialized operations.

Advanced Query Examples

Data Analytics with Window Functions

-- Analyze customer order history with sequence and totals
SELECT
  customer_id,
  order_date,
  total_amount,
  ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date) as order_number,
  SUM(total_amount) OVER (PARTITION BY customer_id ORDER BY order_date ROWS UNBOUNDED PRECEDING) as cumulative_total,
  LAG(total_amount) OVER (PARTITION BY customer_id ORDER BY order_date) as prev_order_amount
FROM orders
WHERE order_date >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
ORDER BY customer_id, order_date;

Stored Procedure Execution

-- Generate a sales report for a date range
CALL GenerateSalesReport('2025-01-01', '2025-06-30', 'detailed');
 
-- Retrieve output parameters from the stored procedure
SELECT @total_sales, @order_count, @top_customer;

Complex Data Transformation

-- Summarize quarterly sales by product category
SELECT
  product_category,
  SUM(CASE WHEN MONTH(order_date) = 4 THEN total_amount ELSE 0 END) as apr_sales,
  SUM(CASE WHEN MONTH(order_date) = 5 THEN total_amount ELSE 0 END) as may_sales,
  SUM(CASE WHEN MONTH(order_date) = 6 THEN total_amount ELSE 0 END) as jun_sales,
  COUNT(DISTINCT customer_id) as unique_buyers
FROM orders o
JOIN products p ON o.product_id = p.product_id
WHERE YEAR(order_date) = YEAR(NOW())
GROUP BY product_category
ORDER BY (apr_sales + may_sales + jun_sales) DESC;

Full-Text Search

-- Search products with relevance scoring
SELECT
  product_id,
  product_name,
  description,
  MATCH(product_name, description) AGAINST('smartphone accessories' IN NATURAL LANGUAGE MODE) as relevance
FROM products
WHERE MATCH(product_name, description) AGAINST('smartphone accessories' IN NATURAL LANGUAGE MODE)
ORDER BY relevance DESC
LIMIT 25;

MySQL-Specific Features

JSON Operations (MySQL 5.7+)

-- Extract user details from JSON data
SELECT
  user_id,
  JSON_EXTRACT(user_data, '$.full_name') as full_name,
  JSON_EXTRACT(user_data, '$.settings.language') as language
FROM profiles
WHERE JSON_EXTRACT(user_data, '$.active') = true;
 
-- Update JSON fields for user activity
UPDATE profiles
SET user_data = JSON_SET(user_data, '$.last_access', NOW())
WHERE user_id = ?;

Generated Columns

-- Calculate order totals with generated columns
SELECT
  order_id,
  subtotal,
  tax_rate,
  subtotal * tax_rate as tax_amount,
  subtotal + (subtotal * tax_rate) as total_with_tax
FROM orders
WHERE (subtotal + (subtotal * tax_rate)) > 200;

Temporal Tables (MySQL 8.0+)

-- Retrieve historical inventory data for analysis
SELECT * FROM inventory
FOR SYSTEM_TIME BETWEEN '2025-01-01' AND '2025-03-31'
WHERE category = 'electronics';

Performance Optimization

Index Usage

-- Use a specific index for date-based queries
SELECT * FROM transactions USE INDEX (idx_transaction_date)
WHERE transaction_date >= '2025-01-01';
 
-- Analyze query execution for optimization
EXPLAIN ANALYZE
SELECT customer_id, COUNT(*)
FROM orders
WHERE order_date >= DATE_SUB(NOW(), INTERVAL 3 MONTH)
GROUP BY customer_id;

Query Optimization

-- Optimize pagination with key-based filtering
SELECT * FROM products
WHERE product_id > 5000
ORDER BY product_id
LIMIT 25;
 
-- Perform efficient bulk data aggregation
INSERT INTO analytics_temp
SELECT customer_id, SUM(total_amount) as total_spent
FROM orders
WHERE order_date >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
GROUP BY customer_id
HAVING SUM(total_amount) > 500;

Transaction Management

ACID Transactions

-- Process a new order with inventory and audit updates
START TRANSACTION;
  INSERT INTO orders (customer_id, total_amount, status)
  VALUES (?, ?, 'pending');
 
  UPDATE inventory
  SET stock_quantity = stock_quantity - ?
  WHERE product_id = ?;
 
  INSERT INTO order_audit (order_id, action, timestamp)
  VALUES (LAST_INSERT_ID(), 'created', NOW());
COMMIT;

Savepoints

-- Manage account balance updates with rollback option
START TRANSACTION;
  SAVEPOINT before_transfer;
 
  UPDATE accounts SET balance = balance - 200 WHERE account_id = 1;
 
  IF (SELECT balance FROM accounts WHERE account_id = 1) < 0 THEN
    ROLLBACK TO SAVEPOINT before_transfer;
  END IF;
COMMIT;

Troubleshooting

Common Issues

  • Connection Errors: Verify host, port, credentials, and network access. Ensure the MySQL server is running and accessible.
  • Duplicate Entry Errors: Handle unique key violations using ON DUPLICATE KEY UPDATE or error trapping.
  • Foreign Key Constraint Errors: Check referential integrity and cascading rules.
  • Data Too Long Errors: Ensure data fits column length limits.
  • WhatsApp Compatibility: Use text or .mp4 formats for WhatsApp integration—see WhatsApp Guide.
  • Slow Queries: Use EXPLAIN ANALYZE to identify bottlenecks and add appropriate indexes.
⚠️

Test all queries in the Indite editor’s preview mode to catch errors before deployment.

Error Handling and Debugging

Common MySQL Errors

  • Duplicate Entry: Trap unique constraint violations (e.g., error code 1062).
  • Foreign Key Constraint: Resolve referential integrity issues (e.g., error code 1452).
  • Data Too Long: Adjust column definitions or truncate data (e.g., error code 1406).
  • Connection Lost: Implement retry logic for timeouts (e.g., error code 2003).

Debugging Queries

-- Inspect query execution plan for performance issues
EXPLAIN FORMAT=JSON
SELECT * FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.order_date >= DATE_SUB(NOW(), INTERVAL 60 DAY);
 
-- Check for query warnings
SHOW WARNINGS;
 
-- View table metadata for diagnostics
SHOW TABLE STATUS LIKE 'orders';

Response Mapping and Integration

  • Single Values: Extract specific column values.
  • Result Sets: Process multi-row results as arrays.
  • JSON Responses: Handle JSON column data with JSON_EXTRACT.
  • Aggregated Data: Map calculated values to variables.
  • Error Information: Capture and process error details.

Best Practices

Security

  • Prepared Statements: Use parameterized queries to prevent SQL injection.
  • User Privileges: Grant minimal permissions to users.
  • SSL Connections: Encrypt data in transit with SSL/TLS.
  • Regular Updates: Keep MySQL updated to patch vulnerabilities.

Performance

  • Index Strategy: Create indexes for frequent query patterns.
  • Query Optimization: Analyze queries with EXPLAIN or EXPLAIN ANALYZE.
  • Connection Pooling: Reuse connections for efficiency.
  • Partitioning: Use table partitioning for large datasets.

Maintenance

  • Regular Backups: Schedule automated backups.
  • Monitoring: Track slow queries and errors via logs.
  • Log Analysis: Review slow query logs for optimization.
  • Optimization: Run OPTIMIZE TABLE periodically for maintenance.
Indite Documentation v1.4.0
PrivacyTermsSupport