Title: wpdb::get_results
Published: April 25, 2014
Last modified: August 20, 2026

---

# wpdb::get_results( string|null $query = null, string $output = OBJECT ): array|null

## In this article

 * [Description](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#description)
 * [Parameters](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#parameters)
 * [Return](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#return)
 * [Source](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#source)
 * [Related](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#related)
 * [Changelog](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#changelog)
 * [User Contributed Notes](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#user-contributed-notes)

[ Back to top](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#wp--skip-link--target)

Retrieves an entire SQL result set from the database (i.e., many rows).

## 󠀁[Description](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#description)󠁿

Executes a SQL query and returns the entire SQL result.

Returns an empty array when no rows match or when the database reports an error 
for the query. Returns null when $query is empty, when $output is not one of the
recognized constants, or when the query cannot run because the connection is not
ready.

## 󠀁[Parameters](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#parameters)󠁿

 `$query`string|nulloptional

SQL query.

Default:`null`

`$output`stringoptional

Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants.
 With one of the first three,
return an array of rows indexed from 0 by SQL result row number. Each row is an 
associative array (column => value, …), a numerically indexed array (0 => value,…),
or an object ( ->column = value ), respectively. With OBJECT_K, return an associative
array of row objects keyed by the value of each row’s first column’s value. Duplicate
keys are discarded.

Default:`OBJECT`

## 󠀁[Return](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#return)󠁿

 array|null Database query results. Empty array when no rows match or on database
error. Null when $query is empty, when $output is invalid, or when the connection
is not ready.

## 󠀁[Source](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#source)󠁿

    ```php
    public function get_results( $query = null, $output = OBJECT ) {
    	$this->func_call = "\$db->get_results(\"$query\", $output)";

    	if ( $query ) {
    		if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
    			$this->check_current_query = false;
    		}

    		$this->query( $query );
    	} else {
    		return null;
    	}

    	$new_array = array();
    	if ( OBJECT === $output ) {
    		// Return an integer-keyed array of row objects.
    		return $this->last_result;
    	} elseif ( OBJECT_K === $output ) {
    		/*
    		 * Return an array of row objects with keys from column 1.
    		 * (Duplicates are discarded.)
    		 */
    		if ( $this->last_result ) {
    			foreach ( $this->last_result as $row ) {
    				$var_by_ref = get_object_vars( $row );
    				/**
    				 * The first column's value is used as the key.
    				 *
    				 * A SQL NULL value surfaces as null here, so coerce it to an empty string to avoid the deprecated
    				 * use of null as an array offset (PHP 8.5+).
    				 *
    				 * @var array-key $key
    				 */
    				$key = array_shift( $var_by_ref ) ?? '';
    				if ( ! isset( $new_array[ $key ] ) ) {
    					$new_array[ $key ] = $row;
    				}
    			}
    		}
    		return $new_array;
    	} elseif ( ARRAY_A === $output || ARRAY_N === $output ) {
    		// Return an integer-keyed array of...
    		if ( $this->last_result ) {
    			if ( ARRAY_N === $output ) {
    				foreach ( (array) $this->last_result as $row ) {
    					// ...integer-keyed row arrays.
    					$new_array[] = array_values( get_object_vars( $row ) );
    				}
    			} else {
    				foreach ( (array) $this->last_result as $row ) {
    					// ...column name-keyed row arrays.
    					$new_array[] = get_object_vars( $row );
    				}
    			}
    		}
    		return $new_array;
    	} elseif ( strtoupper( $output ) === OBJECT ) {
    		// Back compat for OBJECT being previously case-insensitive.
    		return $this->last_result;
    	}
    	return null;
    }
    ```

[View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
[View on Trac](https://core.trac.wordpress.org/browser/tags/7.1/src/wp-includes/class-wpdb.php#L3205)
[View on GitHub](https://github.com/WordPress/wordpress-develop/blob/7.1/src/wp-includes/class-wpdb.php#L3205-L3266)

## 󠀁[Related](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#related)󠁿

| Uses | Description | 
| [wpdb::check_safe_collation()](https://developer.wordpress.org/reference/classes/wpdb/check_safe_collation/)`wp-includes/class-wpdb.php` |

Checks if the query is accessing a collation considered safe.

  | 
| [wpdb::query()](https://developer.wordpress.org/reference/classes/wpdb/query/)`wp-includes/class-wpdb.php` |

Performs a database query, using current database connection.

  |

| Used by | Description | 
| [wp_prime_network_option_caches()](https://developer.wordpress.org/reference/functions/wp_prime_network_option_caches/)`wp-includes/option.php` |

Primes specific network options into the cache with a single database query.

  | 
| [wp_prime_option_caches()](https://developer.wordpress.org/reference/functions/wp_prime_option_caches/)`wp-includes/option.php` |

Primes specific options into the cache with a single database query.

  | 
| [_prime_post_parent_id_caches()](https://developer.wordpress.org/reference/functions/_prime_post_parent_id_caches/)`wp-includes/post.php` |

Prime the cache containing the parent ID of various post objects.

  | 
| [WP_Site_Health::should_suggest_persistent_object_cache()](https://developer.wordpress.org/reference/classes/wp_site_health/should_suggest_persistent_object_cache/)`wp-admin/includes/class-wp-site-health.php` |

Determines whether to suggest using a persistent object cache.

  | 
| [WP_Debug_Data::get_database_size()](https://developer.wordpress.org/reference/classes/wp_debug_data/get_database_size/)`wp-admin/includes/class-wp-debug-data.php` |

Fetches the total size of all the database tables for the active database user.

  | 
| [wp_is_site_initialized()](https://developer.wordpress.org/reference/functions/wp_is_site_initialized/)`wp-includes/ms-site.php` |

Checks whether a site is initialized.

  | 
| [WP_Privacy_Requests_Table::get_request_counts()](https://developer.wordpress.org/reference/classes/wp_privacy_requests_table/get_request_counts/)`wp-admin/includes/class-wp-privacy-requests-table.php` |

Counts the number of requests for each status.

  | 
| [has_term_meta()](https://developer.wordpress.org/reference/functions/has_term_meta/)`wp-includes/taxonomy.php` |

Gets all meta data, including meta IDs, for the given term ID.

  | 
| [WP_Term_Query::get_terms()](https://developer.wordpress.org/reference/classes/wp_term_query/get_terms/)`wp-includes/class-wp-term-query.php` |

Retrieves the query results.

  | 
| [_prime_term_caches()](https://developer.wordpress.org/reference/functions/_prime_term_caches/)`wp-includes/taxonomy.php` |

Adds any terms from the given IDs to the cache that do not already exist in cache.

  | 
| [_prime_network_caches()](https://developer.wordpress.org/reference/functions/_prime_network_caches/)`wp-includes/ms-network.php` |

Adds any networks from the given IDs to the cache that do not already exist in cache.

  | 
| [_prime_site_caches()](https://developer.wordpress.org/reference/functions/_prime_site_caches/)`wp-includes/ms-site.php` |

Adds any sites from the given IDs to the cache that do not already exist in cache.

  | 
| [wxr_term_meta()](https://developer.wordpress.org/reference/functions/wxr_term_meta/)`wp-admin/includes/export.php` |

Outputs term meta XML tags for a given term object.

  | 
| [WP_Term::get_instance()](https://developer.wordpress.org/reference/classes/wp_term/get_instance/)`wp-includes/class-wp-term.php` |

Retrieve [WP_Term](https://developer.wordpress.org/reference/classes/wp_term/) instance.

  | 
| [_prime_comment_caches()](https://developer.wordpress.org/reference/functions/_prime_comment_caches/)`wp-includes/comment.php` |

Adds any comments from the given IDs to the cache that do not already exist in cache.

  | 
| [_wp_batch_split_terms()](https://developer.wordpress.org/reference/functions/_wp_batch_split_terms/)`wp-includes/taxonomy.php` |

Splits a batch of shared taxonomy terms.

  | 
| [wpdb::get_table_charset()](https://developer.wordpress.org/reference/classes/wpdb/get_table_charset/)`wp-includes/class-wpdb.php` |

Retrieves the character set for the given table.

  | 
| [maybe_convert_table_to_utf8mb4()](https://developer.wordpress.org/reference/functions/maybe_convert_table_to_utf8mb4/)`wp-admin/includes/upgrade.php` |

If a table only contains utf8 or utf8mb4 columns, convert it to utf8mb4.

  | 
| [attachment_url_to_postid()](https://developer.wordpress.org/reference/functions/attachment_url_to_postid/)`wp-includes/media.php` |

Tries to convert an attachment URL into a post ID.

  | 
| [check_column()](https://developer.wordpress.org/reference/functions/check_column/)`wp-admin/install-helper.php` |

Checks that database table column matches the criteria.

  | 
| [export_date_options()](https://developer.wordpress.org/reference/functions/export_date_options/)`wp-admin/export.php` |

Creates the date options fields for exporting a given post type.

  | 
| [export_wp()](https://developer.wordpress.org/reference/functions/export_wp/)`wp-admin/includes/export.php` |

Generates the WXR export file for download.

  | 
| [wxr_authors_list()](https://developer.wordpress.org/reference/functions/wxr_authors_list/)`wp-admin/includes/export.php` |

Outputs list of authors with posts.

  | 
| [get_editable_authors()](https://developer.wordpress.org/reference/functions/get_editable_authors/)`wp-admin/includes/deprecated.php` |

Gets author users who can edit posts.

  | 
| [get_others_unpublished_posts()](https://developer.wordpress.org/reference/functions/get_others_unpublished_posts/)`wp-admin/includes/deprecated.php` |

Retrieves editable posts from other users.

  | 
| [WP_List_Table::months_dropdown()](https://developer.wordpress.org/reference/classes/wp_list_table/months_dropdown/)`wp-admin/includes/class-wp-list-table.php` |

Displays a dropdown for filtering items in the list table by month.

  | 
| [pre_schema_upgrade()](https://developer.wordpress.org/reference/functions/pre_schema_upgrade/)`wp-admin/includes/upgrade.php` |

Runs before the schema is upgraded.

  | 
| [upgrade_network()](https://developer.wordpress.org/reference/functions/upgrade_network/)`wp-admin/includes/upgrade.php` |

Executes network-level upgrade routines.

  | 
| [get_alloptions_110()](https://developer.wordpress.org/reference/functions/get_alloptions_110/)`wp-admin/includes/upgrade.php` |

Retrieve all options as it was for 1.2.

  | 
| [dbDelta()](https://developer.wordpress.org/reference/functions/dbdelta/)`wp-admin/includes/upgrade.php` |

Modifies the database based on specified SQL statements.

  | 
| [get_users_drafts()](https://developer.wordpress.org/reference/functions/get_users_drafts/)`wp-admin/includes/user.php` |

Retrieve the user’s drafts.

  | 
| [parent_dropdown()](https://developer.wordpress.org/reference/functions/parent_dropdown/)`wp-admin/includes/template.php` |

Prints out option HTML elements for the page parents drop-down.

  | 
| [media_upload_library_form()](https://developer.wordpress.org/reference/functions/media_upload_library_form/)`wp-admin/includes/media.php` |

Outputs the legacy media upload form for the media library.

  | 
| [has_meta()](https://developer.wordpress.org/reference/functions/has_meta/)`wp-admin/includes/post.php` |

Returns meta data for the given post ID.

  | 
| [bulk_edit_posts()](https://developer.wordpress.org/reference/functions/bulk_edit_posts/)`wp-admin/includes/post.php` |

Processes the post data for the bulk editing of posts.

  | 
| [WP_Importer::get_imported_comments()](https://developer.wordpress.org/reference/classes/wp_importer/get_imported_comments/)`wp-admin/includes/class-wp-importer.php` |

Sets array with imported comments from WordPress database.

  | 
| [WP_Importer::get_imported_posts()](https://developer.wordpress.org/reference/classes/wp_importer/get_imported_posts/)`wp-admin/includes/class-wp-importer.php` |

Returns array with imported permalinks from WordPress database.

  | 
| [WP_Importer::count_imported_posts()](https://developer.wordpress.org/reference/classes/wp_importer/count_imported_posts/)`wp-admin/includes/class-wp-importer.php` |

Returns count of imported permalinks from WordPress database.

  | 
| [get_pending_comments_num()](https://developer.wordpress.org/reference/functions/get_pending_comments_num/)`wp-admin/includes/comment.php` |

Gets the number of pending comments on a post or posts.

  | 
| [cache_users()](https://developer.wordpress.org/reference/functions/cache_users/)`wp-includes/pluggable.php` |

Retrieves info for user lists to prevent multiple queries by [get_userdata()](https://developer.wordpress.org/reference/functions/get_userdata/) .

  | 
| [wp_get_archives()](https://developer.wordpress.org/reference/functions/wp_get_archives/)`wp-includes/general-template.php` |

Displays archive links based on type and format.

  | 
| [get_calendar()](https://developer.wordpress.org/reference/functions/get_calendar/)`wp-includes/general-template.php` |

Displays calendar with days that have posts as links.

  | 
| [get_users_of_blog()](https://developer.wordpress.org/reference/functions/get_users_of_blog/)`wp-includes/deprecated.php` |

Get users for the site.

  | 
| [WP_Query::get_posts()](https://developer.wordpress.org/reference/classes/wp_query/get_posts/)`wp-includes/class-wp-query.php` |

Retrieves an array of posts based on query variables.

  | 
| [wp_scheduled_delete()](https://developer.wordpress.org/reference/functions/wp_scheduled_delete/)`wp-includes/functions.php` |

Permanently deletes comments or posts of any type that have held a status of ‘trash’ for the number of days defined in EMPTY_TRASH_DAYS.

  | 
| [is_blog_installed()](https://developer.wordpress.org/reference/functions/is_blog_installed/)`wp-includes/functions.php` |

Determines whether WordPress is already installed.

  | 
| [_pad_term_counts()](https://developer.wordpress.org/reference/functions/_pad_term_counts/)`wp-includes/taxonomy.php` |

Adds count of children to parent count.

  | 
| [clean_term_cache()](https://developer.wordpress.org/reference/functions/clean_term_cache/)`wp-includes/taxonomy.php` |

Removes all of the term IDs from the cache.

  | 
| [wp_delete_term()](https://developer.wordpress.org/reference/functions/wp_delete_term/)`wp-includes/taxonomy.php` |

Removes a term from the database.

  | 
| [wp_version_check()](https://developer.wordpress.org/reference/functions/wp_version_check/)`wp-includes/update.php` |

Checks WordPress version against the newest version.

  | 
| [wp_load_alloptions()](https://developer.wordpress.org/reference/functions/wp_load_alloptions/)`wp-includes/option.php` |

Loads and caches all autoloaded options, if available or all options.

  | 
| [WP_User_Query::query()](https://developer.wordpress.org/reference/classes/wp_user_query/query/)`wp-includes/class-wp-user-query.php` |

Executes the query, with the current variables.

  | 
| [count_many_users_posts()](https://developer.wordpress.org/reference/functions/count_many_users_posts/)`wp-includes/user.php` |

Gets the number of posts written by a list of users.

  | 
| [wp_enqueue_media()](https://developer.wordpress.org/reference/functions/wp_enqueue_media/)`wp-includes/media.php` |

Enqueues all scripts, styles, settings, and templates necessary to use all media JS APIs.

  | 
| [_prime_post_caches()](https://developer.wordpress.org/reference/functions/_prime_post_caches/)`wp-includes/post.php` |

Adds any posts from the given IDs to the cache that do not already exist in cache.

  | 
| [get_page_by_path()](https://developer.wordpress.org/reference/functions/get_page_by_path/)`wp-includes/post.php` |

Retrieves a page given its path.

  | 
| [wp_delete_post()](https://developer.wordpress.org/reference/functions/wp_delete_post/)`wp-includes/post.php` |

Trashes or deletes a post or page.

  | 
| [wp_trash_post_comments()](https://developer.wordpress.org/reference/functions/wp_trash_post_comments/)`wp-includes/post.php` |

Moves comments for a post to the Trash.

  | 
| [wp_count_posts()](https://developer.wordpress.org/reference/functions/wp_count_posts/)`wp-includes/post.php` |

Counts number of posts of a post type and if user has permissions to view.

  | 
| [wp_count_attachments()](https://developer.wordpress.org/reference/functions/wp_count_attachments/)`wp-includes/post.php` |

Counts number of attachments for the mime type(s).

  | 
| [WP_Rewrite::page_uri_index()](https://developer.wordpress.org/reference/classes/wp_rewrite/page_uri_index/)`wp-includes/class-wp-rewrite.php` |

Retrieves all pages and attachments for pages URIs.

  | 
| [redirect_canonical()](https://developer.wordpress.org/reference/functions/redirect_canonical/)`wp-includes/canonical.php` |

Redirects incoming links to the proper URL based on the site url.

  | 
| [install_blog()](https://developer.wordpress.org/reference/functions/install_blog/)`wp-includes/ms-deprecated.php` |

Install an empty blog.

  | 
| [get_admin_users_for_domain()](https://developer.wordpress.org/reference/functions/get_admin_users_for_domain/)`wp-includes/ms-deprecated.php` |

Get the admin for a domain/path combination.

  | 
| [get_bookmarks()](https://developer.wordpress.org/reference/functions/get_bookmarks/)`wp-includes/bookmark.php` |

Retrieves the list of bookmarks.

  | 
| [get_blog_list()](https://developer.wordpress.org/reference/functions/get_blog_list/)`wp-includes/ms-deprecated.php` |

Deprecated functionality to retrieve a list of all sites.

  | 
| [wp_list_authors()](https://developer.wordpress.org/reference/functions/wp_list_authors/)`wp-includes/author-template.php` |

Lists all the authors of the site, with several options available.

  | 
| [get_last_updated()](https://developer.wordpress.org/reference/functions/get_last_updated/)`wp-includes/ms-blogs.php` |

Gets a list of most recently updated blogs.

  | 
| [wp_xmlrpc_server::mt_getTrackbackPings()](https://developer.wordpress.org/reference/classes/wp_xmlrpc_server/mt_gettrackbackpings/)`wp-includes/class-wp-xmlrpc-server.php` |

Retrieves trackbacks sent to a given post.

  | 
| [wp_xmlrpc_server::pingback_ping()](https://developer.wordpress.org/reference/classes/wp_xmlrpc_server/pingback_ping/)`wp-includes/class-wp-xmlrpc-server.php` |

Retrieves a pingback and registers it.

  | 
| [wp_xmlrpc_server::pingback_extensions_getPingbacks()](https://developer.wordpress.org/reference/classes/wp_xmlrpc_server/pingback_extensions_getpingbacks/)`wp-includes/class-wp-xmlrpc-server.php` |

Retrieves an array of URLs that pingbacked the given URL.

  | 
| [wp_xmlrpc_server::attach_uploads()](https://developer.wordpress.org/reference/classes/wp_xmlrpc_server/attach_uploads/)`wp-includes/class-wp-xmlrpc-server.php` |

Attaches an upload to a post.

  | 
| [wp_xmlrpc_server::wp_getPageList()](https://developer.wordpress.org/reference/classes/wp_xmlrpc_server/wp_getpagelist/)`wp-includes/class-wp-xmlrpc-server.php` |

Retrieves page list.

  | 
| [update_meta_cache()](https://developer.wordpress.org/reference/functions/update_meta_cache/)`wp-includes/meta.php` |

Updates the metadata cache for the specified objects.

  |

[Show 69 more](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#)
[Show less](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#)

## 󠀁[Changelog](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#changelog)󠁿

| Version | Description | 
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |

## 󠀁[User Contributed Notes](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#user-contributed-notes)󠁿

 1.   [Skip to note 5 content](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#comment-content-1461)
 2.    [fabianplaza](https://profiles.wordpress.org/fabianplaza/)  [  10 years ago  ](https://developer.wordpress.org/reference/classes/wpdb/get_results/#comment-1461)
 3.  [You must log in to vote on the helpfulness of this note](https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fclasses%2Fwpdb%2Fget_results%2F%23comment-1461)
     Vote results for this note: 9[You must log in to vote on the helpfulness of this note](https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fclasses%2Fwpdb%2Fget_results%2F%23comment-1461)
 4.  Example about how can you retrieve data from a table using get_results function:
 5.      ```php
         public function wpdocs_some_function( $some_parameter ) {
                 global $wpdb;
                 $results = $wpdb->get_results( 
                         $wpdb->prepare( "SELECT count( ID ) as total FROM {$wpdb->prefix}your_table_without_prefix WHERE some_field_in_your_table=%d", $some_parameter ) 
                 );
         }
         ```
     
 6.  **Please, note that I have used %d assuming that $some_parameter is a int value.**
 7.   [Log in to add feedback](https://login.wordpress.org/?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fclasses%2Fwpdb%2Fget_results%2F%3Freplytocom%3D1461%23feedback-editor-1461)
 8.   [Skip to note 6 content](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#comment-content-5917)
 9.    [flimm](https://profiles.wordpress.org/flimm/)  [  4 years ago  ](https://developer.wordpress.org/reference/classes/wpdb/get_results/#comment-5917)
 10. [You must log in to vote on the helpfulness of this note](https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fclasses%2Fwpdb%2Fget_results%2F%23comment-5917)
     Vote results for this note: 2[You must log in to vote on the helpfulness of this note](https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fclasses%2Fwpdb%2Fget_results%2F%23comment-5917)
 11. Don’t forget to handle the error case. Here is how to catch errors from `get_results`:
 12.     ```php
         global $wpdb;
         $result = $wpdb->get_results( "SELECT * FROM invalid query" );
         if ( $wpdb->last_error ) {
           echo 'wpdb error: ' . $wpdb->last_error;
         }
         ```
     
 13.  [Log in to add feedback](https://login.wordpress.org/?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fclasses%2Fwpdb%2Fget_results%2F%3Freplytocom%3D5917%23feedback-editor-5917)
 14.  [Skip to note 7 content](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#comment-content-7590)
 15.   [Rodrigo Vieira Eufrasio da Silva](https://profiles.wordpress.org/rodrigomct/)
     [  2 weeks ago  ](https://developer.wordpress.org/reference/classes/wpdb/get_results/#comment-7590)
 16. [You must log in to vote on the helpfulness of this note](https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fclasses%2Fwpdb%2Fget_results%2F%23comment-7590)
     Vote results for this note: 0[You must log in to vote on the helpfulness of this note](https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fclasses%2Fwpdb%2Fget_results%2F%23comment-7590)
 17. When using OBJECT_K, the docs say “Duplicate keys are discarded” but don’t say
     WHICH row survives. Looking at the source:
 18. foreach ( $this->last_result as $row ) {
      $var_by_ref = get_object_vars( $row );
     $key = array_shift( $var_by_ref ); if ( ! isset( $new_array[ $key ] ) ) { $new_array[
     $key ] = $row; } }
 19. The FIRST row for each key wins, and every later row with the same key is discarded.
     This is the opposite of how a normal PHP loop assignment behaves ($array[$key]
     = $value repeated in a loop normally means “last write wins”), so it’s an easy
     assumption to get backwards.
 20. In practice, this means: if you query something like “the latest meta value per
     post” or “the newest row per user_id” and rely on OBJECT_K to collapse duplicates,
     the row you actually get back depends entirely on the order MySQL returns rows
     in — which is NOT guaranteed unless you explicitly ORDER BY.
 21. // WRONG: assumes the “latest” row wins, but SQL row order isn’t
      // guaranteed
     without ORDER BY, so this can silently return stale data. $latest_by_post = $[wpdb](https://developer.wordpress.org/reference/classes/wpdb/)-
     >get_results( “SELECT post_id, meta_value FROM $[wpdb](https://developer.wordpress.org/reference/classes/wpdb/)-
     >postmeta WHERE meta_key = ‘my_key’”, OBJECT_K );
 22. // RIGHT: since OBJECT_K keeps the FIRST row per key, order by the
      // field that
     determines “latest” in DESCENDING order, so the row you // want to keep is the
     first one MySQL returns for each post_id. $latest_by_post = $[wpdb](https://developer.wordpress.org/reference/classes/wpdb/)-
     >get_results( “SELECT post_id, meta_value FROM $[wpdb](https://developer.wordpress.org/reference/classes/wpdb/)-
     >postmeta WHERE meta_key = ‘my_key’ ORDER BY meta_id DESC”, OBJECT_K );
 23. If your key column isn’t guaranteed unique in the result set and you don’t care
     which duplicate wins, this doesn’t matter — but if you do care (e.g. “most recent
     per group”), always pair OBJECT_K with an explicit ORDER BY, otherwise which row
     you get is essentially undefined behavior.
 24.  [Log in to add feedback](https://login.wordpress.org/?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fclasses%2Fwpdb%2Fget_results%2F%3Freplytocom%3D7590%23feedback-editor-7590)
 25.  [Skip to note 8 content](https://developer.wordpress.org/reference/classes/wpdb/get_results/?output_format=md#comment-content-3064)
 26.   [Eduard Milushi](https://profiles.wordpress.org/emilushi/)  [  8 years ago  ](https://developer.wordpress.org/reference/classes/wpdb/get_results/#comment-3064)
 27. [You must log in to vote on the helpfulness of this note](https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fclasses%2Fwpdb%2Fget_results%2F%23comment-3064)
     Vote results for this note: -2[You must log in to vote on the helpfulness of this note](https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fclasses%2Fwpdb%2Fget_results%2F%23comment-3064)
 28. The example below is using **heredoc** to write the query and then getting the
     result through `$wpdb->get_result()`. The second parameter `ARRAY_A` used on the
     function will tell to the function that we need the result to be an Array.
 29.     ```php
         $query = <<<SQL
         SELECT
                p.ID, m.meta_key, m.meta_value
         FROM
              $wpdb->posts p
              LEFT JOIN
              $wpdb->postmeta m ON p.ID = m.post_id
              WHERE
                    p.post_type IN ( 'post', 'page' )
                    AND p.post_status = 'publish'
                    AND ( m.meta_key IN ( '_yoast_wpseo_title', '_yoast_wpseo_metadesc', '_yoast_wpseo_meta-robots-noindex', 
                    '_yoast_wpseo_meta-robots-nofollow' )
                    OR 1 = 1 )
         SQL;
     
         /** @var array $result this will give us the ID and the other meta_field if any of all post types selected */
         $result = $wpdb->get_results( $query, ARRAY_A );
         ```
     
 30.  [Log in to add feedback](https://login.wordpress.org/?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fclasses%2Fwpdb%2Fget_results%2F%3Freplytocom%3D3064%23feedback-editor-3064)

You must [log in](https://login.wordpress.org/?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fclasses%2Fwpdb%2Fget_results%2F)
before being able to contribute a note or feedback.