You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iceberg.apache.org by ao...@apache.org on 2022/12/24 18:37:35 UTC

[iceberg] branch master updated: Spark 3.3: Support storage-partitioned joins (#6371)

This is an automated email from the ASF dual-hosted git repository.

aokolnychyi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iceberg.git


The following commit(s) were added to refs/heads/master by this push:
     new 31c8011043 Spark 3.3: Support storage-partitioned joins (#6371)
31c8011043 is described below

commit 31c801104303678a790e33586aeb388833fd90d6
Author: Anton Okolnychyi <ao...@apple.com>
AuthorDate: Sat Dec 24 10:37:28 2022 -0800

    Spark 3.3: Support storage-partitioned joins (#6371)
---
 .../main/java/org/apache/iceberg/Partitioning.java |  29 +-
 .../java/org/apache/iceberg/TestPartitioning.java  |  39 +-
 .../extensions/TestAlterTablePartitionFields.java  |   6 +-
 .../spark/extensions/TestCopyOnWriteDelete.java    |  33 ++
 .../spark/extensions/TestCopyOnWriteMerge.java     |  45 ++
 .../spark/extensions/TestCopyOnWriteUpdate.java    |  35 ++
 ...toragePartitionedJoinsInRowLevelOperations.java | 283 ++++++++++
 .../java/org/apache/iceberg/spark/Spark3Util.java  | 123 +++--
 .../org/apache/iceberg/spark/SparkReadConf.java    |   8 +
 .../apache/iceberg/spark/SparkSQLProperties.java   |   5 +
 .../apache/iceberg/spark/source/SparkBatch.java    |   5 +
 .../iceberg/spark/source/SparkBatchQueryScan.java  |  83 +--
 .../iceberg/spark/source/SparkChangelogScan.java   |  25 +-
 .../iceberg/spark/source/SparkCopyOnWriteScan.java |  62 +--
 .../iceberg/spark/source/SparkInputPartition.java  |  13 +-
 .../spark/source/SparkMicroBatchStream.java        |   3 +
 .../spark/source/SparkPartitioningAwareScan.java   | 269 ++++++++++
 .../org/apache/iceberg/spark/source/SparkScan.java |  35 +-
 .../iceberg/spark/source/SparkScanBuilder.java     |   5 +-
 .../apache/iceberg/spark/source/SparkWrite.java    |   2 +-
 .../iceberg/spark/source/StructInternalRow.java    |  20 +
 .../org/apache/iceberg/spark/SparkTestBase.java    |  71 +++
 .../spark/sql/TestStoragePartitionedJoins.java     | 586 +++++++++++++++++++++
 23 files changed, 1567 insertions(+), 218 deletions(-)

diff --git a/core/src/main/java/org/apache/iceberg/Partitioning.java b/core/src/main/java/org/apache/iceberg/Partitioning.java
index 0fda98bf4d..b07f9a4504 100644
--- a/core/src/main/java/org/apache/iceberg/Partitioning.java
+++ b/core/src/main/java/org/apache/iceberg/Partitioning.java
@@ -200,6 +200,18 @@ public class Partitioning {
   /**
    * Builds a grouping key type considering all provided specs.
    *
+   * @param specs one or many specs
+   * @return the constructed grouping key type
+   * @deprecated use {@link #groupingKeyType(Schema, Collection)} instead; will be removed in 1.3.0
+   */
+  @Deprecated
+  public static StructType groupingKeyType(Collection<PartitionSpec> specs) {
+    return groupingKeyType(null, specs);
+  }
+
+  /**
+   * Builds a grouping key type considering the provided schema and specs.
+   *
    * <p>A grouping key defines how data is split between files and consists of partition fields with
    * non-void transforms that are present in each provided spec. Iceberg guarantees that records
    * with different values for the grouping key are disjoint and are stored in separate files.
@@ -215,11 +227,15 @@ public class Partitioning {
    * that have the same field ID but use a void transform under the hood. Such fields cannot be part
    * of the grouping key as void transforms always return null.
    *
+   * <p>If the provided schema is not null, this method will only take into account partition fields
+   * on top of columns present in the schema. Otherwise, all partition fields will be considered.
+   *
+   * @param schema a schema specifying a set of source columns to consider (null to consider all)
    * @param specs one or many specs
    * @return the constructed grouping key type
    */
-  public static StructType groupingKeyType(Collection<PartitionSpec> specs) {
-    return buildPartitionProjectionType("grouping key", specs, commonActiveFieldIds(specs));
+  public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec> specs) {
+    return buildPartitionProjectionType("grouping key", specs, commonActiveFieldIds(schema, specs));
   }
 
   /**
@@ -341,15 +357,15 @@ public class Partitioning {
   }
 
   // collects IDs of partition fields with non-void transforms that are present in each spec
-  private static Set<Integer> commonActiveFieldIds(Collection<PartitionSpec> specs) {
+  private static Set<Integer> commonActiveFieldIds(Schema schema, Collection<PartitionSpec> specs) {
     Set<Integer> commonActiveFieldIds = Sets.newHashSet();
 
     int specIndex = 0;
     for (PartitionSpec spec : specs) {
       if (specIndex == 0) {
-        commonActiveFieldIds.addAll(activeFieldIds(spec));
+        commonActiveFieldIds.addAll(activeFieldIds(schema, spec));
       } else {
-        commonActiveFieldIds.retainAll(activeFieldIds(spec));
+        commonActiveFieldIds.retainAll(activeFieldIds(schema, spec));
       }
 
       specIndex++;
@@ -358,8 +374,9 @@ public class Partitioning {
     return commonActiveFieldIds;
   }
 
-  private static List<Integer> activeFieldIds(PartitionSpec spec) {
+  private static List<Integer> activeFieldIds(Schema schema, PartitionSpec spec) {
     return spec.fields().stream()
+        .filter(field -> schema == null || schema.findField(field.sourceId()) != null)
         .filter(field -> !isVoidTransform(field))
         .map(PartitionField::fieldId)
         .collect(Collectors.toList());
diff --git a/core/src/test/java/org/apache/iceberg/TestPartitioning.java b/core/src/test/java/org/apache/iceberg/TestPartitioning.java
index 46c9cb1f61..1faf8d2f69 100644
--- a/core/src/test/java/org/apache/iceberg/TestPartitioning.java
+++ b/core/src/test/java/org/apache/iceberg/TestPartitioning.java
@@ -185,7 +185,7 @@ public class TestPartitioning {
 
     StructType expectedType =
         StructType.of(NestedField.optional(1000, "data", Types.StringType.get()));
-    StructType actualType = Partitioning.groupingKeyType(table.specs().values());
+    StructType actualType = Partitioning.groupingKeyType(table.schema(), table.specs().values());
     Assert.assertEquals("Types must match", expectedType, actualType);
   }
 
@@ -200,7 +200,7 @@ public class TestPartitioning {
 
     StructType expectedType =
         StructType.of(NestedField.optional(1000, "data", Types.StringType.get()));
-    StructType actualType = Partitioning.groupingKeyType(table.specs().values());
+    StructType actualType = Partitioning.groupingKeyType(table.schema(), table.specs().values());
     Assert.assertEquals("Types must match", expectedType, actualType);
   }
 
@@ -216,7 +216,7 @@ public class TestPartitioning {
 
     StructType expectedType =
         StructType.of(NestedField.optional(1000, "data", Types.StringType.get()));
-    StructType actualType = Partitioning.groupingKeyType(table.specs().values());
+    StructType actualType = Partitioning.groupingKeyType(table.schema(), table.specs().values());
     Assert.assertEquals("Types must match", expectedType, actualType);
   }
 
@@ -232,7 +232,7 @@ public class TestPartitioning {
 
     StructType expectedType =
         StructType.of(NestedField.optional(1000, "data", Types.StringType.get()));
-    StructType actualType = Partitioning.groupingKeyType(table.specs().values());
+    StructType actualType = Partitioning.groupingKeyType(table.schema(), table.specs().values());
     Assert.assertEquals("Types must match", expectedType, actualType);
   }
 
@@ -248,7 +248,7 @@ public class TestPartitioning {
 
     StructType expectedType =
         StructType.of(NestedField.optional(1000, "p2", Types.StringType.get()));
-    StructType actualType = Partitioning.groupingKeyType(table.specs().values());
+    StructType actualType = Partitioning.groupingKeyType(table.schema(), table.specs().values());
     Assert.assertEquals("Types must match", expectedType, actualType);
   }
 
@@ -264,7 +264,7 @@ public class TestPartitioning {
 
     StructType expectedType =
         StructType.of(NestedField.optional(1000, "p2", Types.StringType.get()));
-    StructType actualType = Partitioning.groupingKeyType(table.specs().values());
+    StructType actualType = Partitioning.groupingKeyType(table.schema(), table.specs().values());
     Assert.assertEquals("Types must match", expectedType, actualType);
   }
 
@@ -278,7 +278,7 @@ public class TestPartitioning {
     Assert.assertEquals("Should have 2 specs", 2, table.specs().size());
 
     StructType expectedType = StructType.of();
-    StructType actualType = Partitioning.groupingKeyType(table.specs().values());
+    StructType actualType = Partitioning.groupingKeyType(table.schema(), table.specs().values());
     Assert.assertEquals("Types must match", expectedType, actualType);
   }
 
@@ -292,7 +292,7 @@ public class TestPartitioning {
     Assert.assertEquals("Should have 2 specs", 2, table.specs().size());
 
     StructType expectedType = StructType.of();
-    StructType actualType = Partitioning.groupingKeyType(table.specs().values());
+    StructType actualType = Partitioning.groupingKeyType(table.schema(), table.specs().values());
     Assert.assertEquals("Types must match", expectedType, actualType);
   }
 
@@ -307,7 +307,7 @@ public class TestPartitioning {
 
     StructType expectedType =
         StructType.of(NestedField.optional(1000, "category", Types.StringType.get()));
-    StructType actualType = Partitioning.groupingKeyType(table.specs().values());
+    StructType actualType = Partitioning.groupingKeyType(table.schema(), table.specs().values());
     Assert.assertEquals("Types must match", expectedType, actualType);
   }
 
@@ -322,7 +322,7 @@ public class TestPartitioning {
 
     StructType expectedType =
         StructType.of(NestedField.optional(1000, "category", Types.StringType.get()));
-    StructType actualType = Partitioning.groupingKeyType(table.specs().values());
+    StructType actualType = Partitioning.groupingKeyType(table.schema(), table.specs().values());
     Assert.assertEquals("Types must match", expectedType, actualType);
   }
 
@@ -335,7 +335,7 @@ public class TestPartitioning {
     Assert.assertEquals("Should have 1 spec", 1, table.specs().size());
 
     StructType expectedType = StructType.of();
-    StructType actualType = Partitioning.groupingKeyType(table.specs().values());
+    StructType actualType = Partitioning.groupingKeyType(table.schema(), table.specs().values());
     Assert.assertEquals("Types must match", expectedType, actualType);
   }
 
@@ -350,7 +350,20 @@ public class TestPartitioning {
     Assert.assertEquals("Should have 2 specs", 2, table.specs().size());
 
     StructType expectedType = StructType.of();
-    StructType actualType = Partitioning.groupingKeyType(table.specs().values());
+    StructType actualType = Partitioning.groupingKeyType(table.schema(), table.specs().values());
+    Assert.assertEquals("Types must match", expectedType, actualType);
+  }
+
+  @Test
+  public void testGroupingKeyTypeWithProjectedSchema() {
+    TestTables.TestTable table =
+        TestTables.create(tableDir, "test", SCHEMA, BY_CATEGORY_DATA_SPEC, V1_FORMAT_VERSION);
+
+    Schema projectedSchema = table.schema().select("id", "data");
+
+    StructType expectedType =
+        StructType.of(NestedField.optional(1001, "data", Types.StringType.get()));
+    StructType actualType = Partitioning.groupingKeyType(projectedSchema, table.specs().values());
     Assert.assertEquals("Types must match", expectedType, actualType);
   }
 
@@ -371,6 +384,6 @@ public class TestPartitioning {
         "Should complain about incompatible specs",
         ValidationException.class,
         "Conflicting partition fields",
-        () -> Partitioning.groupingKeyType(table.specs().values()));
+        () -> Partitioning.groupingKeyType(table.schema(), table.specs().values()));
   }
 }
diff --git a/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestAlterTablePartitionFields.java b/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestAlterTablePartitionFields.java
index 8528ab296b..a4928e6552 100644
--- a/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestAlterTablePartitionFields.java
+++ b/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestAlterTablePartitionFields.java
@@ -404,15 +404,15 @@ public class TestAlterTablePartitionFields extends SparkExtensionsTestBase {
     assertPartitioningEquals(sparkTable(), 1, "bucket(16, id)");
 
     sql("ALTER TABLE %s ADD PARTITION FIELD truncate(data, 4)", tableName);
-    assertPartitioningEquals(sparkTable(), 2, "truncate(data, 4)");
+    assertPartitioningEquals(sparkTable(), 2, "truncate(4, data)");
 
     sql("ALTER TABLE %s ADD PARTITION FIELD years(ts)", tableName);
     assertPartitioningEquals(sparkTable(), 3, "years(ts)");
 
     sql("ALTER TABLE %s DROP PARTITION FIELD years(ts)", tableName);
-    assertPartitioningEquals(sparkTable(), 2, "truncate(data, 4)");
+    assertPartitioningEquals(sparkTable(), 2, "truncate(4, data)");
 
-    sql("ALTER TABLE %s DROP PARTITION FIELD truncate(data, 4)", tableName);
+    sql("ALTER TABLE %s DROP PARTITION FIELD truncate(4, data)", tableName);
     assertPartitioningEquals(sparkTable(), 1, "bucket(16, id)");
 
     sql("ALTER TABLE %s DROP PARTITION FIELD shard", tableName);
diff --git a/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestCopyOnWriteDelete.java b/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestCopyOnWriteDelete.java
index 22dbd9df5e..5c9d547a6a 100644
--- a/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestCopyOnWriteDelete.java
+++ b/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestCopyOnWriteDelete.java
@@ -32,14 +32,19 @@ import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 import org.apache.iceberg.DataFile;
 import org.apache.iceberg.RowLevelOperationMode;
+import org.apache.iceberg.Snapshot;
 import org.apache.iceberg.Table;
 import org.apache.iceberg.TableProperties;
 import org.apache.iceberg.data.GenericRecord;
 import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
 import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
 import org.apache.iceberg.relocated.com.google.common.util.concurrent.MoreExecutors;
 import org.apache.iceberg.spark.Spark3Util;
+import org.apache.iceberg.spark.SparkSQLProperties;
 import org.apache.spark.sql.Encoders;
+import org.apache.spark.sql.catalyst.analysis.NoSuchTableException;
+import org.apache.spark.sql.internal.SQLConf;
 import org.assertj.core.api.Assertions;
 import org.junit.Assert;
 import org.junit.Assume;
@@ -143,4 +148,32 @@ public class TestCopyOnWriteDelete extends TestDelete {
     executorService.shutdown();
     Assert.assertTrue("Timeout", executorService.awaitTermination(2, TimeUnit.MINUTES));
   }
+
+  @Test
+  public void testRuntimeFilteringWithPreservedDataGrouping() throws NoSuchTableException {
+    createAndInitPartitionedTable();
+
+    append(new Employee(1, "hr"), new Employee(3, "hr"));
+    append(new Employee(1, "hardware"), new Employee(2, "hardware"));
+
+    Map<String, String> sqlConf =
+        ImmutableMap.of(
+            SQLConf.V2_BUCKETING_ENABLED().key(),
+            "true",
+            SparkSQLProperties.PRESERVE_DATA_GROUPING,
+            "true");
+
+    withSQLConf(sqlConf, () -> sql("DELETE FROM %s WHERE id = 2", tableName));
+
+    Table table = validationCatalog.loadTable(tableIdent);
+    Assert.assertEquals("Should have 3 snapshots", 3, Iterables.size(table.snapshots()));
+
+    Snapshot currentSnapshot = table.currentSnapshot();
+    validateCopyOnWrite(currentSnapshot, "1", "1", "1");
+
+    assertEquals(
+        "Should have expected rows",
+        ImmutableList.of(row(1, "hardware"), row(1, "hr"), row(3, "hr")),
+        sql("SELECT * FROM %s ORDER BY id, dep", tableName));
+  }
 }
diff --git a/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestCopyOnWriteMerge.java b/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestCopyOnWriteMerge.java
index ebb445d255..6a50937c88 100644
--- a/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestCopyOnWriteMerge.java
+++ b/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestCopyOnWriteMerge.java
@@ -32,14 +32,18 @@ import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 import org.apache.iceberg.DataFile;
 import org.apache.iceberg.RowLevelOperationMode;
+import org.apache.iceberg.Snapshot;
 import org.apache.iceberg.Table;
 import org.apache.iceberg.TableProperties;
 import org.apache.iceberg.data.GenericRecord;
 import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
 import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
 import org.apache.iceberg.relocated.com.google.common.util.concurrent.MoreExecutors;
 import org.apache.iceberg.spark.Spark3Util;
+import org.apache.iceberg.spark.SparkSQLProperties;
 import org.apache.spark.sql.Encoders;
+import org.apache.spark.sql.internal.SQLConf;
 import org.assertj.core.api.Assertions;
 import org.junit.Assert;
 import org.junit.Assume;
@@ -148,4 +152,45 @@ public class TestCopyOnWriteMerge extends TestMerge {
     executorService.shutdown();
     Assert.assertTrue("Timeout", executorService.awaitTermination(2, TimeUnit.MINUTES));
   }
+
+  @Test
+  public void testRuntimeFilteringWithReportedPartitioning() {
+    createAndInitTable("id INT, dep STRING");
+    sql("ALTER TABLE %s ADD PARTITION FIELD dep", tableName);
+
+    append(tableName, "{ \"id\": 1, \"dep\": \"hr\" }\n" + "{ \"id\": 3, \"dep\": \"hr\" }");
+    append(
+        tableName,
+        "{ \"id\": 1, \"dep\": \"hardware\" }\n" + "{ \"id\": 2, \"dep\": \"hardware\" }");
+
+    createOrReplaceView("source", Collections.singletonList(2), Encoders.INT());
+
+    Map<String, String> sqlConf =
+        ImmutableMap.of(
+            SQLConf.V2_BUCKETING_ENABLED().key(),
+            "true",
+            SparkSQLProperties.PRESERVE_DATA_GROUPING,
+            "true");
+
+    withSQLConf(
+        sqlConf,
+        () ->
+            sql(
+                "MERGE INTO %s t USING source s "
+                    + "ON t.id == s.value "
+                    + "WHEN MATCHED THEN "
+                    + "  UPDATE SET id = -1",
+                tableName));
+
+    Table table = validationCatalog.loadTable(tableIdent);
+    Assert.assertEquals("Should have 3 snapshots", 3, Iterables.size(table.snapshots()));
+
+    Snapshot currentSnapshot = table.currentSnapshot();
+    validateCopyOnWrite(currentSnapshot, "1", "1", "1");
+
+    assertEquals(
+        "Should have expected rows",
+        ImmutableList.of(row(-1, "hardware"), row(1, "hardware"), row(1, "hr"), row(3, "hr")),
+        sql("SELECT * FROM %s ORDER BY id, dep", tableName));
+  }
 }
diff --git a/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestCopyOnWriteUpdate.java b/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestCopyOnWriteUpdate.java
index b8c7bab788..cc17d4aa05 100644
--- a/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestCopyOnWriteUpdate.java
+++ b/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestCopyOnWriteUpdate.java
@@ -31,13 +31,17 @@ import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 import org.apache.iceberg.DataFile;
 import org.apache.iceberg.RowLevelOperationMode;
+import org.apache.iceberg.Snapshot;
 import org.apache.iceberg.Table;
 import org.apache.iceberg.TableProperties;
 import org.apache.iceberg.data.GenericRecord;
 import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
 import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
 import org.apache.iceberg.relocated.com.google.common.util.concurrent.MoreExecutors;
 import org.apache.iceberg.spark.Spark3Util;
+import org.apache.iceberg.spark.SparkSQLProperties;
+import org.apache.spark.sql.internal.SQLConf;
 import org.assertj.core.api.Assertions;
 import org.junit.Assert;
 import org.junit.Assume;
@@ -140,4 +144,35 @@ public class TestCopyOnWriteUpdate extends TestUpdate {
     executorService.shutdown();
     Assert.assertTrue("Timeout", executorService.awaitTermination(2, TimeUnit.MINUTES));
   }
+
+  @Test
+  public void testRuntimeFilteringWithReportedPartitioning() {
+    createAndInitTable("id INT, dep STRING");
+    sql("ALTER TABLE %s ADD PARTITION FIELD dep", tableName);
+
+    append(tableName, "{ \"id\": 1, \"dep\": \"hr\" }\n" + "{ \"id\": 3, \"dep\": \"hr\" }");
+    append(
+        tableName,
+        "{ \"id\": 1, \"dep\": \"hardware\" }\n" + "{ \"id\": 2, \"dep\": \"hardware\" }");
+
+    Map<String, String> sqlConf =
+        ImmutableMap.of(
+            SQLConf.V2_BUCKETING_ENABLED().key(),
+            "true",
+            SparkSQLProperties.PRESERVE_DATA_GROUPING,
+            "true");
+
+    withSQLConf(sqlConf, () -> sql("UPDATE %s SET id = -1 WHERE id = 2", tableName));
+
+    Table table = validationCatalog.loadTable(tableIdent);
+    Assert.assertEquals("Should have 3 snapshots", 3, Iterables.size(table.snapshots()));
+
+    Snapshot currentSnapshot = table.currentSnapshot();
+    validateCopyOnWrite(currentSnapshot, "1", "1", "1");
+
+    assertEquals(
+        "Should have expected rows",
+        ImmutableList.of(row(-1, "hardware"), row(1, "hardware"), row(1, "hr"), row(3, "hr")),
+        sql("SELECT * FROM %s ORDER BY id, dep", tableName));
+  }
 }
diff --git a/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestStoragePartitionedJoinsInRowLevelOperations.java b/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestStoragePartitionedJoinsInRowLevelOperations.java
new file mode 100644
index 0000000000..bc81c9ea33
--- /dev/null
+++ b/spark/v3.3/spark-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestStoragePartitionedJoinsInRowLevelOperations.java
@@ -0,0 +1,283 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.extensions;
+
+import static org.apache.iceberg.RowLevelOperationMode.COPY_ON_WRITE;
+import static org.apache.iceberg.RowLevelOperationMode.MERGE_ON_READ;
+
+import java.util.Map;
+import org.apache.iceberg.RowLevelOperationMode;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.spark.SparkCatalogConfig;
+import org.apache.iceberg.spark.SparkSQLProperties;
+import org.apache.spark.sql.execution.SparkPlan;
+import org.apache.spark.sql.internal.SQLConf;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runners.Parameterized;
+
+public class TestStoragePartitionedJoinsInRowLevelOperations extends SparkExtensionsTestBase {
+
+  private static final String OTHER_TABLE_NAME = "other_table";
+
+  // open file cost and split size are set as 16 MB to produce a split per file
+  private static final Map<String, String> COMMON_TABLE_PROPERTIES =
+      ImmutableMap.of(
+          TableProperties.FORMAT_VERSION,
+          "2",
+          TableProperties.SPLIT_SIZE,
+          "16777216",
+          TableProperties.SPLIT_OPEN_FILE_COST,
+          "16777216");
+
+  // only v2 bucketing and preserve data grouping properties have to be enabled to trigger SPJ
+  // other properties are only to simplify testing and validation
+  private static final Map<String, String> ENABLED_SPJ_SQL_CONF =
+      ImmutableMap.of(
+          SQLConf.V2_BUCKETING_ENABLED().key(),
+          "true",
+          SQLConf.REQUIRE_ALL_CLUSTER_KEYS_FOR_CO_PARTITION().key(),
+          "false",
+          SQLConf.ADAPTIVE_EXECUTION_ENABLED().key(),
+          "false",
+          SQLConf.AUTO_BROADCASTJOIN_THRESHOLD().key(),
+          "-1",
+          SparkSQLProperties.PRESERVE_DATA_GROUPING,
+          "true");
+
+  @Parameterized.Parameters(name = "catalogName = {0}, implementation = {1}, config = {2}")
+  public static Object[][] parameters() {
+    return new Object[][] {
+      {
+        SparkCatalogConfig.HIVE.catalogName(),
+        SparkCatalogConfig.HIVE.implementation(),
+        SparkCatalogConfig.HIVE.properties()
+      }
+    };
+  }
+
+  public TestStoragePartitionedJoinsInRowLevelOperations(
+      String catalogName, String implementation, Map<String, String> config) {
+    super(catalogName, implementation, config);
+  }
+
+  @After
+  public void removeTables() {
+    sql("DROP TABLE IF EXISTS %s", tableName);
+    sql("DROP TABLE IF EXISTS %s", tableName(OTHER_TABLE_NAME));
+  }
+
+  @Test
+  public void testCopyOnWriteDeleteWithoutShuffles() {
+    checkDelete(COPY_ON_WRITE);
+  }
+
+  @Test
+  public void testMergeOnReadDeleteWithoutShuffles() {
+    checkDelete(MERGE_ON_READ);
+  }
+
+  private void checkDelete(RowLevelOperationMode mode) {
+    String createTableStmt =
+        "CREATE TABLE %s (id INT, salary INT, dep STRING)"
+            + "USING iceberg "
+            + "PARTITIONED BY (dep) "
+            + "TBLPROPERTIES (%s)";
+
+    sql(createTableStmt, tableName, tablePropsAsString(COMMON_TABLE_PROPERTIES));
+
+    append(tableName, "{ \"id\": 1, \"salary\": 100, \"dep\": \"hr\" }");
+    append(tableName, "{ \"id\": 2, \"salary\": 200, \"dep\": \"hr\" }");
+    append(tableName, "{ \"id\": 3, \"salary\": 300, \"dep\": \"hr\" }");
+    append(tableName, "{ \"id\": 4, \"salary\": 400, \"dep\": \"hardware\" }");
+
+    sql(createTableStmt, tableName(OTHER_TABLE_NAME), tablePropsAsString(COMMON_TABLE_PROPERTIES));
+
+    append(tableName(OTHER_TABLE_NAME), "{ \"id\": 1, \"salary\": 110, \"dep\": \"hr\" }");
+    append(tableName(OTHER_TABLE_NAME), "{ \"id\": 5, \"salary\": 500, \"dep\": \"hr\" }");
+
+    Map<String, String> deleteTableProps =
+        ImmutableMap.of(
+            TableProperties.DELETE_MODE,
+            mode.modeName(),
+            TableProperties.DELETE_DISTRIBUTION_MODE,
+            "none");
+
+    sql("ALTER TABLE %s SET TBLPROPERTIES(%s)", tableName, tablePropsAsString(deleteTableProps));
+
+    withSQLConf(
+        ENABLED_SPJ_SQL_CONF,
+        () -> {
+          SparkPlan plan =
+              executeAndKeepPlan(
+                  "DELETE FROM %s t WHERE "
+                      + "EXISTS (SELECT 1 FROM %s s WHERE t.id = s.id AND t.dep = s.dep) AND "
+                      + "dep = 'hr'",
+                  tableName, tableName(OTHER_TABLE_NAME));
+          String planAsString = plan.toString();
+          Assert.assertFalse("Should be no shuffles with SPJ", planAsString.contains("Exchange"));
+        });
+
+    ImmutableList<Object[]> expectedRows =
+        ImmutableList.of(
+            row(2, 200, "hr"), // remaining
+            row(3, 300, "hr"), // remaining
+            row(4, 400, "hardware")); // remaining
+
+    assertEquals(
+        "Should have expected rows",
+        expectedRows,
+        sql("SELECT * FROM %s ORDER BY id, salary", tableName));
+  }
+
+  @Test
+  public void testCopyOnWriteUpdateWithoutShuffles() {
+    checkUpdate(COPY_ON_WRITE);
+  }
+
+  @Test
+  public void testMergeOnReadUpdateWithoutShuffles() {
+    checkUpdate(MERGE_ON_READ);
+  }
+
+  private void checkUpdate(RowLevelOperationMode mode) {
+    String createTableStmt =
+        "CREATE TABLE %s (id INT, salary INT, dep STRING)"
+            + "USING iceberg "
+            + "PARTITIONED BY (dep) "
+            + "TBLPROPERTIES (%s)";
+
+    sql(createTableStmt, tableName, tablePropsAsString(COMMON_TABLE_PROPERTIES));
+
+    append(tableName, "{ \"id\": 1, \"salary\": 100, \"dep\": \"hr\" }");
+    append(tableName, "{ \"id\": 2, \"salary\": 200, \"dep\": \"hr\" }");
+    append(tableName, "{ \"id\": 3, \"salary\": 300, \"dep\": \"hr\" }");
+    append(tableName, "{ \"id\": 4, \"salary\": 400, \"dep\": \"hardware\" }");
+
+    sql(createTableStmt, tableName(OTHER_TABLE_NAME), tablePropsAsString(COMMON_TABLE_PROPERTIES));
+
+    append(tableName(OTHER_TABLE_NAME), "{ \"id\": 1, \"salary\": 110, \"dep\": \"hr\" }");
+    append(tableName(OTHER_TABLE_NAME), "{ \"id\": 5, \"salary\": 500, \"dep\": \"hr\" }");
+
+    Map<String, String> updateTableProps =
+        ImmutableMap.of(
+            TableProperties.UPDATE_MODE,
+            mode.modeName(),
+            TableProperties.UPDATE_DISTRIBUTION_MODE,
+            "none");
+
+    sql("ALTER TABLE %s SET TBLPROPERTIES(%s)", tableName, tablePropsAsString(updateTableProps));
+
+    withSQLConf(
+        ENABLED_SPJ_SQL_CONF,
+        () -> {
+          SparkPlan plan =
+              executeAndKeepPlan(
+                  "UPDATE %s t SET salary = -1 WHERE "
+                      + "EXISTS (SELECT 1 FROM %s s WHERE t.id = s.id AND t.dep = s.dep) AND "
+                      + "dep = 'hr'",
+                  tableName, tableName(OTHER_TABLE_NAME));
+          String planAsString = plan.toString();
+          Assert.assertFalse("Should be no shuffles with SPJ", planAsString.contains("Exchange"));
+        });
+
+    ImmutableList<Object[]> expectedRows =
+        ImmutableList.of(
+            row(1, -1, "hr"), // updated
+            row(2, 200, "hr"), // existing
+            row(3, 300, "hr"), // existing
+            row(4, 400, "hardware")); // existing
+
+    assertEquals(
+        "Should have expected rows",
+        expectedRows,
+        sql("SELECT * FROM %s ORDER BY id, salary", tableName));
+  }
+
+  @Test
+  public void testCopyOnWriteMergeWithoutShuffles() {
+    checkMerge(COPY_ON_WRITE);
+  }
+
+  @Test
+  public void testMergeOnReadMergeWithoutShuffles() {
+    checkMerge(MERGE_ON_READ);
+  }
+
+  private void checkMerge(RowLevelOperationMode mode) {
+    String createTableStmt =
+        "CREATE TABLE %s (id INT, salary INT, dep STRING)"
+            + "USING iceberg "
+            + "PARTITIONED BY (dep) "
+            + "TBLPROPERTIES (%s)";
+
+    sql(createTableStmt, tableName, tablePropsAsString(COMMON_TABLE_PROPERTIES));
+
+    append(tableName, "{ \"id\": 1, \"salary\": 100, \"dep\": \"hr\" }");
+    append(tableName, "{ \"id\": 2, \"salary\": 200, \"dep\": \"hr\" }");
+    append(tableName, "{ \"id\": 3, \"salary\": 300, \"dep\": \"hr\" }");
+    append(tableName, "{ \"id\": 4, \"salary\": 400, \"dep\": \"hardware\" }");
+
+    sql(createTableStmt, tableName(OTHER_TABLE_NAME), tablePropsAsString(COMMON_TABLE_PROPERTIES));
+
+    append(tableName(OTHER_TABLE_NAME), "{ \"id\": 1, \"salary\": 110, \"dep\": \"hr\" }");
+    append(tableName(OTHER_TABLE_NAME), "{ \"id\": 5, \"salary\": 500, \"dep\": \"hr\" }");
+
+    Map<String, String> mergeTableProps =
+        ImmutableMap.of(
+            TableProperties.MERGE_MODE,
+            mode.modeName(),
+            TableProperties.MERGE_DISTRIBUTION_MODE,
+            "none");
+
+    sql("ALTER TABLE %s SET TBLPROPERTIES(%s)", tableName, tablePropsAsString(mergeTableProps));
+
+    withSQLConf(
+        ENABLED_SPJ_SQL_CONF,
+        () -> {
+          SparkPlan plan =
+              executeAndKeepPlan(
+                  "MERGE INTO %s AS t USING %s AS s "
+                      + "ON t.id = s.id AND t.dep = s.dep AND t.dep = 'hr'"
+                      + "WHEN MATCHED THEN "
+                      + "  UPDATE SET t.salary = s.salary "
+                      + "WHEN NOT MATCHED THEN "
+                      + "  INSERT *",
+                  tableName, tableName(OTHER_TABLE_NAME));
+          String planAsString = plan.toString();
+          Assert.assertFalse("Should be no shuffles with SPJ", planAsString.contains("Exchange"));
+        });
+
+    ImmutableList<Object[]> expectedRows =
+        ImmutableList.of(
+            row(1, 110, "hr"), // updated
+            row(2, 200, "hr"), // existing
+            row(3, 300, "hr"), // existing
+            row(4, 400, "hardware"), // existing
+            row(5, 500, "hr")); // new
+
+    assertEquals(
+        "Should have expected rows",
+        expectedRows,
+        sql("SELECT * FROM %s ORDER BY id, salary", tableName));
+  }
+}
diff --git a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/Spark3Util.java b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/Spark3Util.java
index 94a86edd38..ec3bacd01c 100644
--- a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/Spark3Util.java
+++ b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/Spark3Util.java
@@ -30,6 +30,7 @@ import java.util.stream.Stream;
 import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.Path;
 import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.PartitionField;
 import org.apache.iceberg.PartitionSpec;
 import org.apache.iceberg.Schema;
 import org.apache.iceberg.TableOperations;
@@ -255,6 +256,21 @@ public class Spark3Util {
     return sparkTable.table();
   }
 
+  public static Transform[] toTransforms(Schema schema, List<PartitionField> fields) {
+    SpecTransformToSparkTransform visitor = new SpecTransformToSparkTransform(schema);
+
+    List<Transform> transforms = Lists.newArrayList();
+
+    for (PartitionField field : fields) {
+      Transform transform = PartitionSpecVisitor.visit(schema, field, visitor);
+      if (transform != null) {
+        transforms.add(transform);
+      }
+    }
+
+    return transforms.toArray(new Transform[0]);
+  }
+
   /**
    * Converts a PartitionSpec to Spark transforms.
    *
@@ -262,67 +278,68 @@ public class Spark3Util {
    * @return an array of Transforms
    */
   public static Transform[] toTransforms(PartitionSpec spec) {
-    Map<Integer, String> quotedNameById = SparkSchemaUtil.indexQuotedNameById(spec.schema());
-    List<Transform> transforms =
-        PartitionSpecVisitor.visit(
-            spec,
-            new PartitionSpecVisitor<Transform>() {
-              @Override
-              public Transform identity(String sourceName, int sourceId) {
-                return Expressions.identity(quotedName(sourceId));
-              }
+    SpecTransformToSparkTransform visitor = new SpecTransformToSparkTransform(spec.schema());
+    List<Transform> transforms = PartitionSpecVisitor.visit(spec, visitor);
+    return transforms.stream().filter(Objects::nonNull).toArray(Transform[]::new);
+  }
 
-              @Override
-              public Transform bucket(String sourceName, int sourceId, int numBuckets) {
-                return Expressions.bucket(numBuckets, quotedName(sourceId));
-              }
+  private static class SpecTransformToSparkTransform implements PartitionSpecVisitor<Transform> {
+    private final Map<Integer, String> quotedNameById;
 
-              @Override
-              public Transform truncate(String sourceName, int sourceId, int width) {
-                return Expressions.apply(
-                    "truncate",
-                    Expressions.column(quotedName(sourceId)),
-                    Expressions.literal(width));
-              }
+    SpecTransformToSparkTransform(Schema schema) {
+      this.quotedNameById = SparkSchemaUtil.indexQuotedNameById(schema);
+    }
 
-              @Override
-              public Transform year(String sourceName, int sourceId) {
-                return Expressions.years(quotedName(sourceId));
-              }
+    @Override
+    public Transform identity(String sourceName, int sourceId) {
+      return Expressions.identity(quotedName(sourceId));
+    }
 
-              @Override
-              public Transform month(String sourceName, int sourceId) {
-                return Expressions.months(quotedName(sourceId));
-              }
+    @Override
+    public Transform bucket(String sourceName, int sourceId, int numBuckets) {
+      return Expressions.bucket(numBuckets, quotedName(sourceId));
+    }
 
-              @Override
-              public Transform day(String sourceName, int sourceId) {
-                return Expressions.days(quotedName(sourceId));
-              }
+    @Override
+    public Transform truncate(String sourceName, int sourceId, int width) {
+      NamedReference column = Expressions.column(quotedName(sourceId));
+      return Expressions.apply("truncate", Expressions.literal(width), column);
+    }
 
-              @Override
-              public Transform hour(String sourceName, int sourceId) {
-                return Expressions.hours(quotedName(sourceId));
-              }
+    @Override
+    public Transform year(String sourceName, int sourceId) {
+      return Expressions.years(quotedName(sourceId));
+    }
 
-              @Override
-              public Transform alwaysNull(int fieldId, String sourceName, int sourceId) {
-                // do nothing for alwaysNull, it doesn't need to be converted to a transform
-                return null;
-              }
+    @Override
+    public Transform month(String sourceName, int sourceId) {
+      return Expressions.months(quotedName(sourceId));
+    }
 
-              @Override
-              public Transform unknown(
-                  int fieldId, String sourceName, int sourceId, String transform) {
-                return Expressions.apply(transform, Expressions.column(quotedName(sourceId)));
-              }
+    @Override
+    public Transform day(String sourceName, int sourceId) {
+      return Expressions.days(quotedName(sourceId));
+    }
 
-              private String quotedName(int id) {
-                return quotedNameById.get(id);
-              }
-            });
+    @Override
+    public Transform hour(String sourceName, int sourceId) {
+      return Expressions.hours(quotedName(sourceId));
+    }
 
-    return transforms.stream().filter(Objects::nonNull).toArray(Transform[]::new);
+    @Override
+    public Transform alwaysNull(int fieldId, String sourceName, int sourceId) {
+      // do nothing for alwaysNull, it doesn't need to be converted to a transform
+      return null;
+    }
+
+    @Override
+    public Transform unknown(int fieldId, String sourceName, int sourceId, String transform) {
+      return Expressions.apply(transform, Expressions.column(quotedName(sourceId)));
+    }
+
+    private String quotedName(int id) {
+      return quotedNameById.get(id);
+    }
   }
 
   public static NamedReference toNamedReference(String name) {
@@ -473,6 +490,10 @@ public class Spark3Util {
     return null;
   }
 
+  public static String describe(List<org.apache.iceberg.expressions.Expression> exprs) {
+    return exprs.stream().map(Spark3Util::describe).collect(Collectors.joining(", "));
+  }
+
   public static String describe(org.apache.iceberg.expressions.Expression expr) {
     return ExpressionVisitors.visit(expr, DescribeExpressionVisitor.INSTANCE);
   }
diff --git a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/SparkReadConf.java b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/SparkReadConf.java
index 5a5c72197c..f3b78700ec 100644
--- a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/SparkReadConf.java
+++ b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/SparkReadConf.java
@@ -235,4 +235,12 @@ public class SparkReadConf {
   public Long endTimestamp() {
     return confParser.longConf().option(SparkReadOptions.END_TIMESTAMP).parseOptional();
   }
+
+  public boolean preserveDataGrouping() {
+    return confParser
+        .booleanConf()
+        .sessionConf(SparkSQLProperties.PRESERVE_DATA_GROUPING)
+        .defaultValue(SparkSQLProperties.PRESERVE_DATA_GROUPING_DEFAULT)
+        .parse();
+  }
 }
diff --git a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/SparkSQLProperties.java b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/SparkSQLProperties.java
index fa8bd719f3..5b009c65b7 100644
--- a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/SparkSQLProperties.java
+++ b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/SparkSQLProperties.java
@@ -42,4 +42,9 @@ public class SparkSQLProperties {
   // Controls whether to check the order of fields during writes
   public static final String CHECK_ORDERING = "spark.sql.iceberg.check-ordering";
   public static final boolean CHECK_ORDERING_DEFAULT = true;
+
+  // Controls whether to preserve the existing grouping of data while planning splits
+  public static final String PRESERVE_DATA_GROUPING =
+      "spark.sql.iceberg.planning.preserve-data-grouping";
+  public static final boolean PRESERVE_DATA_GROUPING_DEFAULT = false;
 }
diff --git a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatch.java b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatch.java
index 0593fa5a0b..394a920a2d 100644
--- a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatch.java
+++ b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatch.java
@@ -28,6 +28,7 @@ import org.apache.iceberg.Schema;
 import org.apache.iceberg.SchemaParser;
 import org.apache.iceberg.Table;
 import org.apache.iceberg.spark.SparkReadConf;
+import org.apache.iceberg.types.Types;
 import org.apache.iceberg.util.Tasks;
 import org.apache.iceberg.util.ThreadPools;
 import org.apache.spark.api.java.JavaSparkContext;
@@ -41,6 +42,7 @@ class SparkBatch implements Batch {
   private final JavaSparkContext sparkContext;
   private final Table table;
   private final SparkReadConf readConf;
+  private final Types.StructType groupingKeyType;
   private final List<? extends ScanTaskGroup<?>> taskGroups;
   private final Schema expectedSchema;
   private final boolean caseSensitive;
@@ -51,12 +53,14 @@ class SparkBatch implements Batch {
       JavaSparkContext sparkContext,
       Table table,
       SparkReadConf readConf,
+      Types.StructType groupingKeyType,
       List<? extends ScanTaskGroup<?>> taskGroups,
       Schema expectedSchema,
       int scanHashCode) {
     this.sparkContext = sparkContext;
     this.table = table;
     this.readConf = readConf;
+    this.groupingKeyType = groupingKeyType;
     this.taskGroups = taskGroups;
     this.expectedSchema = expectedSchema;
     this.caseSensitive = readConf.caseSensitive();
@@ -80,6 +84,7 @@ class SparkBatch implements Batch {
             index ->
                 partitions[index] =
                     new SparkInputPartition(
+                        groupingKeyType,
                         taskGroups.get(index),
                         tableBroadcast,
                         expectedSchemaString,
diff --git a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatchQueryScan.java b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatchQueryScan.java
index 19bb551426..138eff4eb6 100644
--- a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatchQueryScan.java
+++ b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatchQueryScan.java
@@ -18,9 +18,6 @@
  */
 package org.apache.iceberg.spark.source;
 
-import java.io.IOException;
-import java.io.UncheckedIOException;
-import java.util.Collections;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
@@ -42,7 +39,6 @@ import org.apache.iceberg.expressions.Expression;
 import org.apache.iceberg.expressions.ExpressionUtil;
 import org.apache.iceberg.expressions.Expressions;
 import org.apache.iceberg.expressions.Projections;
-import org.apache.iceberg.io.CloseableIterable;
 import org.apache.iceberg.relocated.com.google.common.collect.Lists;
 import org.apache.iceberg.relocated.com.google.common.collect.Maps;
 import org.apache.iceberg.relocated.com.google.common.collect.Sets;
@@ -51,7 +47,6 @@ import org.apache.iceberg.spark.SparkFilters;
 import org.apache.iceberg.spark.SparkReadConf;
 import org.apache.iceberg.spark.SparkSchemaUtil;
 import org.apache.iceberg.util.SnapshotUtil;
-import org.apache.iceberg.util.TableScanUtil;
 import org.apache.spark.sql.SparkSession;
 import org.apache.spark.sql.connector.expressions.NamedReference;
 import org.apache.spark.sql.connector.read.Statistics;
@@ -60,11 +55,11 @@ import org.apache.spark.sql.sources.Filter;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-class SparkBatchQueryScan extends SparkScan implements SupportsRuntimeFiltering {
+class SparkBatchQueryScan extends SparkPartitioningAwareScan<PartitionScanTask>
+    implements SupportsRuntimeFiltering {
 
   private static final Logger LOG = LoggerFactory.getLogger(SparkBatchQueryScan.class);
 
-  private final Scan<?, ? extends ScanTask, ? extends ScanTaskGroup<?>> scan;
   private final Long snapshotId;
   private final Long startSnapshotId;
   private final Long endSnapshotId;
@@ -73,10 +68,6 @@ class SparkBatchQueryScan extends SparkScan implements SupportsRuntimeFiltering
   private final String tag;
   private final List<Expression> runtimeFilterExpressions;
 
-  private Set<Integer> specIds = null; // lazy cache of scanned spec IDs
-  private List<PartitionScanTask> tasks = null; // lazy cache of uncombined tasks
-  private List<ScanTaskGroup<PartitionScanTask>> taskGroups = null; // lazy cache of task groups
-
   SparkBatchQueryScan(
       SparkSession spark,
       Table table,
@@ -85,9 +76,8 @@ class SparkBatchQueryScan extends SparkScan implements SupportsRuntimeFiltering
       Schema expectedSchema,
       List<Expression> filters) {
 
-    super(spark, table, readConf, expectedSchema, filters);
+    super(spark, table, scan, readConf, expectedSchema, filters);
 
-    this.scan = scan;
     this.snapshotId = readConf.snapshotId();
     this.startSnapshotId = readConf.startSnapshotId();
     this.endSnapshotId = readConf.endSnapshotId();
@@ -95,72 +85,22 @@ class SparkBatchQueryScan extends SparkScan implements SupportsRuntimeFiltering
     this.branch = readConf.branch();
     this.tag = readConf.tag();
     this.runtimeFilterExpressions = Lists.newArrayList();
-
-    if (scan == null) {
-      this.specIds = Collections.emptySet();
-      this.tasks = Collections.emptyList();
-      this.taskGroups = Collections.emptyList();
-    }
   }
 
   Long snapshotId() {
     return snapshotId;
   }
 
-  private Set<Integer> specIds() {
-    if (specIds == null) {
-      Set<Integer> specIdSet = Sets.newHashSet();
-      for (PartitionScanTask task : tasks()) {
-        specIdSet.add(task.spec().specId());
-      }
-      this.specIds = specIdSet;
-    }
-
-    return specIds;
-  }
-
-  private List<PartitionScanTask> tasks() {
-    if (tasks == null) {
-      try (CloseableIterable<? extends ScanTask> taskIterable = scan.planFiles()) {
-        List<PartitionScanTask> partitionScanTasks = Lists.newArrayList();
-        for (ScanTask task : taskIterable) {
-          ValidationException.check(
-              task instanceof PartitionScanTask,
-              "Unsupported task type, expected a subtype of PartitionScanTask: %",
-              task.getClass().getName());
-
-          partitionScanTasks.add((PartitionScanTask) task);
-        }
-        this.tasks = partitionScanTasks;
-      } catch (IOException e) {
-        throw new UncheckedIOException("Failed to close scan: " + scan, e);
-      }
-    }
-
-    return tasks;
-  }
-
   @Override
-  protected List<ScanTaskGroup<PartitionScanTask>> taskGroups() {
-    if (taskGroups == null) {
-      CloseableIterable<ScanTaskGroup<PartitionScanTask>> plannedTaskGroups =
-          TableScanUtil.planTaskGroups(
-              CloseableIterable.withNoopClose(tasks()),
-              scan.targetSplitSize(),
-              scan.splitLookback(),
-              scan.splitOpenFileCost());
-      taskGroups = Lists.newArrayList(plannedTaskGroups);
-    }
-
-    return taskGroups;
+  protected Class<PartitionScanTask> taskJavaClass() {
+    return PartitionScanTask.class;
   }
 
   @Override
   public NamedReference[] filterAttributes() {
     Set<Integer> partitionFieldSourceIds = Sets.newHashSet();
 
-    for (Integer specId : specIds()) {
-      PartitionSpec spec = table().specs().get(specId);
+    for (PartitionSpec spec : specs()) {
       for (PartitionField field : spec.fields()) {
         partitionFieldSourceIds.add(field.sourceId());
       }
@@ -185,12 +125,11 @@ class SparkBatchQueryScan extends SparkScan implements SupportsRuntimeFiltering
     if (runtimeFilterExpr != Expressions.alwaysTrue()) {
       Map<Integer, Evaluator> evaluatorsBySpecId = Maps.newHashMap();
 
-      for (Integer specId : specIds()) {
-        PartitionSpec spec = table().specs().get(specId);
+      for (PartitionSpec spec : specs()) {
         Expression inclusiveExpr =
             Projections.inclusive(spec, caseSensitive()).project(runtimeFilterExpr);
         Evaluator inclusive = new Evaluator(spec.partitionType(), inclusiveExpr);
-        evaluatorsBySpecId.put(specId, inclusive);
+        evaluatorsBySpecId.put(spec.specId(), inclusive);
       }
 
       LOG.info(
@@ -215,9 +154,7 @@ class SparkBatchQueryScan extends SparkScan implements SupportsRuntimeFiltering
 
       // don't invalidate tasks if the runtime filter had no effect to avoid planning splits again
       if (filteredTasks.size() < tasks().size()) {
-        this.specIds = null;
-        this.tasks = filteredTasks;
-        this.taskGroups = null;
+        resetTasks(filteredTasks);
       }
 
       // save the evaluated filter for equals/hashCode
@@ -249,7 +186,7 @@ class SparkBatchQueryScan extends SparkScan implements SupportsRuntimeFiltering
 
   @Override
   public Statistics estimateStatistics() {
-    if (scan == null) {
+    if (scan() == null) {
       return estimateStatistics(null);
 
     } else if (snapshotId != null) {
diff --git a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkChangelogScan.java b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkChangelogScan.java
index 649238e1e5..54fdd186d4 100644
--- a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkChangelogScan.java
+++ b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkChangelogScan.java
@@ -23,7 +23,6 @@ import java.io.UncheckedIOException;
 import java.util.Collections;
 import java.util.List;
 import java.util.Objects;
-import java.util.stream.Collectors;
 import org.apache.iceberg.ChangelogScanTask;
 import org.apache.iceberg.IncrementalChangelogScan;
 import org.apache.iceberg.ScanTaskGroup;
@@ -37,6 +36,7 @@ import org.apache.iceberg.spark.Spark3Util;
 import org.apache.iceberg.spark.SparkReadConf;
 import org.apache.iceberg.spark.SparkSchemaUtil;
 import org.apache.iceberg.spark.SparkUtil;
+import org.apache.iceberg.types.Types;
 import org.apache.spark.api.java.JavaSparkContext;
 import org.apache.spark.sql.SparkSession;
 import org.apache.spark.sql.connector.read.Batch;
@@ -47,6 +47,8 @@ import org.apache.spark.sql.types.StructType;
 
 class SparkChangelogScan implements Scan, SupportsReportStatistics {
 
+  private static final Types.StructType EMPTY_GROUPING_KEY_TYPE = Types.StructType.of();
+
   private final JavaSparkContext sparkContext;
   private final Table table;
   private final IncrementalChangelogScan scan;
@@ -104,7 +106,14 @@ class SparkChangelogScan implements Scan, SupportsReportStatistics {
 
   @Override
   public Batch toBatch() {
-    return new SparkBatch(sparkContext, table, readConf, taskGroups(), expectedSchema, hashCode());
+    return new SparkBatch(
+        sparkContext,
+        table,
+        readConf,
+        EMPTY_GROUPING_KEY_TYPE,
+        taskGroups(),
+        expectedSchema,
+        hashCode());
   }
 
   private List<ScanTaskGroup<ChangelogScanTask>> taskGroups() {
@@ -123,18 +132,18 @@ class SparkChangelogScan implements Scan, SupportsReportStatistics {
   public String description() {
     return String.format(
         "%s [fromSnapshotId=%d, toSnapshotId=%d, filters=%s]",
-        table, startSnapshotId, endSnapshotId, filtersAsString());
+        table, startSnapshotId, endSnapshotId, Spark3Util.describe(filters));
   }
 
   @Override
   public String toString() {
     return String.format(
         "IcebergChangelogScan(table=%s, type=%s, fromSnapshotId=%d, toSnapshotId=%d, filters=%s)",
-        table, expectedSchema.asStruct(), startSnapshotId, endSnapshotId, filtersAsString());
-  }
-
-  private String filtersAsString() {
-    return filters.stream().map(Spark3Util::describe).collect(Collectors.joining(", "));
+        table,
+        expectedSchema.asStruct(),
+        startSnapshotId,
+        endSnapshotId,
+        Spark3Util.describe(filters));
   }
 
   @Override
diff --git a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkCopyOnWriteScan.java b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkCopyOnWriteScan.java
index 0431f904e7..71a28c3a78 100644
--- a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkCopyOnWriteScan.java
+++ b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkCopyOnWriteScan.java
@@ -18,27 +18,21 @@
  */
 package org.apache.iceberg.spark.source;
 
-import java.io.IOException;
 import java.util.Collections;
 import java.util.List;
 import java.util.Objects;
 import java.util.Set;
 import java.util.stream.Collectors;
-import org.apache.iceberg.CombinedScanTask;
+import org.apache.iceberg.BatchScan;
 import org.apache.iceberg.FileScanTask;
 import org.apache.iceberg.MetadataColumns;
 import org.apache.iceberg.Schema;
 import org.apache.iceberg.Snapshot;
 import org.apache.iceberg.Table;
-import org.apache.iceberg.TableScan;
-import org.apache.iceberg.exceptions.RuntimeIOException;
 import org.apache.iceberg.expressions.Expression;
-import org.apache.iceberg.io.CloseableIterable;
 import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
-import org.apache.iceberg.relocated.com.google.common.collect.Lists;
 import org.apache.iceberg.relocated.com.google.common.collect.Sets;
 import org.apache.iceberg.spark.SparkReadConf;
-import org.apache.iceberg.util.TableScanUtil;
 import org.apache.spark.sql.SparkSession;
 import org.apache.spark.sql.connector.expressions.Expressions;
 import org.apache.spark.sql.connector.expressions.NamedReference;
@@ -47,14 +41,10 @@ import org.apache.spark.sql.connector.read.SupportsRuntimeFiltering;
 import org.apache.spark.sql.sources.Filter;
 import org.apache.spark.sql.sources.In;
 
-class SparkCopyOnWriteScan extends SparkScan implements SupportsRuntimeFiltering {
+class SparkCopyOnWriteScan extends SparkPartitioningAwareScan<FileScanTask>
+    implements SupportsRuntimeFiltering {
 
-  private final TableScan scan;
   private final Snapshot snapshot;
-
-  // lazy variables
-  private List<FileScanTask> files = null; // lazy cache of files
-  private List<CombinedScanTask> tasks = null; // lazy cache of tasks
   private Set<String> filteredLocations = null;
 
   SparkCopyOnWriteScan(
@@ -69,20 +59,17 @@ class SparkCopyOnWriteScan extends SparkScan implements SupportsRuntimeFiltering
   SparkCopyOnWriteScan(
       SparkSession spark,
       Table table,
-      TableScan scan,
+      BatchScan scan,
       Snapshot snapshot,
       SparkReadConf readConf,
       Schema expectedSchema,
       List<Expression> filters) {
 
-    super(spark, table, readConf, expectedSchema, filters);
+    super(spark, table, scan, readConf, expectedSchema, filters);
 
-    this.scan = scan;
     this.snapshot = snapshot;
 
     if (scan == null) {
-      this.files = Collections.emptyList();
-      this.tasks = Collections.emptyList();
       this.filteredLocations = Collections.emptySet();
     }
   }
@@ -91,6 +78,11 @@ class SparkCopyOnWriteScan extends SparkScan implements SupportsRuntimeFiltering
     return snapshot != null ? snapshot.snapshotId() : null;
   }
 
+  @Override
+  protected Class<FileScanTask> taskJavaClass() {
+    return FileScanTask.class;
+  }
+
   @Override
   public Statistics estimateStatistics() {
     return estimateStatistics(snapshot);
@@ -126,45 +118,17 @@ class SparkCopyOnWriteScan extends SparkScan implements SupportsRuntimeFiltering
         // as such cases are rewritten using UNION and the same scan on both sides
         // so filter files only if it is beneficial
         if (filteredLocations == null || fileLocations.size() < filteredLocations.size()) {
-          this.tasks = null;
           this.filteredLocations = fileLocations;
-          this.files =
-              files().stream()
+          List<FileScanTask> filteredTasks =
+              tasks().stream()
                   .filter(file -> fileLocations.contains(file.file().path().toString()))
                   .collect(Collectors.toList());
+          resetTasks(filteredTasks);
         }
       }
     }
   }
 
-  // should be accessible to the write
-  synchronized List<FileScanTask> files() {
-    if (files == null) {
-      try (CloseableIterable<FileScanTask> filesIterable = scan.planFiles()) {
-        this.files = Lists.newArrayList(filesIterable);
-      } catch (IOException e) {
-        throw new RuntimeIOException(e, "Failed to close table scan: %s", scan);
-      }
-    }
-
-    return files;
-  }
-
-  @Override
-  protected synchronized List<CombinedScanTask> taskGroups() {
-    if (tasks == null) {
-      CloseableIterable<FileScanTask> splitFiles =
-          TableScanUtil.splitFiles(
-              CloseableIterable.withNoopClose(files()), scan.targetSplitSize());
-      CloseableIterable<CombinedScanTask> scanTasks =
-          TableScanUtil.planTasks(
-              splitFiles, scan.targetSplitSize(), scan.splitLookback(), scan.splitOpenFileCost());
-      tasks = Lists.newArrayList(scanTasks);
-    }
-
-    return tasks;
-  }
-
   @Override
   public boolean equals(Object o) {
     if (this == o) {
diff --git a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkInputPartition.java b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkInputPartition.java
index 8ea89e8a34..e4b5f63bd9 100644
--- a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkInputPartition.java
+++ b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkInputPartition.java
@@ -26,10 +26,14 @@ import org.apache.iceberg.SchemaParser;
 import org.apache.iceberg.Table;
 import org.apache.iceberg.hadoop.HadoopInputFile;
 import org.apache.iceberg.hadoop.Util;
+import org.apache.iceberg.types.Types;
 import org.apache.spark.broadcast.Broadcast;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.read.HasPartitionKey;
 import org.apache.spark.sql.connector.read.InputPartition;
 
-class SparkInputPartition implements InputPartition, Serializable {
+class SparkInputPartition implements InputPartition, HasPartitionKey, Serializable {
+  private final Types.StructType groupingKeyType;
   private final ScanTaskGroup<?> taskGroup;
   private final Broadcast<Table> tableBroadcast;
   private final String expectedSchemaString;
@@ -39,11 +43,13 @@ class SparkInputPartition implements InputPartition, Serializable {
   private transient String[] preferredLocations = null;
 
   SparkInputPartition(
+      Types.StructType groupingKeyType,
       ScanTaskGroup<?> taskGroup,
       Broadcast<Table> tableBroadcast,
       String expectedSchemaString,
       boolean caseSensitive,
       boolean localityPreferred) {
+    this.groupingKeyType = groupingKeyType;
     this.taskGroup = taskGroup;
     this.tableBroadcast = tableBroadcast;
     this.expectedSchemaString = expectedSchemaString;
@@ -61,6 +67,11 @@ class SparkInputPartition implements InputPartition, Serializable {
     return preferredLocations;
   }
 
+  @Override
+  public InternalRow partitionKey() {
+    return new StructInternalRow(groupingKeyType).setStruct(taskGroup.groupingKey());
+  }
+
   @SuppressWarnings("unchecked")
   public <T extends ScanTask> ScanTaskGroup<T> taskGroup() {
     return (ScanTaskGroup<T>) taskGroup;
diff --git a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkMicroBatchStream.java b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkMicroBatchStream.java
index 822464f37e..e69557f193 100644
--- a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkMicroBatchStream.java
+++ b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkMicroBatchStream.java
@@ -47,6 +47,7 @@ import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
 import org.apache.iceberg.relocated.com.google.common.collect.Lists;
 import org.apache.iceberg.spark.SparkReadConf;
 import org.apache.iceberg.spark.SparkReadOptions;
+import org.apache.iceberg.types.Types;
 import org.apache.iceberg.util.PropertyUtil;
 import org.apache.iceberg.util.SnapshotUtil;
 import org.apache.iceberg.util.TableScanUtil;
@@ -64,6 +65,7 @@ import org.slf4j.LoggerFactory;
 public class SparkMicroBatchStream implements MicroBatchStream {
   private static final Joiner SLASH = Joiner.on("/");
   private static final Logger LOG = LoggerFactory.getLogger(SparkMicroBatchStream.class);
+  private static final Types.StructType EMPTY_GROUPING_KEY_TYPE = Types.StructType.of();
 
   private final Table table;
   private final boolean caseSensitive;
@@ -160,6 +162,7 @@ public class SparkMicroBatchStream implements MicroBatchStream {
             index ->
                 partitions[index] =
                     new SparkInputPartition(
+                        EMPTY_GROUPING_KEY_TYPE,
                         combinedScanTasks.get(index),
                         tableBroadcast,
                         expectedSchema,
diff --git a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkPartitioningAwareScan.java b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkPartitioningAwareScan.java
new file mode 100644
index 0000000000..4b5519f8d2
--- /dev/null
+++ b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkPartitioningAwareScan.java
@@ -0,0 +1,269 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.source;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import org.apache.iceberg.BaseScanTaskGroup;
+import org.apache.iceberg.PartitionField;
+import org.apache.iceberg.PartitionScanTask;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Scan;
+import org.apache.iceberg.ScanTask;
+import org.apache.iceberg.ScanTaskGroup;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.exceptions.ValidationException;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.spark.Spark3Util;
+import org.apache.iceberg.spark.SparkReadConf;
+import org.apache.iceberg.types.Types.StructType;
+import org.apache.iceberg.util.StructLikeSet;
+import org.apache.iceberg.util.TableScanUtil;
+import org.apache.spark.sql.SparkSession;
+import org.apache.spark.sql.connector.expressions.Transform;
+import org.apache.spark.sql.connector.read.SupportsReportPartitioning;
+import org.apache.spark.sql.connector.read.partitioning.KeyGroupedPartitioning;
+import org.apache.spark.sql.connector.read.partitioning.Partitioning;
+import org.apache.spark.sql.connector.read.partitioning.UnknownPartitioning;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+abstract class SparkPartitioningAwareScan<T extends PartitionScanTask> extends SparkScan
+    implements SupportsReportPartitioning {
+
+  private static final Logger LOG = LoggerFactory.getLogger(SparkPartitioningAwareScan.class);
+
+  private final Scan<?, ? extends ScanTask, ? extends ScanTaskGroup<?>> scan;
+  private final boolean preserveDataGrouping;
+
+  private Set<PartitionSpec> specs = null; // lazy cache of scanned specs
+  private List<T> tasks = null; // lazy cache of uncombined tasks
+  private List<ScanTaskGroup<T>> taskGroups = null; // lazy cache of task groups
+  private StructType groupingKeyType = null; // lazy cache of the grouping key type
+  private Transform[] groupingKeyTransforms = null; // lazy cache of grouping key transforms
+  private StructLikeSet groupingKeys = null; // lazy cache of grouping keys
+
+  SparkPartitioningAwareScan(
+      SparkSession spark,
+      Table table,
+      Scan<?, ? extends ScanTask, ? extends ScanTaskGroup<?>> scan,
+      SparkReadConf readConf,
+      Schema expectedSchema,
+      List<Expression> filters) {
+
+    super(spark, table, readConf, expectedSchema, filters);
+
+    this.scan = scan;
+    this.preserveDataGrouping = readConf.preserveDataGrouping();
+
+    if (scan == null) {
+      this.specs = Collections.emptySet();
+      this.tasks = Collections.emptyList();
+      this.taskGroups = Collections.emptyList();
+    }
+  }
+
+  protected abstract Class<T> taskJavaClass();
+
+  protected Scan<?, ? extends ScanTask, ? extends ScanTaskGroup<?>> scan() {
+    return scan;
+  }
+
+  @Override
+  public Partitioning outputPartitioning() {
+    if (groupingKeyType().fields().isEmpty()) {
+      LOG.info("Reporting UnknownPartitioning with {} partition(s)", taskGroups().size());
+      return new UnknownPartitioning(taskGroups().size());
+    } else {
+      LOG.info(
+          "Reporting KeyGroupedPartitioning by {} with {} partition(s)",
+          groupingKeyTransforms(),
+          taskGroups().size());
+      return new KeyGroupedPartitioning(groupingKeyTransforms(), taskGroups().size());
+    }
+  }
+
+  @Override
+  protected StructType groupingKeyType() {
+    if (groupingKeyType == null) {
+      if (preserveDataGrouping) {
+        this.groupingKeyType = computeGroupingKeyType();
+      } else {
+        this.groupingKeyType = StructType.of();
+      }
+    }
+
+    return groupingKeyType;
+  }
+
+  private StructType computeGroupingKeyType() {
+    return org.apache.iceberg.Partitioning.groupingKeyType(expectedSchema(), specs());
+  }
+
+  private Transform[] groupingKeyTransforms() {
+    if (groupingKeyTransforms == null) {
+      Map<Integer, PartitionField> fieldsById = indexFieldsById(specs());
+
+      List<PartitionField> groupingKeyFields =
+          groupingKeyType().fields().stream()
+              .map(field -> fieldsById.get(field.fieldId()))
+              .collect(Collectors.toList());
+
+      this.groupingKeyTransforms = Spark3Util.toTransforms(table().schema(), groupingKeyFields);
+    }
+
+    return groupingKeyTransforms;
+  }
+
+  private Map<Integer, PartitionField> indexFieldsById(Iterable<PartitionSpec> specIterable) {
+    Map<Integer, PartitionField> fieldsById = Maps.newHashMap();
+
+    for (PartitionSpec spec : specIterable) {
+      for (PartitionField field : spec.fields()) {
+        fieldsById.putIfAbsent(field.fieldId(), field);
+      }
+    }
+
+    return fieldsById;
+  }
+
+  protected Set<PartitionSpec> specs() {
+    if (specs == null) {
+      // avoid calling equals/hashCode on specs as those methods are relatively expensive
+      IntStream specIds = tasks().stream().mapToInt(task -> task.spec().specId()).distinct();
+      this.specs = specIds.mapToObj(id -> table().specs().get(id)).collect(Collectors.toSet());
+    }
+
+    return specs;
+  }
+
+  protected synchronized List<T> tasks() {
+    if (tasks == null) {
+      try (CloseableIterable<? extends ScanTask> taskIterable = scan.planFiles()) {
+        List<T> plannedTasks = Lists.newArrayList();
+
+        for (ScanTask task : taskIterable) {
+          ValidationException.check(
+              taskJavaClass().isInstance(task),
+              "Unsupported task type, expected a subtype of %s: %",
+              taskJavaClass().getName(),
+              task.getClass().getName());
+
+          plannedTasks.add(taskJavaClass().cast(task));
+        }
+
+        this.tasks = plannedTasks;
+      } catch (IOException e) {
+        throw new UncheckedIOException("Failed to close scan: " + scan, e);
+      }
+    }
+
+    return tasks;
+  }
+
+  @Override
+  protected synchronized List<ScanTaskGroup<T>> taskGroups() {
+    if (taskGroups == null) {
+      if (groupingKeyType().fields().isEmpty()) {
+        CloseableIterable<ScanTaskGroup<T>> plannedTaskGroups =
+            TableScanUtil.planTaskGroups(
+                CloseableIterable.withNoopClose(tasks()),
+                scan.targetSplitSize(),
+                scan.splitLookback(),
+                scan.splitOpenFileCost());
+        this.taskGroups = Lists.newArrayList(plannedTaskGroups);
+
+        LOG.debug("Planned {} task group(s) without data grouping", taskGroups.size());
+
+      } else {
+        List<ScanTaskGroup<T>> plannedTaskGroups =
+            TableScanUtil.planTaskGroups(
+                tasks(),
+                scan.targetSplitSize(),
+                scan.splitLookback(),
+                scan.splitOpenFileCost(),
+                groupingKeyType());
+        StructLikeSet plannedGroupingKeys = collectGroupingKeys(plannedTaskGroups);
+
+        LOG.debug(
+            "Planned {} task group(s) with {} grouping key type and {} unique grouping key(s)",
+            plannedTaskGroups.size(),
+            groupingKeyType(),
+            plannedGroupingKeys.size());
+
+        // task groups may be planned multiple times because of runtime filtering
+        // the number of task groups may change but the set of grouping keys must stay same
+        // if grouping keys are not null, this planning happens after runtime filtering
+        // so an empty task group must be added for each filtered out grouping key
+
+        if (groupingKeys == null) {
+          this.taskGroups = plannedTaskGroups;
+          this.groupingKeys = plannedGroupingKeys;
+
+        } else {
+          StructLikeSet missingGroupingKeys = StructLikeSet.create(groupingKeyType());
+
+          for (StructLike groupingKey : groupingKeys) {
+            if (!plannedGroupingKeys.contains(groupingKey)) {
+              missingGroupingKeys.add(groupingKey);
+            }
+          }
+
+          LOG.debug("{} grouping key(s) were filtered out at runtime", missingGroupingKeys.size());
+
+          for (StructLike groupingKey : missingGroupingKeys) {
+            plannedTaskGroups.add(new BaseScanTaskGroup<>(groupingKey, Collections.emptyList()));
+          }
+
+          this.taskGroups = plannedTaskGroups;
+        }
+      }
+    }
+
+    return taskGroups;
+  }
+
+  // only task groups can be reset while resetting tasks
+  // the set of scanned specs, grouping key type, grouping keys must never change
+  protected void resetTasks(List<T> filteredTasks) {
+    this.taskGroups = null;
+    this.tasks = filteredTasks;
+  }
+
+  private StructLikeSet collectGroupingKeys(Iterable<ScanTaskGroup<T>> taskGroupIterable) {
+    StructLikeSet keys = StructLikeSet.create(groupingKeyType());
+
+    for (ScanTaskGroup<T> taskGroup : taskGroupIterable) {
+      keys.add(taskGroup.groupingKey());
+    }
+
+    return keys;
+  }
+}
diff --git a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkScan.java b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkScan.java
index f40003dc0e..d1ef4457e8 100644
--- a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkScan.java
+++ b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkScan.java
@@ -20,6 +20,7 @@ package org.apache.iceberg.spark.source;
 
 import java.util.Collections;
 import java.util.List;
+import java.util.Map;
 import java.util.stream.Collectors;
 import org.apache.iceberg.ScanTaskGroup;
 import org.apache.iceberg.Schema;
@@ -34,6 +35,7 @@ import org.apache.iceberg.spark.SparkSchemaUtil;
 import org.apache.iceberg.spark.SparkUtil;
 import org.apache.iceberg.spark.source.metrics.NumDeletes;
 import org.apache.iceberg.spark.source.metrics.NumSplits;
+import org.apache.iceberg.types.Types;
 import org.apache.iceberg.util.PropertyUtil;
 import org.apache.spark.api.java.JavaSparkContext;
 import org.apache.spark.sql.SparkSession;
@@ -95,11 +97,16 @@ abstract class SparkScan implements Scan, SupportsReportStatistics {
     return filterExpressions;
   }
 
+  protected Types.StructType groupingKeyType() {
+    return Types.StructType.of();
+  }
+
   protected abstract List<? extends ScanTaskGroup<?>> taskGroups();
 
   @Override
   public Batch toBatch() {
-    return new SparkBatch(sparkContext, table, readConf, taskGroups(), expectedSchema, hashCode());
+    return new SparkBatch(
+        sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
   }
 
   @Override
@@ -130,13 +137,11 @@ abstract class SparkScan implements Scan, SupportsReportStatistics {
       return new Stats(0L, 0L);
     }
 
-    // estimate stats using snapshot summary only for partitioned tables (metadata tables are
-    // unpartitioned)
+    // estimate stats using snapshot summary only for partitioned tables
+    // (metadata tables are unpartitioned)
     if (!table.spec().isUnpartitioned() && filterExpressions.isEmpty()) {
-      LOG.debug("using table metadata to estimate table statistics");
-      long totalRecords =
-          PropertyUtil.propertyAsLong(
-              snapshot.summary(), SnapshotSummary.TOTAL_RECORDS_PROP, Long.MAX_VALUE);
+      LOG.debug("Using table metadata to estimate table statistics");
+      long totalRecords = totalRecords(snapshot);
       return new Stats(SparkSchemaUtil.estimateSize(readSchema(), totalRecords), totalRecords);
     }
 
@@ -145,11 +150,21 @@ abstract class SparkScan implements Scan, SupportsReportStatistics {
     return new Stats(sizeInBytes, rowsCount);
   }
 
+  private long totalRecords(Snapshot snapshot) {
+    Map<String, String> summary = snapshot.summary();
+    return PropertyUtil.propertyAsLong(summary, SnapshotSummary.TOTAL_RECORDS_PROP, Long.MAX_VALUE);
+  }
+
   @Override
   public String description() {
-    String filters =
-        filterExpressions.stream().map(Spark3Util::describe).collect(Collectors.joining(", "));
-    return String.format("%s [filters=%s]", table, filters);
+    String groupingKeyFieldNamesAsString =
+        groupingKeyType().fields().stream()
+            .map(Types.NestedField::name)
+            .collect(Collectors.joining(", "));
+
+    return String.format(
+        "%s [filters=%s, groupedBy=%s]",
+        table(), Spark3Util.describe(filterExpressions), groupingKeyFieldNamesAsString);
   }
 
   @Override
diff --git a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkScanBuilder.java b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkScanBuilder.java
index 0e076d16a1..1dee9b6128 100644
--- a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkScanBuilder.java
+++ b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkScanBuilder.java
@@ -29,7 +29,6 @@ import org.apache.iceberg.Schema;
 import org.apache.iceberg.Snapshot;
 import org.apache.iceberg.Table;
 import org.apache.iceberg.TableProperties;
-import org.apache.iceberg.TableScan;
 import org.apache.iceberg.exceptions.ValidationException;
 import org.apache.iceberg.expressions.Binder;
 import org.apache.iceberg.expressions.Expression;
@@ -421,9 +420,9 @@ public class SparkScanBuilder
 
     Schema expectedSchema = schemaWithMetadataColumns();
 
-    TableScan scan =
+    BatchScan scan =
         table
-            .newScan()
+            .newBatchScan()
             .useSnapshot(snapshot.snapshotId())
             .ignoreResiduals()
             .caseSensitive(caseSensitive)
diff --git a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkWrite.java b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkWrite.java
index 52e43d3484..0b19fec9fd 100644
--- a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkWrite.java
+++ b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/SparkWrite.java
@@ -383,7 +383,7 @@ abstract class SparkWrite implements Write, RequiresDistributionAndOrdering {
     }
 
     private List<DataFile> overwrittenFiles() {
-      return scan.files().stream().map(FileScanTask::file).collect(Collectors.toList());
+      return scan.tasks().stream().map(FileScanTask::file).collect(Collectors.toList());
     }
 
     private Expression conflictDetectionFilter() {
diff --git a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/StructInternalRow.java b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/StructInternalRow.java
index 3c7ebabeab..f67013f8c4 100644
--- a/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/StructInternalRow.java
+++ b/spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/source/StructInternalRow.java
@@ -27,6 +27,7 @@ import java.time.OffsetDateTime;
 import java.util.Collection;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.function.BiConsumer;
 import java.util.function.Function;
 import org.apache.iceberg.StructLike;
@@ -356,4 +357,23 @@ class StructInternalRow extends InternalRow {
 
     return new GenericArrayData(array);
   }
+
+  @Override
+  public boolean equals(Object other) {
+    if (this == other) {
+      return true;
+    }
+
+    if (other == null || getClass() != other.getClass()) {
+      return false;
+    }
+
+    StructInternalRow that = (StructInternalRow) other;
+    return type.equals(that.type) && struct.equals(that.struct);
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(type, struct);
+  }
 }
diff --git a/spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/SparkTestBase.java b/spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/SparkTestBase.java
index 27fcb50817..20b3ab3c3f 100644
--- a/spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/SparkTestBase.java
+++ b/spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/SparkTestBase.java
@@ -28,6 +28,8 @@ import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicReference;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
 import org.apache.hadoop.hive.conf.HiveConf;
@@ -41,11 +43,17 @@ import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
 import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
 import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
 import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.spark.api.java.JavaSparkContext;
 import org.apache.spark.sql.Dataset;
 import org.apache.spark.sql.Encoders;
 import org.apache.spark.sql.Row;
 import org.apache.spark.sql.SparkSession;
+import org.apache.spark.sql.catalyst.analysis.NoSuchTableException;
+import org.apache.spark.sql.execution.QueryExecution;
+import org.apache.spark.sql.execution.SparkPlan;
+import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanExec;
 import org.apache.spark.sql.internal.SQLConf;
+import org.apache.spark.sql.util.QueryExecutionListener;
 import org.junit.AfterClass;
 import org.junit.Assert;
 import org.junit.BeforeClass;
@@ -57,6 +65,7 @@ public abstract class SparkTestBase {
   protected static TestHiveMetastore metastore = null;
   protected static HiveConf hiveConf = null;
   protected static SparkSession spark = null;
+  protected static JavaSparkContext sparkContext = null;
   protected static HiveCatalog catalog = null;
 
   @BeforeClass
@@ -74,6 +83,8 @@ public abstract class SparkTestBase {
             .enableHiveSupport()
             .getOrCreate();
 
+    SparkTestBase.sparkContext = JavaSparkContext.fromSparkContext(spark.sparkContext());
+
     SparkTestBase.catalog =
         (HiveCatalog)
             CatalogUtil.loadCatalog(
@@ -93,6 +104,7 @@ public abstract class SparkTestBase {
     SparkTestBase.metastore = null;
     spark.stop();
     SparkTestBase.spark = null;
+    SparkTestBase.sparkContext = null;
   }
 
   protected long waitUntilAfter(long timestampMillis) {
@@ -257,6 +269,65 @@ public abstract class SparkTestBase {
     return spark.read().schema(schema).json(jsonDF);
   }
 
+  protected void append(String table, String... jsonRecords) {
+    try {
+      String schema = spark.table(table).schema().toDDL();
+      Dataset<Row> df = jsonToDF(schema, jsonRecords);
+      df.coalesce(1).writeTo(table).append();
+    } catch (NoSuchTableException e) {
+      throw new RuntimeException("Failed to write data", e);
+    }
+  }
+
+  protected String tablePropsAsString(Map<String, String> tableProps) {
+    StringBuilder stringBuilder = new StringBuilder();
+
+    for (Map.Entry<String, String> property : tableProps.entrySet()) {
+      if (stringBuilder.length() > 0) {
+        stringBuilder.append(", ");
+      }
+      stringBuilder.append(String.format("'%s' '%s'", property.getKey(), property.getValue()));
+    }
+
+    return stringBuilder.toString();
+  }
+
+  protected SparkPlan executeAndKeepPlan(String query, Object... args) {
+    return executeAndKeepPlan(() -> sql(query, args));
+  }
+
+  protected SparkPlan executeAndKeepPlan(Action action) {
+    AtomicReference<SparkPlan> executedPlanRef = new AtomicReference<>();
+
+    QueryExecutionListener listener =
+        new QueryExecutionListener() {
+          @Override
+          public void onSuccess(String funcName, QueryExecution qe, long durationNs) {
+            executedPlanRef.set(qe.executedPlan());
+          }
+
+          @Override
+          public void onFailure(String funcName, QueryExecution qe, Exception exception) {}
+        };
+
+    spark.listenerManager().register(listener);
+
+    action.invoke();
+
+    try {
+      spark.sparkContext().listenerBus().waitUntilEmpty();
+    } catch (TimeoutException e) {
+      throw new RuntimeException("Timeout while waiting for processing events", e);
+    }
+
+    SparkPlan executedPlan = executedPlanRef.get();
+    if (executedPlan instanceof AdaptiveSparkPlanExec) {
+      return ((AdaptiveSparkPlanExec) executedPlan).executedPlan();
+    } else {
+      return executedPlan;
+    }
+  }
+
   @FunctionalInterface
   protected interface Action {
     void invoke();
diff --git a/spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestStoragePartitionedJoins.java b/spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestStoragePartitionedJoins.java
new file mode 100644
index 0000000000..78e18516f7
--- /dev/null
+++ b/spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestStoragePartitionedJoins.java
@@ -0,0 +1,586 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.spark.SparkSQLProperties;
+import org.apache.iceberg.spark.SparkSchemaUtil;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.iceberg.spark.SparkWriteOptions;
+import org.apache.iceberg.spark.data.RandomData;
+import org.apache.spark.api.java.JavaRDD;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.catalyst.analysis.NoSuchTableException;
+import org.apache.spark.sql.internal.SQLConf;
+import org.apache.spark.sql.types.StructType;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class TestStoragePartitionedJoins extends SparkTestBaseWithCatalog {
+
+  private static final String OTHER_TABLE_NAME = "other_table";
+
+  // open file cost and split size are set as 16 MB to produce a split per file
+  private static final Map<String, String> TABLE_PROPERTIES =
+      ImmutableMap.of(
+          TableProperties.SPLIT_SIZE, "16777216", TableProperties.SPLIT_OPEN_FILE_COST, "16777216");
+
+  // only v2 bucketing and preserve data grouping properties have to be enabled to trigger SPJ
+  // other properties are only to simplify testing and validation
+  private static final Map<String, String> ENABLED_SPJ_SQL_CONF =
+      ImmutableMap.of(
+          SQLConf.V2_BUCKETING_ENABLED().key(),
+          "true",
+          SQLConf.REQUIRE_ALL_CLUSTER_KEYS_FOR_CO_PARTITION().key(),
+          "false",
+          SQLConf.ADAPTIVE_EXECUTION_ENABLED().key(),
+          "false",
+          SQLConf.AUTO_BROADCASTJOIN_THRESHOLD().key(),
+          "-1",
+          SparkSQLProperties.PRESERVE_DATA_GROUPING,
+          "true");
+
+  private static final Map<String, String> DISABLED_SPJ_SQL_CONF =
+      ImmutableMap.of(
+          SQLConf.V2_BUCKETING_ENABLED().key(),
+          "false",
+          SQLConf.REQUIRE_ALL_CLUSTER_KEYS_FOR_CO_PARTITION().key(),
+          "false",
+          SQLConf.ADAPTIVE_EXECUTION_ENABLED().key(),
+          "false",
+          SQLConf.AUTO_BROADCASTJOIN_THRESHOLD().key(),
+          "-1",
+          SparkSQLProperties.PRESERVE_DATA_GROUPING,
+          "true");
+
+  @BeforeClass
+  public static void setupSparkConf() {
+    spark.conf().set("spark.sql.shuffle.partitions", "4");
+  }
+
+  @After
+  public void removeTables() {
+    sql("DROP TABLE IF EXISTS %s", tableName);
+    sql("DROP TABLE IF EXISTS %s", tableName(OTHER_TABLE_NAME));
+  }
+
+  // TODO: add tests for truncate transforms once SPARK-40295 is released
+  // TODO: add tests for cases when one side contains a subset of keys once SPARK-41398 is released
+
+  @Test
+  public void testJoinsWithBucketingOnByteColumn() throws NoSuchTableException {
+    checkJoin("byte_col", "TINYINT", "bucket(4, byte_col)");
+  }
+
+  @Test
+  public void testJoinsWithBucketingOnShortColumn() throws NoSuchTableException {
+    checkJoin("short_col", "SMALLINT", "bucket(4, short_col)");
+  }
+
+  @Test
+  public void testJoinsWithBucketingOnIntColumn() throws NoSuchTableException {
+    checkJoin("int_col", "INT", "bucket(16, int_col)");
+  }
+
+  @Test
+  public void testJoinsWithBucketingOnLongColumn() throws NoSuchTableException {
+    checkJoin("long_col", "BIGINT", "bucket(16, long_col)");
+  }
+
+  @Test
+  public void testJoinsWithBucketingOnTimestampColumn() throws NoSuchTableException {
+    checkJoin("timestamp_col", "TIMESTAMP", "bucket(16, timestamp_col)");
+  }
+
+  @Test
+  public void testJoinsWithBucketingOnDateColumn() throws NoSuchTableException {
+    checkJoin("date_col", "DATE", "bucket(8, date_col)");
+  }
+
+  @Test
+  public void testJoinsWithBucketingOnDecimalColumn() throws NoSuchTableException {
+    checkJoin("decimal_col", "DECIMAL(20, 2)", "bucket(8, decimal_col)");
+  }
+
+  @Test
+  public void testJoinsWithBucketingOnBinaryColumn() throws NoSuchTableException {
+    checkJoin("binary_col", "BINARY", "bucket(8, binary_col)");
+  }
+
+  @Test
+  public void testJoinsWithYearsOnTimestampColumn() throws NoSuchTableException {
+    checkJoin("timestamp_col", "TIMESTAMP", "years(timestamp_col)");
+  }
+
+  @Test
+  public void testJoinsWithYearsOnDateColumn() throws NoSuchTableException {
+    checkJoin("date_col", "DATE", "years(date_col)");
+  }
+
+  @Test
+  public void testJoinsWithMonthsOnTimestampColumn() throws NoSuchTableException {
+    checkJoin("timestamp_col", "TIMESTAMP", "months(timestamp_col)");
+  }
+
+  @Test
+  public void testJoinsWithMonthsOnDateColumn() throws NoSuchTableException {
+    checkJoin("date_col", "DATE", "months(date_col)");
+  }
+
+  @Test
+  public void testJoinsWithDaysOnTimestampColumn() throws NoSuchTableException {
+    checkJoin("timestamp_col", "TIMESTAMP", "days(timestamp_col)");
+  }
+
+  @Test
+  public void testJoinsWithDaysOnDateColumn() throws NoSuchTableException {
+    checkJoin("date_col", "DATE", "days(date_col)");
+  }
+
+  @Test
+  public void testJoinsWithHoursOnTimestampColumn() throws NoSuchTableException {
+    checkJoin("timestamp_col", "TIMESTAMP", "hours(timestamp_col)");
+  }
+
+  @Test
+  public void testJoinsWithMultipleTransformTypes() throws NoSuchTableException {
+    String createTableStmt =
+        "CREATE TABLE %s ("
+            + "  id BIGINT, int_col INT, date_col1 DATE, date_col2 DATE, date_col3 DATE,"
+            + "  timestamp_col TIMESTAMP, string_col STRING, dep STRING)"
+            + "USING iceberg "
+            + "PARTITIONED BY ("
+            + "  years(date_col1), months(date_col2), days(date_col3), hours(timestamp_col), "
+            + "  bucket(8, int_col), dep)"
+            + "TBLPROPERTIES (%s)";
+
+    sql(createTableStmt, tableName, tablePropsAsString(TABLE_PROPERTIES));
+    sql(createTableStmt, tableName(OTHER_TABLE_NAME), tablePropsAsString(TABLE_PROPERTIES));
+
+    Table table = validationCatalog.loadTable(tableIdent);
+
+    Dataset<Row> dataDF = randomDataDF(table.schema(), 16);
+
+    // write to the first table 1 time to generate 1 file per partition
+    append(tableName, dataDF);
+
+    // write to the second table 2 times to generate 2 files per partition
+    append(tableName(OTHER_TABLE_NAME), dataDF);
+    append(tableName(OTHER_TABLE_NAME), dataDF);
+
+    // Spark SPJ support is limited at the moment and requires all source partitioning columns,
+    // which were projected in the query, to be part of the join condition
+    // suppose a table is partitioned by `p1`, `bucket(8, pk)`
+    // queries covering `p1` and `pk` columns must include equality predicates
+    // on both `p1` and `pk` to benefit from SPJ
+    // this is a temporary Spark limitation that will be removed in a future release
+
+    assertPartitioningAwarePlan(
+        1, /* expected num of shuffles with SPJ */
+        3, /* expected num of shuffles without SPJ */
+        "SELECT t1.id "
+            + "FROM %s t1 "
+            + "INNER JOIN %s t2 "
+            + "ON t1.id = t2.id AND t1.dep = t2.dep "
+            + "ORDER BY t1.id",
+        tableName,
+        tableName(OTHER_TABLE_NAME));
+
+    assertPartitioningAwarePlan(
+        1, /* expected num of shuffles with SPJ */
+        3, /* expected num of shuffles without SPJ */
+        "SELECT t1.id, t1.int_col, t1.date_col1 "
+            + "FROM %s t1 "
+            + "INNER JOIN %s t2 "
+            + "ON t1.id = t2.id AND t1.int_col = t2.int_col AND t1.date_col1 = t2.date_col1 "
+            + "ORDER BY t1.id, t1.int_col, t1.date_col1",
+        tableName,
+        tableName(OTHER_TABLE_NAME));
+
+    assertPartitioningAwarePlan(
+        1, /* expected num of shuffles with SPJ */
+        3, /* expected num of shuffles without SPJ */
+        "SELECT t1.id, t1.timestamp_col, t1.string_col "
+            + "FROM %s t1 "
+            + "INNER JOIN %s t2 "
+            + "ON t1.id = t2.id AND t1.timestamp_col = t2.timestamp_col AND t1.string_col = t2.string_col "
+            + "ORDER BY t1.id, t1.timestamp_col, t1.string_col",
+        tableName,
+        tableName(OTHER_TABLE_NAME));
+
+    assertPartitioningAwarePlan(
+        1, /* expected num of shuffles with SPJ */
+        3, /* expected num of shuffles without SPJ */
+        "SELECT t1.id, t1.date_col1, t1.date_col2, t1.date_col3 "
+            + "FROM %s t1 "
+            + "INNER JOIN %s t2 "
+            + "ON t1.id = t2.id AND t1.date_col1 = t2.date_col1 AND t1.date_col2 = t2.date_col2 AND t1.date_col3 = t2.date_col3 "
+            + "ORDER BY t1.id, t1.date_col1, t1.date_col2, t1.date_col3",
+        tableName,
+        tableName(OTHER_TABLE_NAME));
+
+    assertPartitioningAwarePlan(
+        1, /* expected num of shuffles with SPJ */
+        3, /* expected num of shuffles without SPJ */
+        "SELECT t1.id, t1.int_col, t1.timestamp_col, t1.dep "
+            + "FROM %s t1 "
+            + "INNER JOIN %s t2 "
+            + "ON t1.id = t2.id AND t1.int_col = t2.int_col AND t1.timestamp_col = t2.timestamp_col AND t1.dep = t2.dep "
+            + "ORDER BY t1.id, t1.int_col, t1.timestamp_col, t1.dep",
+        tableName,
+        tableName(OTHER_TABLE_NAME));
+  }
+
+  @Test
+  public void testJoinsWithCompatibleSpecEvolution() {
+    // create a table with an empty spec
+    sql(
+        "CREATE TABLE %s (id BIGINT, int_col INT, dep STRING)"
+            + "USING iceberg "
+            + "TBLPROPERTIES (%s)",
+        tableName, tablePropsAsString(TABLE_PROPERTIES));
+
+    Table table = validationCatalog.loadTable(tableIdent);
+
+    // evolve the spec in the first table by adding `dep`
+    table.updateSpec().addField("dep").commit();
+
+    // insert data into the first table partitioned by `dep`
+    sql("REFRESH TABLE %s", tableName);
+    sql("INSERT INTO %s VALUES (1L, 100, 'software')", tableName);
+
+    // evolve the spec in the first table by adding `bucket(int_col, 8)`
+    table.updateSpec().addField(Expressions.bucket("int_col", 8)).commit();
+
+    // insert data into the first table partitioned by `dep`, `bucket(8, int_col)`
+    sql("REFRESH TABLE %s", tableName);
+    sql("INSERT INTO %s VALUES (2L, 200, 'hr')", tableName);
+
+    // create another table partitioned by `other_dep`
+    sql(
+        "CREATE TABLE %s (other_id BIGINT, other_int_col INT, other_dep STRING)"
+            + "USING iceberg "
+            + "PARTITIONED BY (other_dep)"
+            + "TBLPROPERTIES (%s)",
+        tableName(OTHER_TABLE_NAME), tablePropsAsString(TABLE_PROPERTIES));
+
+    // insert data into the second table partitioned by 'other_dep'
+    sql("INSERT INTO %s VALUES (1L, 100, 'software')", tableName(OTHER_TABLE_NAME));
+    sql("INSERT INTO %s VALUES (2L, 200, 'hr')", tableName(OTHER_TABLE_NAME));
+
+    // SPJ would apply as the grouping keys are compatible
+    // the first table: `dep` (an intersection of all active partition fields across scanned specs)
+    // the second table: `other_dep` (the only partition field).
+
+    assertPartitioningAwarePlan(
+        1, /* expected num of shuffles with SPJ */
+        3, /* expected num of shuffles without SPJ */
+        "SELECT * "
+            + "FROM %s "
+            + "INNER JOIN %s "
+            + "ON id = other_id AND int_col = other_int_col AND dep = other_dep "
+            + "ORDER BY id, int_col, dep",
+        tableName,
+        tableName(OTHER_TABLE_NAME));
+  }
+
+  @Test
+  public void testJoinsWithIncompatibleSpecs() {
+    sql(
+        "CREATE TABLE %s (id BIGINT, int_col INT, dep STRING)"
+            + "USING iceberg "
+            + "PARTITIONED BY (dep)"
+            + "TBLPROPERTIES (%s)",
+        tableName, tablePropsAsString(TABLE_PROPERTIES));
+
+    sql("INSERT INTO %s VALUES (1L, 100, 'software')", tableName);
+    sql("INSERT INTO %s VALUES (2L, 200, 'software')", tableName);
+    sql("INSERT INTO %s VALUES (3L, 300, 'software')", tableName);
+
+    sql(
+        "CREATE TABLE %s (id BIGINT, int_col INT, dep STRING)"
+            + "USING iceberg "
+            + "PARTITIONED BY (bucket(8, int_col))"
+            + "TBLPROPERTIES (%s)",
+        tableName(OTHER_TABLE_NAME), tablePropsAsString(TABLE_PROPERTIES));
+
+    sql("INSERT INTO %s VALUES (1L, 100, 'software')", tableName(OTHER_TABLE_NAME));
+    sql("INSERT INTO %s VALUES (2L, 200, 'software')", tableName(OTHER_TABLE_NAME));
+    sql("INSERT INTO %s VALUES (3L, 300, 'software')", tableName(OTHER_TABLE_NAME));
+
+    // queries can't benefit from SPJ as specs are not compatible
+    // the first table: `dep`
+    // the second table: `bucket(8, int_col)`
+
+    assertPartitioningAwarePlan(
+        3, /* expected num of shuffles with SPJ */
+        3, /* expected num of shuffles with SPJ */
+        "SELECT * "
+            + "FROM %s t1 "
+            + "INNER JOIN %s t2 "
+            + "ON t1.id = t2.id AND t1.int_col = t2.int_col AND t1.dep = t2.dep "
+            + "ORDER BY t1.id, t1.int_col, t1.dep, t2.id, t2.int_col, t2.dep",
+        tableName,
+        tableName(OTHER_TABLE_NAME));
+  }
+
+  @Test
+  public void testJoinsWithUnpartitionedTables() {
+    sql(
+        "CREATE TABLE %s (id BIGINT, int_col INT, dep STRING)"
+            + "USING iceberg "
+            + "TBLPROPERTIES ("
+            + "  'read.split.target-size' = 16777216,"
+            + "  'read.split.open-file-cost' = 16777216)",
+        tableName);
+
+    sql("INSERT INTO %s VALUES (1L, 100, 'software')", tableName);
+    sql("INSERT INTO %s VALUES (2L, 200, 'software')", tableName);
+    sql("INSERT INTO %s VALUES (3L, 300, 'software')", tableName);
+
+    sql(
+        "CREATE TABLE %s (id BIGINT, int_col INT, dep STRING)"
+            + "USING iceberg "
+            + "TBLPROPERTIES ("
+            + "  'read.split.target-size' = 16777216,"
+            + "  'read.split.open-file-cost' = 16777216)",
+        tableName(OTHER_TABLE_NAME));
+
+    sql("INSERT INTO %s VALUES (1L, 100, 'software')", tableName(OTHER_TABLE_NAME));
+    sql("INSERT INTO %s VALUES (2L, 200, 'software')", tableName(OTHER_TABLE_NAME));
+    sql("INSERT INTO %s VALUES (3L, 300, 'software')", tableName(OTHER_TABLE_NAME));
+
+    // queries covering unpartitioned tables can't benefit from SPJ but shouldn't fail
+
+    assertPartitioningAwarePlan(
+        3, /* expected num of shuffles with SPJ */
+        3, /* expected num of shuffles without SPJ */
+        "SELECT * "
+            + "FROM %s t1 "
+            + "INNER JOIN %s t2 "
+            + "ON t1.id = t2.id AND t1.int_col = t2.int_col AND t1.dep = t2.dep "
+            + "ORDER BY t1.id, t1.int_col, t1.dep, t2.id, t2.int_col, t2.dep",
+        tableName,
+        tableName(OTHER_TABLE_NAME));
+  }
+
+  @Test
+  public void testJoinsWithEmptyTable() {
+    sql(
+        "CREATE TABLE %s (id BIGINT, int_col INT, dep STRING)"
+            + "USING iceberg "
+            + "PARTITIONED BY (dep)"
+            + "TBLPROPERTIES (%s)",
+        tableName, tablePropsAsString(TABLE_PROPERTIES));
+
+    sql(
+        "CREATE TABLE %s (id BIGINT, int_col INT, dep STRING)"
+            + "USING iceberg "
+            + "PARTITIONED BY (dep)"
+            + "TBLPROPERTIES (%s)",
+        tableName(OTHER_TABLE_NAME), tablePropsAsString(TABLE_PROPERTIES));
+
+    sql("INSERT INTO %s VALUES (1L, 100, 'software')", tableName(OTHER_TABLE_NAME));
+    sql("INSERT INTO %s VALUES (2L, 200, 'software')", tableName(OTHER_TABLE_NAME));
+    sql("INSERT INTO %s VALUES (3L, 300, 'software')", tableName(OTHER_TABLE_NAME));
+
+    assertPartitioningAwarePlan(
+        3, /* expected num of shuffles with SPJ */
+        3, /* expected num of shuffles without SPJ */
+        "SELECT * "
+            + "FROM %s t1 "
+            + "INNER JOIN %s t2 "
+            + "ON t1.id = t2.id AND t1.int_col = t2.int_col AND t1.dep = t2.dep "
+            + "ORDER BY t1.id, t1.int_col, t1.dep, t2.id, t2.int_col, t2.dep",
+        tableName,
+        tableName(OTHER_TABLE_NAME));
+  }
+
+  @Test
+  public void testJoinsWithOneSplitTables() {
+    sql(
+        "CREATE TABLE %s (id BIGINT, int_col INT, dep STRING)"
+            + "USING iceberg "
+            + "PARTITIONED BY (dep)"
+            + "TBLPROPERTIES (%s)",
+        tableName, tablePropsAsString(TABLE_PROPERTIES));
+
+    sql("INSERT INTO %s VALUES (1L, 100, 'software')", tableName);
+
+    sql(
+        "CREATE TABLE %s (id BIGINT, int_col INT, dep STRING)"
+            + "USING iceberg "
+            + "PARTITIONED BY (dep)"
+            + "TBLPROPERTIES (%s)",
+        tableName(OTHER_TABLE_NAME), tablePropsAsString(TABLE_PROPERTIES));
+
+    sql("INSERT INTO %s VALUES (1L, 100, 'software')", tableName(OTHER_TABLE_NAME));
+
+    // Spark should be able to avoid shuffles even without SPJ if each side has only one split
+
+    assertPartitioningAwarePlan(
+        0, /* expected num of shuffles with SPJ */
+        0, /* expected num of shuffles without SPJ */
+        "SELECT * "
+            + "FROM %s t1 "
+            + "INNER JOIN %s t2 "
+            + "ON t1.id = t2.id AND t1.int_col = t2.int_col AND t1.dep = t2.dep "
+            + "ORDER BY t1.id, t1.int_col, t1.dep, t2.id, t2.int_col, t2.dep",
+        tableName,
+        tableName(OTHER_TABLE_NAME));
+  }
+
+  @Test
+  public void testAggregates() throws NoSuchTableException {
+    sql(
+        "CREATE TABLE %s (id BIGINT, int_col INT, dep STRING)"
+            + "USING iceberg "
+            + "PARTITIONED BY (dep, bucket(8, int_col))"
+            + "TBLPROPERTIES (%s)",
+        tableName, tablePropsAsString(TABLE_PROPERTIES));
+
+    // write to the table 3 times to generate 3 files per partition
+    Table table = validationCatalog.loadTable(tableIdent);
+    Dataset<Row> dataDF = randomDataDF(table.schema(), 100);
+    append(tableName, dataDF);
+
+    assertPartitioningAwarePlan(
+        1, /* expected num of shuffles with SPJ */
+        3, /* expected num of shuffles without SPJ */
+        "SELECT COUNT (DISTINCT id) AS count FROM %s GROUP BY dep, int_col ORDER BY count",
+        tableName,
+        tableName(OTHER_TABLE_NAME));
+
+    assertPartitioningAwarePlan(
+        1, /* expected num of shuffles with SPJ */
+        3, /* expected num of shuffles without SPJ */
+        "SELECT COUNT (DISTINCT id) AS count FROM %s GROUP BY dep ORDER BY count",
+        tableName,
+        tableName(OTHER_TABLE_NAME));
+  }
+
+  private void checkJoin(String sourceColumnName, String sourceColumnType, String transform)
+      throws NoSuchTableException {
+
+    String createTableStmt =
+        "CREATE TABLE %s (id BIGINT, salary INT, %s %s)"
+            + "USING iceberg "
+            + "PARTITIONED BY (%s)"
+            + "TBLPROPERTIES (%s)";
+
+    sql(
+        createTableStmt,
+        tableName,
+        sourceColumnName,
+        sourceColumnType,
+        transform,
+        tablePropsAsString(TABLE_PROPERTIES));
+
+    sql(
+        createTableStmt,
+        tableName(OTHER_TABLE_NAME),
+        sourceColumnName,
+        sourceColumnType,
+        transform,
+        tablePropsAsString(TABLE_PROPERTIES));
+
+    Table table = validationCatalog.loadTable(tableIdent);
+    Dataset<Row> dataDF = randomDataDF(table.schema(), 200);
+    append(tableName, dataDF);
+    append(tableName(OTHER_TABLE_NAME), dataDF);
+
+    assertPartitioningAwarePlan(
+        1, /* expected num of shuffles with SPJ */
+        3, /* expected num of shuffles without SPJ */
+        "SELECT t1.id, t1.salary, t1.%s "
+            + "FROM %s t1 "
+            + "INNER JOIN %s t2 "
+            + "ON t1.id = t2.id AND t1.%s = t2.%s "
+            + "ORDER BY t1.id, t1.%s",
+        sourceColumnName,
+        tableName,
+        tableName(OTHER_TABLE_NAME),
+        sourceColumnName,
+        sourceColumnName,
+        sourceColumnName);
+  }
+
+  private void assertPartitioningAwarePlan(
+      int expectedNumShufflesWithSPJ,
+      int expectedNumShufflesWithoutSPJ,
+      String query,
+      Object... args) {
+
+    AtomicReference<List<Object[]>> rowsWithSPJ = new AtomicReference<>();
+    AtomicReference<List<Object[]>> rowsWithoutSPJ = new AtomicReference<>();
+
+    withSQLConf(
+        ENABLED_SPJ_SQL_CONF,
+        () -> {
+          String plan = executeAndKeepPlan(query, args).toString();
+          int actualNumShuffles = StringUtils.countMatches(plan, "Exchange");
+          Assert.assertEquals(
+              "Number of shuffles with enabled SPJ must match",
+              expectedNumShufflesWithSPJ,
+              actualNumShuffles);
+
+          rowsWithSPJ.set(sql(query, args));
+        });
+
+    withSQLConf(
+        DISABLED_SPJ_SQL_CONF,
+        () -> {
+          String plan = executeAndKeepPlan(query, args).toString();
+          int actualNumShuffles = StringUtils.countMatches(plan, "Exchange");
+          Assert.assertEquals(
+              "Number of shuffles with disabled SPJ must match",
+              expectedNumShufflesWithoutSPJ,
+              actualNumShuffles);
+
+          rowsWithoutSPJ.set(sql(query, args));
+        });
+
+    assertEquals("SPJ should not change query output", rowsWithoutSPJ.get(), rowsWithSPJ.get());
+  }
+
+  private Dataset<Row> randomDataDF(Schema schema, int numRows) {
+    Iterable<InternalRow> rows = RandomData.generateSpark(schema, numRows, 0);
+    JavaRDD<InternalRow> rowRDD = sparkContext.parallelize(Lists.newArrayList(rows));
+    StructType rowSparkType = SparkSchemaUtil.convert(schema);
+    return spark.internalCreateDataFrame(JavaRDD.toRDD(rowRDD), rowSparkType, false);
+  }
+
+  private void append(String table, Dataset<Row> df) throws NoSuchTableException {
+    // fanout writes are enabled as write-time clustering is not supported without Spark extensions
+    df.coalesce(1).writeTo(table).option(SparkWriteOptions.FANOUT_ENABLED, "true").append();
+  }
+}