Optimizing Drupal Views the Right Way

Posted on July 23, 2012

The Views module is one of the most impressive features Drupal offers. With some clicks here and there, you can build a rich display of data in minutes. But to offer this kind of flexibility, Views makes some assumptions that can hamper your site's performance. In this post, you'll find out how to improve performance dramatically.

First, a quick technical explanation of what happens. Drupal shares the main record for each content type in the node table. That means that regardless of whether an entry is a blog post or an event, it will get a record in this table. This has the advantage that building aggregated lists of all entries is quite easy.

On Joins

How does this tie into Views? When you build a view that uses a field specific to a content type - for example, event date - it doesn't know if every entry will have this field or not. So when querying the database, it tells it "give me this node. And if it has a corresponding field called event date, give me that as well." This is called a LEFT JOIN, and it's quite slow. If on the other hand, we changed the query ever so slightly to "give me this node and the corresponding field event date," then the whole thing will execute much quicker. By doing this, the query is executing an INNER JOIN which joins each node entry with each event entry one to one.

Learning Drupal? Subscribe to my Drupal articles, tips and tutorials.

Keep in mind, this will only work if you want the result set to contain events only. If you need to mix events and blog posts, you're out of luck. Well, sort of1.

On Pagers

Guess what the most expensive part of your view is? That's right, the pager at the bottom. Turns out, counting in databases is slow. Really slow2. So get rid of as many COUNT queries as you can. What's this got to do with pagination? To accurately paginate, Views executes a COUNT query on the entire result set. That means that even if you're displaying 20 records out of a million, Views will need to count all 20 million rows. This takes a long time.

So what are your options? You've got two3. One is to get rid of pagination entirely. The other is to use a less accurate pager. We won't go over the former, because clients/product managers can be notoriously inflexible - good luck trying to convince them to use no pagination. But a less accurate pager? They can probably live with that.

So how does a less accurate pager work? First, it eliminates the "last" option. That means you don't need to know how many total results there are. Skipping more than 2 pages ahead at a time is also nixed. With these compromises, you can get rid of the COUNT query and simply use the current offset to build the pager. You'll only be able to accurately jump to pages before the one you're on, but often this is good enough.

On Distinct

DISTINCT clauses have their time and place - never. No but really, try to avoid them. Most of the time, you can eliminate the need for them by crafting a better query. Duplicates rows are usually a symptom of a bigger problem. So you shouldn't mark your view queries as needing DISTINCT unless you're absolutely certain it's needed. Or if you're lazy. Regardless of the reason, it will slow down your query. Worse - when you use DISTINCT in a view, a GROUP BY clause will be inserted as well. This will also slow down your query significantly. Fortunately, disabling DISTINCT will rid you of both problems. Of course, do check to make sure you're not getting duplicate results. If you're using INNER JOIN as described above, you most likely won't.

The Changes

After all that technical talk, let's actually apply these changes. Three assumptions:

  1. Let's assume your view's machine name is my_view.
  2. Let's also assume it's joining to a table called content_type_event for the additional event information.
  3. Let's pretend you've got a module floating around called my_module.

Here's how to do this The Right Way™:

 * Implements hook_views_query_alter().                                         
 * Disables distinct and turns LEFT joins into INNER joins. This drammatically  
 * speeds up performance.                                                       
