How to fix ERROR 1065: Query was empty in MySQL

MySQLBEGINNERLOWUpdated Dec 22, 2025ยท 157 views

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);
  1. Add logging before query execution
  2. Validate query string is not empty before execution
  3. Check for missing SQL keywords or conditional logic
  4. Remove consecutive semicolons from SQL files
mysql โ€” error
$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

  1. Most common: Application code sends an empty string ("") or null value to MySQL instead of a valid SQL statement
  2. Dynamic query generation logic fails to properly construct the SQL, leaving variables empty or undefined
  3. Consecutive semicolons (;;) in SQL scripts create empty statements between them
  4. Query builder or ORM strips all content due to conditional logic that removes all clauses
  5. Newline characters or excessive whitespace with no actual SQL content
  6. SQL comments (-- or /* */) remove all code, leaving only whitespace
  7. Database driver receives empty buffer or malformed connection data

How to fix "ERROR 1065: Query was empty"

1Add logging before query execution

Insert logging statements in your application to capture the exact query string being sent to MySQL.

PHP example:

php
$query = "SELECT * FROM users WHERE id = " . $userId;
error_log("About to execute: " . $query);
$result = mysqli_query($connection, $query);

Node.js/JavaScript example:

javascript
const query = "SELECT * FROM users WHERE id = " . userId;
console.log("Query:", query);
db.query(query, (err, results) => { /* ... */ });

Python example:

python
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.

2Validate query string is not empty before execution

Add validation checks to ensure your query is not null or empty before sending it to the database.

PHP:

php
$query = buildQuery();
if (empty(trim($query))) {
  throw new Exception("Query cannot be empty");
}
mysqli_query($connection, $query);

JavaScript:

javascript
const query = buildQuery();
if (!query || query.trim().length === 0) {
  throw new Error("Query cannot be empty");
}
db.query(query);

Python:

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.

3Check for missing SQL keywords or conditional logic

Review your query construction code to ensure all required SQL components are included. Look for conditional blocks that might remove all content.

Problem example:

javascript
// 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:

javascript
// 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.

4Remove consecutive semicolons from SQL files

If importing SQL from migration files or batch scripts, check for empty statements caused by double semicolons.

Problem in migration file:

sql
CREATE TABLE users (id INT);;
CREATE TABLE posts (id INT);

The double semicolon (;;) creates an empty statement between the two statements.

Fix:

sql
CREATE TABLE users (id INT);
CREATE TABLE posts (id INT);

Use search and replace to find and remove ;; patterns from your SQL files.

5Check for commented-out or stripped content

Verify that query preprocessing doesn't accidentally remove all content.

Problem example:

python
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.

6Use parameterized queries to prevent construction errors

Switch to parameterized queries (prepared statements) which handle empty values more gracefully.

MySQL with prepared statements:

php
$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):

php
$user = User::find($userId);
// ORM handles query construction and validation

Parameterized 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