Wordpress - Does a query executed through wpdb class get cached?
Nope, doesn't work like that. The database-related caching is minimal and mostly covers using precisely same queries during single page load.
Best way to cache persistently database and/or computationally intensive results is using Transients API to store results for fitting period of time.
The docs suggested that the output from a query was only cached for that specific request - so presumably WordPress is doing a buffered query on MySQL.
In my case, I used the wp_cache_* functions - see http://codex.wordpress.org/Class_Reference/WP_Object_Cache
Example code:
sql = "
SELECT {$wpdb->posts}.* FROM {$wpdb->posts}
LEFT JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)
LEFT JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id)
WHERE ({$wpdb->term_taxonomy}.taxonomy = 'category' AND {$wpdb->term_taxonomy}.term_id = 9849 )
AND
{$wpdb->posts}.post_status = 'publish' AND
{$wpdb->posts}.post_type = 'post' ORDER BY {$wpdb->posts}.post_title ASC";
$posts = wp_cache_get(md5($sql), 'somerandomkey');
if($posts === false) {
$posts = $wpdb->get_results($sql, OBJECT);
wp_cache_add(md5($sql), $posts, 'somerandomkey');
}
if(empty($posts)) {
echo "<p>No results found </p>";
}