diff --git a/core/lib/Drupal/Core/Entity/Query/Sql/Query.php b/core/lib/Drupal/Core/Entity/Query/Sql/Query.php
index 7e5db5b9a0..2ff1fd9835 100644
--- a/core/lib/Drupal/Core/Entity/Query/Sql/Query.php
+++ b/core/lib/Drupal/Core/Entity/Query/Sql/Query.php
@@ -316,4 +316,22 @@ public function getTables(SelectInterface $sql_query) {
     return new $class($sql_query);
   }
 
+  /**
+   * Implements the magic __clone method.
+   */
+  public function __toString() {
+    // Clone the query so the prepare and compile stuff doesn't get repeated.
+    // TODO: figure out if this is necessary -- is it ok to call compile() more
+    // than once, e.g. if the query is dumped with this, then more is added to
+    // it?
+    $clone = clone($this);
+
+    $clone->prepare()
+      ->compile()
+      ->addSort()
+      ->finish();
+
+    return strtr((string) $clone->sqlQuery, $clone->sqlQuery->getArguments());
+  }
+
 }
diff --git a/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php b/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php
index 2c9b86826d..4e65b4f11d 100644
--- a/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php
@@ -1135,4 +1135,29 @@ public function testWithTwoEntityReferenceFieldsToSameEntityType() {
     $this->assertEquals($entity->id(), reset($result));
   }
 
+  /**
+   * Tests __toString().
+   */
+  public function testToString() {
+    $query = $this->storage->getQuery();
+    $group_blue = $query->andConditionGroup()->condition("{$this->figures}.color", ['blue'], 'IN');
+    $group_red = $query->andConditionGroup()->condition("{$this->figures}.color", ['red'], 'IN');
+    $this->queryResults = $query
+      ->condition($group_blue)
+      ->condition($group_red)
+      ->sort('id');
+
+    $figures = $this->figures;
+    $this->assertEquals(<<<EOF
+SELECT base_table.revision_id AS revision_id, base_table.id AS id
+FROM 
+{entity_test_mulrev} base_table
+INNER JOIN {entity_test_mulrev__{$figures}} entity_test_mulrev__$figures ON entity_test_mulrev__$figures.entity_id = base_table.id
+INNER JOIN {entity_test_mulrev__{$figures}} entity_test_mulrev__{$figures}_2 ON entity_test_mulrev__{$figures}_2.entity_id = base_table.id
+WHERE (entity_test_mulrev__{$figures}.{$figures}_color IN (blue)) AND (entity_test_mulrev__{$figures}_2.{$figures}_color IN (red))
+ORDER BY base_table.id ASC
+EOF
+, (string) $query);
+  }
+
 }
