I am making an template and I have to write a completely custom sql query.

This is exactly what I personally use at this time however it does not work

$wp_query = new WP_Query(array($query, 'paged' => get_query_var('paged')));

I additionally use wordpress_pagenavi for pagination so I'm a little limited.

wp_pagenavi(array( 'query' => $wp_query ));

Here's one particular query that will get typically the most popular publish (using the "Wordpress Popular Posts" wordpress plugin)

SELECT pl_posts.* 
FROM pl_posts  
INNER JOIN pl_popularpostsdata ON pl_posts.ID = pl_popularpostsdata.postid 
WHERE pl_posts.post_type = 'post' 
  AND pl_posts.post_date < NOW() 
  AND pl_posts.post_status = 'publish' 
ORDER BY pl_popularpostsdata.pageviews DESC 
LIMIT 0, 5

However , wordpress_query just returns all posts and ignore my query.

While using the paged option without posts_per_the first page would assume it uses the default quantity of posts per page in the blog configurations.

Simply employ:

$wp_query = new WP_Query(array($query, 'posts_per_page' => NUMBER, 'paged' => get_query_var('paged')));