diff --git a/wp-includes/wp-db.php b/wp-includes/wp-db.php
index 391cfa4..0235c1d 100644
--- a/wp-includes/wp-db.php
+++ b/wp-includes/wp-db.php
@@ -1000,6 +1000,46 @@ class wpdb {
 		$query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
 		$query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
 		$query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
+
+		// START replace NULLs
+		preg_match_all(
+			'|\'?%(?:(\d+)\$)?[dfs]\'?|',
+			$query,
+			$positions,
+			PREG_OFFSET_CAPTURE
+		);
+		if ( ! empty( $positions ) ) {
+			$values     = array_values( $args );
+			$index      = 0;
+			$str_offset = 0;
+			foreach ( $positions[0] as $ref => $pattern ) {
+				$loc_index = 0;
+				if ( ! empty( $positions[1][$ref] ) ) {
+					$loc_index = ( (int)$positions[1][$ref][0] ) - 1;
+				} else {
+					$loc_index = $index++;
+				}
+				if ( ! isset( $values[$loc_index] ) ) {
+					unset( $values[$loc_index] ); // NULL is not set, but present
+					$format_length = strlen( $pattern[0] );
+					$query = substr(
+						$query,
+						0,
+						$pattern[1] + $str_offset
+						) . ' NULL ' .
+						substr(
+							$query,
+							$pattern[1] + $format_length + $str_offset
+						);
+					if ( $format_length != 6 ) {
+						$str_offset += 6 - $format_length;
+					}
+				}
+			}
+			$args = array_values( $values );
+		}
+		// END replace NULLs
+
 		array_walk( $args, array( $this, 'escape_by_ref' ) );
 		return @vsprintf( $query, $args );
 	}