function my_module_views_query_alter(&$view, &$query) {                         
  if ($view->name == "my_view") {                                               
    $query->table_queue['content_type_notice']['join']->type = 'INNER';         
    $query->distinct = 0;                                                       

What about the pager? That's even easier. Just download the lite pager module and select it as the paging option for your view.


Views can be really helpful, no doubt. And it can get a bad rap about performance. But that's because - without much user input - it has to make a lot of assumptions to construct the query. With just a little bit of code, we can guide the query builder down the right path.

  1. You could just load the common data from the node table, then individually fetch the rest of the information with a query per row. 

  2. If you're using the MyISAM table engine for MySQL, disregard this. 

  3. There's a third option: query hinting. But it's beyond the scope of this article. 


Adedapo Harjuone AjuwonNov. 2, 2017, 10:42 a.m.

Highly resourceful content you have here. Subscribed already

jessica alexFeb. 22, 2019, 10:37 a.m.

Wow! I’m browsing away perusing your web journal from my lap! Simply needed to say I adore perusing your website and anticipate every one of i need an assignment your posts! Carry on the eminent work.Feel free to browse for getting more information about writing work

hijMarch 7, 2019, 10:11 a.m.

Nice blog, the article you have shared is good.This article is very useful. My friend suggest me to use this blog. MBA college in punjab

hijMarch 28, 2019, 11:17 a.m.

Apple products are revered for its quality, precision and great design. SRSG started its operations as Apple technology partners in the year 1997.
Apple reseller in Mumbai
Apple authorized service center in Kolkata
ipad service center in delhi
Radio station consultants
system integration service providers

Kaitlyn JohnMarch 29, 2019, 11:39 a.m.

Thank you for sharing such an informative article with us. Many concepts on Optimizing Drupal Views the Right Way is shared here. dermal fillers Many informative things such as on joints, on pages, etc, are clearly explained. Even a beginner can understand what the author tries to share.

dsdsdMay 6, 2019, 5:35 a.m.

Il est également possible de voir des histoires sur les dommages causés aux intérêts des clients à partir des informations, replique montre suisse d'Internet et d'autres canaux. En conséquence, les clients ont tendance à être préparés pour les vendeurs, en particulier ceux qui sont actifs dans la vente sur site, et sont encore plus réticents à entrer en contact avec eux. La tag Heuer montre est associée à un bracelet en caoutchouc doublé de tissu qui améliore la durabilité du bracelet et ajoute au confort.

NikieMay 10, 2019, 12:06 p.m.

We offer calculated visibility for the design and development of technology platforms through ourintensive research-based approach, consistency in performance, and adept decision-making caliber.
website design company in malaysia
online digital marketing malaysia
Search engine optimization companies in malaysia

Alan MartinJune 9, 2019, 12:25 p.m.

Can I simply just say what a comfort to find somebody that really knows what they're discussing on the internet. assignment writing help uk You definitely understand how to bring an issue to light and make it important. More and more people really need to read this and understand this side of your story. It's surprising you're not more popular since you certainly possess the gift

Jacob liamJune 10, 2019, 1:16 p.m.

Assignment Help Online Online provides you best support on the assignment related to management and business and business operations.Accounting Assignment Help

Golalai IsmaeelJune 24, 2019, 11:52 a.m.

The amazing way to discribe the method to optimize drupal views. I appreciate your thoughtful writing. I've tried the same thing on top android spy software in the market and found it very optimized at the end.

John NoelsJuly 6, 2019, 6:40 a.m.

Instant Assignment Help offers the best online assignment writing help to the college students who wish to score top grades in their academic career.

GosJuly 12, 2019, 10:36 a.m.

The goal of the society is to create professionally well skilled students To achieve the said goal, arrangements have been made with the pioneers and front runners both in India and abroad.
top cbse school in premnagar
The Health system is created in a proficient way of expanding the network in the multispecialty services. With the ever-growing population, the hospital has announced many ambitious plans that have ultimately lead to the excellence.
multispeciality hospital in hisar
ivf treatment in hisar

GGJuly 27, 2019, 12:11 p.m.

Good Post

ninaAug. 2, 2019, 6:48 a.m.

yeah i am also facing this when i was visiting chiltan pure moringa oil product page by the way thank you for letting us now good work dude wanna know visit here.

kimyAug. 2, 2019, 6:51 a.m.

it's just coincidence that i have see this on different website so i just wanna say my friend buying kishmish organic cucumber face mask for further info you can visit it's a best face mask ever goood work.

alyAug. 2, 2019, 6:56 a.m.

thank you very much for such a great information that's a very good conclusion. because last day i was searching about gloss whitening cream so i got a on a website that's have a problem by the way wanna know more about whitening cream visit there.

hrtAug. 15, 2019, 9:58 a.m.


Terence MunozAug. 18, 2019, 9:43 a.m.

How to choose the tire size for your car? While tire size can be a bit intimidating at first for car buyers, if the car looks good on your spec sheet, you can start picking tires from this list that you can actually get good on. tiresout.com

Arpit SharmaAug. 31, 2019, 7:23 a.m.

This article is an appealing wealth of useful informative that is interesting and well-written. Thank you for always going above and beyond information to publish here. Travel ERP Software

FreyaSept. 5, 2019, 8:08 a.m.

This post is very helpful to me because of Myself a tutor in the IT industry. This post can be shared with my students for their reference. hoping for more posts in future.

donSept. 6, 2019, 11:52 a.m.

When you provide users with more infrastructure management solutions helpful content then it becomes a good idea to have a helpful site which really provides a big collection of thoughts through the website for readers. The wide variety of such appropriate thoughts and subjects makes the website more impressive to users of all kinds.

selfieSept. 18, 2019, 11:25 a.m.

Welcome to the world of gaming, where life is fast paced and interesting. There is always an adventure waiting for you online.
csgo smurf accounts
csgo vip accounts

kingSept. 20, 2019, 10:10 a.m.

Nice blog, the article you have shared is good.This article is very useful. My friend suggest me to use this blog.oxycodone where to buy

kyron rockoSept. 21, 2019, 6:18 p.m.

If you've been doing research on DHEA, you've probably also heard of 7-Keto DHEA. But what is the difference and which one is the right one for you? must read

furySept. 23, 2019, 1:39 p.m.

I am happy to find this post very useful for me, as it contains lot of information. I like the way you composed this data.Dc party rental

molly jonesSept. 25, 2019, 7:49 a.m.

From CCTV recognition in colossal corporate working environments to your Home Automation, from Network Solutions in top IT relationship to POS in your favored retail stores, LNS client base has spread transversely over level of endeavors and now with DPS-Certification (Department of Protective System) LNS is making to wind up one of driving IT security and IT reinforce relationship in Dubai and offering IT support benefits in wherever all through the UAE.

LNS is known for it's bleeding-edge types of progress and unmatchable 'after-bargain affiliations'. In spite of whether you need a little scale approach or regulate various structures, LNS is among the best cctv installation companies in dubai has the fit social illicit relationship and the creation feeling of how to structure the best solution for your needs. Contact us today for more information and a talk meeting at your region.

We have handy incorporation in following IT affiliations and outlines

• CCTV and Security Solutions

• Biometric Solutions

• Network Solutions

• Server and Data taking care of Solutions

• Sound System Solutions

• Telecom Solutions

• Conference Solutions

• Home Automation Solutions

• POS and Retail Solutions

• Enterprise IT-Infra Solutions

• Annual Maintenance

• Online and web Solutions

Esme TaylorSept. 28, 2019, 10:09 a.m.

When students don’t have enough time to complete their assignments they search for online writes to write my assignment for me. In that case, they can get instant help from expert writers of Myassignmenthelp.com to when they request to write my assignment. The life of a student involves the dilemma of preparing multiple assignments at once like homework, dissertation, thesis paper, research paper and more. Well, you can be sure that your prayers have been heard, as MyAssignmenthelp.com is here to salvage your academic performance.

lesaSept. 30, 2019, 1:04 p.m.

We are the Kenya safari tours specialists. We are wild about wildlife, excited about the natural world, and extremely proud to call Kenya our home.property management in medford oregon

Lewis PlastererHugo PlastererOct. 3, 2019, 12:40 p.m.

Greetings, I should say it was a totally great experience for me and my dog when we called in at your web blog. I hope you don't mind if I commend you on the superior quality of your work and also to send you bon chance with everything as you move forward into the future. It unquestionably was a great adventure to view your website and I'll most certainly be calling back again shortly to see just how you are getting on. Many thanks and if luck is on my side I shall no doubt see you here again before I die - Lewis PlastererGreetings, I have to say it was a truly fine experience for me personally when I dropped by at your web blog. I just wished to praise you on the exceptional quality of your work and also to send your team bon chance as you move on as time goes on. It unquestionably was a hoot to look at your web site and I'll naturally be calling back once more to discover just how you are getting on. Thanks a lot and if luck is on my side I shall doubtless see you here again before I die - Hugo Plasterer

Sophie GreenOct. 4, 2019, 5:58 a.m.

The dissertation can be influenced by many things, which one of them is the length of the work. Writing dissertation is the way to show your expertise on a certain subject, but it should maintain some courtesies in order to present them in front of a dissertation committee. The length factor could be a great impact while evaluating dissertations. So one should be careful about the length and have a fair idea of what be an average length of a dissertation. To get a great idea regarding the perfect length of a dissertation paper, click here and get assistance.

how to write an annotated bibliographyOct. 7, 2019, 11:49 a.m.

Your blog is very good and very informative. Your blog post is very useful. It is exceptionally accommodating for me I learn new information from your post. I truly love your blog post.Thank you for sharing this post with us keep it up.Students always asking us how to write an annotated bibliography in USA? What we suggest them is to hire assignment helper from 500+ writers online which were write your assignment with the help of best free plagiarism checker . For More Detail : Harvard Referencing generator

IDN PokerOct. 11, 2019, 4:04 p.m.

Kronospoker Situs Judi Online, IDN Poker, IDN Poker Mobile, Agen Poker Terpercaya Indonesia untuk permainan Poker Online, Domino Qiu Qiu, Ceme Keliling, Capsa Susun dan Super10

RamizOct. 12, 2019, 2:34 p.m.

Thanks for such a nice post. online class help

Keira TayorOct. 17, 2019, 9:42 a.m.

The purpose of descriptive writing is to writer’s thoughts on the paper. There is no scope for copying text in descriptive essay writing. Hence, our writers strictly follow an anti-plagiarism policy. Are you worried about “adding reference lists in Vancouver referencing style? Simply read it, and consider implementing the same in your papers. Looking for college essay writer in Australia that helps you achieve your academic goal? You are at the right place. Send your requirements at EssayAssignmentHelp.com.au.

Omeo JonesOct. 17, 2019, 12:41 p.m.

The study destination Down Under for thousands of international students each year just received its own custom coursework writing service for its domestic students. Students can now breathe a sigh of relief as the professional writer service at Myassignmenthelp.com are now providing 24x7 teaching and essay writing support for them. Our customers rely on us because we provide them the opportunity to get quality essays written by professionals. Know more about kaplan essay help.

Organizational Culture Assignment HelpOct. 18, 2019, 12:56 p.m.

Searching for corporate culture assignment help? Our experts are capable of providing quality organizational cultural assignment help at most reasonable price.


Organizational Culture Assignment HelpOct. 18, 2019, 12:58 p.m.

Searching for corporate culture assignment help? Our experts are capable of providing quality organizational cultural assignment help at most reasonable price.

Organizational Culture Assignment Help

Katie JoyceOct. 18, 2019, 8:32 p.m.

Great post. Articles that have meaningful and insightful comments are more enjoyable, at least to me. It’s interesting to read what other people thought and how it relates to them or their clients, as their perspective could possibly help you in the future.

Colinas de MontealegreOct. 20, 2019, 11:20 a.m.

Excellent Blog! I have bookmarked your online journal, the articles are path superior to anything other comparable web journals.. a debt of gratitude is in order for an extraordinary online journal!Colinas de Montealegre

#TuesdayThoughtsOct. 22, 2019, 1:12 p.m.

According to the latest review, it is found that students are mostly choosing myassignmenthelp for their unmatched quality of service. There are lots of positive reviews that add to My Assignment Help. This assignment help service is the best in the market according to students’ review. It has been found that most of the students prefer their service because of the quality, price and other beneficial aspects. By analyzing some of the top reviews, let us know why this service has been considered as the best one for the help seekers. The only way to get a detailed insight of the site is to go through the reviews that are posted on the best essay writing service, Before selecting a homework help websites, students must read the reviews. Reading reviews is necessary as the students get to know which service providers are genuine and which is fake. To mislead the visitors, a lot of review are posted in websites. For students who are going to write and looking for topics. Which side of the problem are you going to write about and what solution can you offer.

Steven RowOct. 22, 2019, 7:26 p.m.

It’s interesting to read what other people thought and how it relates to them or their clients, as their perspective could possibly help you in the future. Write For Us Digital Marketing

fazlanOct. 23, 2019, 7:30 a.m.

I am often to blogging i genuinely appreciate your posts. The content has truly peaks my interest. I’m going to bookmark your internet site and keep checking for brand new info. 안전놀이터

t shirt supplier singaporeOct. 23, 2019, 9:59 a.m.

Amazing post ,this is very informative post,thanks for share it with us t shirt supplier singapore

lisaOct. 27, 2019, 8:37 a.m.

Yes you are right, and I just thought I’d say keep it up the fantastic work! It is one of the most excellent blog in these types of blogs in my opinion. Each word of your platform is very informative.outdoor wood burner

wordpress maintenance servicesOct. 27, 2019, 11:11 a.m.

I believe these type of service very helpful for society because they have decrease scandal in society and provide crime free society. So I realize and hope we will start that type of service in our country.wordpress maintenance services

lisaOct. 28, 2019, 10:17 a.m.

Are you searching for a mobile app development company in Canada? We can help you right away with all your needs. Every business today has turned online. You name them and you will find them on the internet. You do not have to wander around the market and look for any service you want. You get everything at your doorstep just within few clicks.sexy indian Halloween costume

lisaOct. 28, 2019, 10:42 a.m.

That is a pretty good point that you are having in this article and I am pretty sure that we are able to make good conversation about it. In the modern days technology is the one thing that keeps us moving.elektra Halloween costume

lisaOct. 28, 2019, 10:48 a.m.

we can ready to do useful for others and remain sound for long time. The data in this article is very instructive for perusing and ought to advance on different systems.landoll trailers

Beam Load CellsOct. 28, 2019, 11:07 a.m.

Yes art is like a new picture of life to see life in new perspective. The mind of an artist is seeing beyond the picture or this strategy helps them to solve many real life problems to see the issue into new or different perspective they can see all the sides of picture.Beam Load Cells

lisaOct. 28, 2019, 11:16 a.m.

There are so many online assignment help website to help you. It is important to choose the best one among the many. Before choosing the one go for that website reviews first and then check the website like their services, prices, discounts, website interface, and everything. Go through their samples that how they write so, you can understand the level of their experts.rgn trailers

amanda knoxOct. 29, 2019, 7:30 a.m.

If you need assistance with your term paper, get help from the companies we've checked and selected! They offer best term paper service UK you can trust.

Face Painting IdeasOct. 31, 2019, 2:22 p.m.

This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value. Im glad to have found this post as its such an interesting one! I am always on the lookout for quality posts and articles so i suppose im lucky to have found this. Face Painting Ideas

SEO Agency in IndiaNov. 2, 2019, 10:58 a.m.

Amazing article .Thanks for sharing this .

SEO Agency India

modafinil online pharmacyNov. 2, 2019, 5:13 a.m.

A scandal can be extensively characterized as an allegation or allegations that get a wide introduction. For the most part, there is an adverse impact on the believability of the individual or association included. Society is scandalized when it is made mindful of glaring ruptures of good standards or legitimate necessities.modafinil online pharmacy

TopXListingNov. 2, 2019, 10:37 a.m.

Topxlisting is a B2B research, reviews, and rating firm which collects data from various companies and picks the best companies in mobile app development, web app development, and SEO field that can deliver a well organized and systematic record to the client.

rickNov. 2, 2019, 12:24 p.m.

I see that you've published another amazing article here, because I will use this content in my altomerge paper, because I really need to do that. If I don't do that, I will be in big trouble, and that will be bad for me.

TopxlistingNov. 4, 2019, noon

Thanks for sharing this post . It is very informative .


marcelbrevenNov. 5, 2019, 2:47 a.m.

Learn how to benefit from Social Media Marketing in the most profitable way possible, by simple learning a few main strategies. Basically, everything is learnable, and the truth is that you can master any skill, if you have the willpower to do it.

marcelbrevenNov. 5, 2019, 2:48 a.m.

fruitful agency ayoub habcy Numerous social media marketing courses are available to business owners who want to utilize social media websites for promoting the products and services that they offer. Using these websites won't require much advanced knowledge on technology because as long as you know how to write and submit good and high quality content, business marketing on the internet will be a piece of cake to you. Social media marketing is actually easy because as long as you know the basics, you can survive the intense business marketing competition going on in the world wide web.

Jodie J MitchellNov. 5, 2019, 2:06 p.m.

The information provided by you is really very good and helpful for me. Keep sharing good information. https://essaytrick.co.uk/

kate daisyNov. 6, 2019, 10:41 a.m.

Amazing, it looks so beautiful, I love it. shell shockers

maskedsingerNov. 7, 2019, 10:02 a.m.

MyAssignmentHelp Review never ceases to surprise me. I was already a fan of their amazing range of services. But last week I got to experience the efficacy of their customer support team. That’s when I found My Assignment Help Review. They are simply the best. The only good thing that I found on the internet is MyAssignmentHelp which has met my requirements for assignment writing and delivered the support on time.

Sophie GreenNov. 7, 2019, 10:05 a.m.

At MyAssignmenthelp.com, we understand that attending a nursing course can be more taxing than it seems. You don’t just need to study and appear for tests. You also need to prepare a number of assignments and tasks, including nursing dissertations. And if you cannot spare enough time for these tasks, it won't be possible for you to pnurepare a remarkable paper without any kind of nursing dissertation help. We keep things very simple at MyAssignmenthelp.com. All our services that offer nursing dissertation help online are easy to avail. And most importantly, they cater to the specific needs of your dissertation. Just let us know about your requirements, and we will deliver the much-needed assistance accordingly. Philosophy dissertation help

SamNov. 7, 2019, 12:47 p.m.

Students who are looking for assignment help australia or assignment help perth are more likely to order their projects through us, because they know what quality they will be getting.

captain cook snorkeling tourNov. 7, 2019, 3:56 p.m.

Hello, An impressive share! I have just forwarded this onto a friend who has been conducting a little research on this. And he actually ordered me dinner simply because I found it for him... lol. So allow me to reword this.... Thank YOU for the meal!! But yeah, thanx for spending the time to talk about this topic here on your web site.captain cook snorkeling tour

TopxlistingNov. 8, 2019, 10:25 a.m.

Great blog! Keep it up. Thanks for sharing it with us Topxlisting

Emma DavisNov. 11, 2019, 11:32 a.m.

Harvard referencing is a note citation system to cite the academic papers or any important documents. This referencing generator tool is also known as the documentary style note. To include the process of referencing and citations in the academic paper is very important to increase the readability of the paper and it will eventually help students in scoring good grades. This Harvard citation generator tool has been designed to create the most accurate formatting and referencing style for your academic paper, that too within a matter of minutes. So all your confusion over Harvard citation and referencing style will be resolved when you select our online Harvard reference generator tool from Allessaywriter.com.

RaurakNov. 12, 2019, 7:41 a.m.

I have read your article, it is very informative and helpful for me.I admire the valuable information you offer in your articles. Thanks for posting it.. Topxlisting | Best SEO Companies in India

Jack JonasNov. 13, 2019, 7:33 a.m.

We know it becomes frustrating when we got stuck with an academic paper that seems impossible to solve. Well, we have the perfect solution for you. Just avail our academic paper writing service in three simple steps and submit an impeccably drafted paper within the instructed deadline. No matter how complex or uncommon the problem is, we have the necessary resources to deal with it easily.

Writing help is one of the oldest running paper writing services on the internet that has been consistent in helping students with their academic needs. In fact, we have introduced a number of custom paper writing service Singapore that can solve your specific needs with perfection. So, place an order today and see a positive change in your academic performance.

indeedseoNov. 13, 2019, 10:35 a.m.

Nice Post!! I am looking for this kind of posts from last many days. thanks for share it with us best seo company india 2019

SamNov. 14, 2019, 6:21 a.m.

If you need any my assignment help related to Law, Human Resource, Leadership, Engineering, Marketing, Management, Finance, Economics or Accounts, we can help you out with it. If you are struggling with your University assignments and need Urgent Assignment Help than you are at the right place, with services like My Assignment Help,Assignment Help Australia and Essay help etc.


Post New Comment