diff --git a/wp-includes/wp-db.php b/wp-includes/wp-db.php
index 391cfa4..271bb7e 100644
--- a/wp-includes/wp-db.php
+++ b/wp-includes/wp-db.php
@@ -1000,6 +1000,54 @@ 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 ) ) {
+			$init_count = count( $args );
+			$args       = array_values( $args );
+			$index      = 0;
+			$str_offset = 0;
+			$max_index  = 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 ( $loc_index > $max_index ) {
+					$max_index = $loc_index;
+				}
+				if ( ! isset( $args[$loc_index] ) ) {
+					unset( $args[$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;
+					}
+				}
+			}
+			if ( ++$max_index > $init_count ) {
+				return; // too few arguments provided
+			}
+			$args = array_values( $args );
+		}
+		// END replace NULLs
+
 		array_walk( $args, array( $this, 'escape_by_ref' ) );
 		return @vsprintf( $query, $args );
 	}
