How to fix ERROR 1065: Query was empty in MySQL
MySQL Error 1065 occurs when an empty or null SQL statement is sent to the server. This typically happens due to programming errors in query construction, malformed dynamic queries, or accidental empty strings in application code.
Quick fix
Fixes 1065
$query = "SELECT * FROM users WHERE id = " . $userId;
error_log("About to execute: " . $query);
$result = mysqli_query($connection, $query);- Add logging before query execution
- Validate query string is not empty before execution
- Check for missing SQL keywords or conditional logic
- Remove consecutive semicolons from SQL files
$query = "SELECT * FROM users WHERE id = " . $userId;error_log("About to execute: " . $query);$result = mysqli_query($connection, $query);ERROR 1065: Query was empty
What this error means
MySQL Error 1065 (ER_EMPTY_QUERY) is raised when the MySQL server receives a query string that contains no valid SQL statement. The server expects at least one non-empty SQL command to execute, but instead gets an empty string, null value, or only whitespace characters. This is a validation error that prevents the server from attempting to parse and execute the invalid input. The error occurs at the protocol level before the parser even attempts to interpret the query. It indicates a problem with how the query was constructed or passed to the server, not with the SQL syntax itself.
Typical symptoms
- Application fails with "ERROR 1065: Query was empty" message
- Database operations throw ER_EMPTY_QUERY exceptions
- Specific database queries fail while others succeed
- Error appears inconsistently with dynamic query generation
- Migration or batch SQL files trigger empty query errors
Common causes
- Most common: Application code sends an empty string ("") or null value to MySQL instead of a valid SQL statement
- Dynamic query generation logic fails to properly construct the SQL, leaving variables empty or undefined
- Consecutive semicolons (;;) in SQL scripts create empty statements between them
- Query builder or ORM strips all content due to conditional logic that removes all clauses
- Newline characters or excessive whitespace with no actual SQL content
- SQL comments (-- or /* */) remove all code, leaving only whitespace
- Database driver receives empty buffer or malformed connection data
How to fix "ERROR 1065: Query was empty"
Insert logging statements in your application to capture the exact query string being sent to MySQL.
PHP example:
$query = "SELECT * FROM users WHERE id = " . $userId;
error_log("About to execute: " . $query);
$result = mysqli_query($connection, $query);Node.js/JavaScript example:
const query = "SELECT * FROM users WHERE id = " . userId;
console.log("Query:", query);
db.query(query, (err, results) => { /* ... */ });Python example:
query = f"SELECT * FROM users WHERE id = {user_id}"
print(f"Executing query: {query}")
cursor.execute(query)Run your code and check the logs to see if the query string is actually empty.
Add validation checks to ensure your query is not null or empty before sending it to the database.
PHP:
$query = buildQuery();
if (empty(trim($query))) {
throw new Exception("Query cannot be empty");
}
mysqli_query($connection, $query);JavaScript:
const query = buildQuery();
if (!query || query.trim().length === 0) {
throw new Error("Query cannot be empty");
}
db.query(query);Python:
query = build_query()
if not query or not query.strip():
raise ValueError("Query cannot be empty")
cursor.execute(query)This fails fast and helps identify where the problem originates.
Review your query construction code to ensure all required SQL components are included. Look for conditional blocks that might remove all content.
Problem example:
// Bad: might result in empty WHERE clause
let query = "SELECT * FROM users";
if (hasFilter) {
query += " WHERE " + filterCondition;
}
// If hasFilter is false, query is fine
// But if filterCondition is empty, you get "SELECT * FROM users WHERE "Better approach:
// Good: only add WHERE if condition exists
let query = "SELECT * FROM users";
if (hasFilter && filterCondition) {
query += " WHERE " + filterCondition;
}Ensure that every variable used in query construction has a value before adding it to the query string.
If importing SQL from migration files or batch scripts, check for empty statements caused by double semicolons.
Problem in migration file:
CREATE TABLE users (id INT);;
CREATE TABLE posts (id INT);The double semicolon (;;) creates an empty statement between the two statements.
Fix:
CREATE TABLE users (id INT);
CREATE TABLE posts (id INT);Use search and replace to find and remove ;; patterns from your SQL files.
Verify that query preprocessing doesn't accidentally remove all content.
Problem example:
query = """
-- SELECT * FROM users
-- WHERE active = 1
"""
# If using comment-stripping, this becomes empty!Check for:
- SQL comment-only files
- Query builders that strip comments before validation
- Template engines that remove all content during processing
- String trim() operations that might leave nothing
Ensure that the query contains actual SQL code, not just comments or whitespace.
Switch to parameterized queries (prepared statements) which handle empty values more gracefully.
MySQL with prepared statements:
$stmt = $connection->prepare("SELECT * FROM users WHERE id = ?");
if (!$stmt) {
throw new Exception("Prepare failed: " . $connection->error);
}
$stmt->bind_param("i", $userId);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}Using ORM (Eloquent for Laravel):
$user = User::find($userId);
// ORM handles query construction and validationParameterized queries prevent many types of errors and are more secure.
Advanced notes
Error 1065 is a protocol-level error that occurs before the MySQL parser runs. Unlike syntax errors (which indicate a problem with SQL grammar), this error means the server never even attempts to parse the query.
In interactive MySQL clients (mysql command-line), pressing Enter with no text also triggers Error 1065, which is why it's commonly seen in script automation and batch operations.
Some database drivers (like the PHP mysqli extension) may wrap this error differently. Check your language's MySQL driver documentation to understand how empty queries are handled in your specific context.
For Node.js mysql library versions, ensure queries are passed correctly. The mysql2 package handles some edge cases better than the original mysql package.
Frequently asked questions
- What does "1065" mean?
- MySQL Error 1065 (ER_EMPTY_QUERY) is raised when the MySQL server receives a query string that contains no valid SQL statement. The server expects at least one non-empty SQL command to execute, but instead gets an empty string, null value, or only whitespace characters. This is a validation error that prevents the server from attempting to parse and execute the invalid input.
- How do I fix "1065"?
- MySQL Error 1065 occurs when an empty or null SQL statement is sent to the server. This typically happens due to programming errors in query construction, malformed dynamic queries, or accidental empty strings in application code.
- What causes "1065"?
- Most common: Application code sends an empty string ("") or null value to MySQL instead of a valid SQL statement Dynamic query generation logic fails to properly construct the SQL, leaving variables empty or undefined Consecutive semicolons (;;) in SQL scripts create empty statements between them
- Is the "1065" error serious?
- It is a low-severity error โ more of a blocker than a risk. The steps above resolve it.
Official resources & further reading
- ๐MySQL Official Documentation
- ๐MySQL Error Reference(Official Docs)
- ๐ฌMySQL Forums - Error 1065 Discussion(Stack Overflow)
- ๐MariaDB Knowledge Base - Error 1065(Official Docs)