UNKNOWN_DATABASE ClickHouse error¶
This error occurs when you reference a database that doesn't exist. It's common when using incorrect database names, wrong connection settings, or missing database creation.
The UNKNOWN_DATABASE error in ClickHouse (and Tinybird) happens when you try to reference a database that doesn't exist in the system. This can occur when using incorrect database names, connecting to the wrong ClickHouse instance, or when the database hasn't been created yet.
What causes this error¶
You'll typically see it when:
- Referencing a database that hasn't been created
- Using incorrect database names (typos, case sensitivity)
- Connecting to the wrong ClickHouse instance
- Database was dropped or renamed
- Insufficient permissions to access the database
- Connection string points to non-existent database
- Database name contains special characters
ClickHouse database names are case-sensitive. Make sure you're using the exact case as defined in the database creation.
Example errors¶
USE non_existent_database;
-- Error: Unknown database 'non_existent_database'
SELECT * FROM wrong_database.events
-- Error: Unknown database 'wrong_database'
USE DatabaseName -- Should be 'database_name' (lowercase)
-- Error: Unknown database 'DatabaseName'
USE `my-database` -- Database name with hyphens
-- Error: Unknown database 'my-database'
How to fix it¶
Check existing databases¶
List all available databases:
SELECT name FROM system.databases
Check current database¶
Verify which database you're currently using:
SELECT currentDatabase() as current_db
Check database permissions¶
Verify your access to databases:
SELECT
database,
user,
grantee,
privilege_type
FROM system.grants
WHERE privilege_type = 'SELECT'
Create missing database¶
Create the database if it doesn't exist:
CREATE DATABASE IF NOT EXISTS your_database_name
Common patterns and solutions¶
Database creation¶
Create the required database:
CREATE DATABASE your_database_name
ENGINE = Atomic
Database switching¶
Switch to the correct database:
USE correct_database_name;
SELECT * FROM events LIMIT 10
Cross-database queries¶
Query tables across databases:
SELECT
u.id,
u.name,
e.event_type
FROM database1.users u
JOIN database2.events e ON u.id = e.user_id
Database verification¶
Verify database existence before use:
SELECT name FROM system.databases
WHERE name = 'your_database_name'
Tinybird-specific notes¶
In Tinybird, UNKNOWN_DATABASE errors often occur when:
- Referencing wrong workspace context
- Using incorrect Data Source references
- Workspace permissions are restricted
- Data Sources are in different workspaces
- API tokens point to wrong workspace
To debug in Tinybird:
- Check your workspace context
- Verify Data Source names and locations
- Check workspace permissions
- Ensure API tokens are for the correct workspace
In Tinybird, workspaces are equivalent to databases. Make sure you're in the correct workspace context.
Best practices¶
Database naming¶
- Use consistent naming conventions
- Avoid special characters in database names
- Use lowercase with underscores for multi-word names
- Document database naming standards
Connection management¶
- Always specify the correct database in connection strings
- Use environment variables for database names
- Implement connection validation
- Test connections before running queries
Database organization¶
- Group related tables in the same database
- Use meaningful database names
- Document database purposes and contents
- Implement proper access controls
Troubleshooting steps¶
Step 1: Verify database existence¶
SELECT name FROM system.databases
WHERE name = 'your_database_name'
Step 2: Check current context¶
SELECT currentDatabase() as current_db
Step 3: List available databases¶
SELECT name, engine FROM system.databases
Step 4: Verify permissions¶
SELECT
database,
user,
privilege_type
FROM system.grants
WHERE database = 'your_database_name'
Alternative solutions¶
Use default database¶
Connect to the default database:
-- Connect without specifying database
-- Or use the default database
USE default;
SELECT * FROM system.tables LIMIT 10
Create temporary database¶
Create a temporary database for testing:
CREATE DATABASE temp_test_db;
USE temp_test_db;
-- Create test table
CREATE TABLE test_events (
id UInt64,
name String
) ENGINE = Memory;
-- Test your queries
INSERT INTO test_events VALUES (1, 'test');
-- Clean up
DROP DATABASE temp_test_db;
Database migration¶
Handle database creation in your application:
-- In your application, implement database creation
-- Example pseudo-code:
--
-- def ensure_database_exists(database_name):
-- try:
-- execute_query(f"USE {database_name}")
-- except UnknownDatabase:
-- execute_query(f"CREATE DATABASE {database_name}")
-- execute_query(f"USE {database_name}")
Configuration options¶
Connection settings¶
-- In your client application, specify database
-- Example for Python clickhouse-driver:
from clickhouse_driver import Client
client = Client(
host='your-host',
port=9000,
database='your_database_name', -- Specify database
user='your_user',
password='your_password'
)
Environment variables¶
-- Use environment variables for database names
-- Example for Python:
import os
database_name = os.getenv('CLICKHOUSE_DATABASE', 'default')
client = Client(
host='your-host',
port=9000,
database=database_name,
user='your_user',
password='your_password'
)
Database validation¶
-- Validate database connection
-- Example pseudo-code:
--
-- def validate_database_connection(client, database_name):
-- try:
-- # Check if database exists
-- databases = client.execute("SELECT name FROM system.databases")
-- database_names = [db[0] for db in databases]
--
-- if database_name not in database_names:
-- raise ValueError(f"Database '{database_name}' does not exist")
--
-- # Test connection to database
-- client.execute(f"USE {database_name}")
-- return True
-- except Exception as e:
-- logger.error(f"Database validation failed: {e}")
-- return False
Monitoring and prevention¶
Database monitoring¶
-- Monitor database usage and health
SELECT
database,
COUNT(*) as table_count,
SUM(total_rows) as total_rows,
SUM(total_bytes) as total_bytes
FROM system.tables
GROUP BY database
ORDER BY total_bytes DESC
Connection tracking¶
-- Track database connections
SELECT
user,
database,
COUNT(*) as connection_count
FROM system.processes
GROUP BY user, database
ORDER BY connection_count DESC
Error logging¶
-- Log database access errors
-- Example pseudo-code:
--
-- def log_database_error(operation, database_name, error):
-- logger.error(f"Database operation failed: {operation} on {database_name}")
-- logger.error(f"Error details: {error}")
--
-- # Track error metrics
-- increment_counter('database_errors', {
-- 'operation': operation,
-- 'database': database_name,
-- 'error_type': type(error).__name__
-- })