<p>Conventional wisdom states that stored procedures are always faster. So, since they're always faster, use them <strong>ALL THE TIME</strong>.</p>

<p>I am pretty sure this is grounded in some historical context where this was once the case. Now, I'm not advocating that Stored Procs are not needed, but I want to know in what cases stored procedures are necessary in modern databases such as MySQL, SQL Server, Oracle, or &lt;<em>Insert_your_DB_here</em>&gt;. Is it overkill to have ALL access through stored procedures?</p>

[{'answer_id': 59883, 'author': 'Ryan Lanciaux', 'author_id': 1385358, 'author_profile': 'https://Stackoverflow.com/users/1385358', 'pm_score': 1, 'selected': False, 'text': '<p>I don\'t know that they are faster. I like using ORM for data access (to not re-invent the wheel) but I realize that\'s not always a viable option. </p>\n\n<p>Frans Bouma has a good article on this subject : <a href="http://weblogs.asp.net/fbouma/archive/2003/11/18/38178.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/fbouma/archive/2003/11/18/38178.aspx</a></p>\n'}, {'answer_id': 59884, 'author': 'spoulson', 'author_id': 3347, 'author_profile': 'https://Stackoverflow.com/users/3347', 'pm_score': 0, 'selected': False, 'text': '<p>Stored procs are great for cases where the SQL code is run frequently because the database stores it tokenized in memory.  If you repeatedly ran the same code outside of a stored proc, you will likey incur a performance hit from the database reparsing the same code over and over.</p>\n\n<p>I typically frequently called code as a stored proc or as a SqlCommand (.NET) object and execute as many times as needed.</p>\n'}, {'answer_id': 59885, 'author': 'Alvaro Rodriguez', 'author_id': 1550, 'author_profile': 'https://Stackoverflow.com/users/1550', 'pm_score': 2, 'selected': False, 'text': '<p>Read Frans Bouma\'s <a href="http://weblogs.asp.net/fbouma/archive/2003/11/18/38178.aspx" rel="nofollow noreferrer">excellent post</a> (if a bit biased) on that.</p>\n'}, {'answer_id': 59892, 'author': 'Jon Galloway', 'author_id': 5, 'author_profile': 'https://Stackoverflow.com/users/5', 'pm_score': 5, 'selected': False, 'text': '<p>In many cases, stored procedures are actually slower because they\'re more genaralized. While stored procedures can be highly tuned, in my experience there\'s enough development and institutional friction that they\'re left in place once they work, so stored procedures often tend to return a lot of columns "just in case" - because you don\'t want to deploy a new stored procedure every time you change your application. An OR/M, on the other hand, only requests the columns the application is using, which cuts down on network traffic, unnecessary joins, etc.</p>\n'}, {'answer_id': 59894, 'author': 'Danimal', 'author_id': 2757, 'author_profile': 'https://Stackoverflow.com/users/2757', 'pm_score': 1, 'selected': False, 'text': '<p>All I can speak to is SQL server. In that platform, stored procedures are lovely because the server stores the execution plan, which in most cases speeds up performance a good bit. I say "in most cases", because if the SP has widely varying paths of execution you might get suboptimal performance. However, even in those cases, some enlightened refactoring of the SPs can speed things up.</p>\n'}, {'answer_id': 59901, 'author': 'Steve Morgan', 'author_id': 5806, 'author_profile': 'https://Stackoverflow.com/users/5806', 'pm_score': 3, 'selected': False, 'text': '<p>It\'s a debate that rages on and on (for instance, <a href="https://stackoverflow.com/questions/22907/which-is-better-ad-hoc-queries-or-stored-procedures">here</a>).</p>\n\n<p>It\'s as easy to write bad stored procedures as it is to write bad data access logic in your app.</p>\n\n<p>My preference is for Stored Procs, but that\'s because I\'m typically working with very large and complex apps in an enterprise environment where there are dedicated DBAs who are responsible for keeping the database servers running sweetly.</p>\n\n<p>In other situations, I\'m happy enough for data access technologies such as LINQ to take care of the optimisation.</p>\n\n<p>Pure performance isn\'t the only consideration, though. Aspects such as security and configuration management are typically at least as important.</p> \n\n<p>Edit: While Frans Bouma\'s article is indeed verbose, it misses the point with regard to security by a mile. The fact that it\'s 5 years old doesn\'t help its relevance, either.</p>\n'}, {'answer_id': 59907, 'author': 'Flory', 'author_id': 5551, 'author_profile': 'https://Stackoverflow.com/users/5551', 'pm_score': 2, 'selected': False, 'text': "<p>I prefer to use SP's when it makes sense to use them.  In SQL Server anyway there is no performance advantage to SP's over a parametrized query.</p>\n\n<p>However, at my current job my boss mentioned that we are forced to use SP's because our customer's require them.  They feel that they are more secure.  I have not been here long enough to see if we are implementing role based security but I have a feeling we do.</p>\n\n<p>So the customer's feelings trump all other arguments in this case.</p>\n"}, {'answer_id': 59920, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 3, 'selected': False, 'text': "<p>There is no noticeable speed difference for stored procedures vs parameterized or prepared queries on most modern databases, because the database will also cache execution plans for those queries.  </p>\n\n<p>Note that a parameterized query is not the same as ad hoc sql.</p>\n\n<p>The main reason imo to still favor stored procedures today has more to do with security.  If you use stored procedures <em>exclusively</em>, you can disable INSERT, SELECT, UPDATE, DELETE, ALTER, DROP, and CREATE etc permissions for your application's user, only leaving it with EXECUTE.  </p>\n\n<p>This provides a little extra protection against <em>2nd order</em> sql injection.  Parameterized queries only protect against <em>1st order</em> injection.</p>\n"}, {'answer_id': 59923, 'author': 'Jon Ericson', 'author_id': 1438, 'author_profile': 'https://Stackoverflow.com/users/1438', 'pm_score': 3, 'selected': False, 'text': "<p>Obviously, actual performance ought to be measured in individual cases, not assumed.  But even in cases where performance is <em>hampered</em> by a stored procedure, there are good reasons to use them:</p>\n\n<ol>\n<li><p>Application developers aren't always the best SQL coders.  Stored procedures hides SQL from the application.</p></li>\n<li><p>Stored procedures automatically use bind variables.  Application developers often avoid bind variables because they seem like unneeded code and show little benefit in small test systems.  Later on, the failure to use bind variables can throttle RDBMS performance.</p></li>\n<li><p>Stored procedures create a layer of indirection that might be useful later on.  It's possible to change implementation details (including table structure) on the database side without touching application code.</p></li>\n<li><p>The exercise of creating stored procedures can be useful for documenting all database interactions for a system.  And it's easier to update the documentation when things change.</p></li>\n</ol>\n\n<p>That said, I usually stick raw SQL in my applications so that I can control it myself.  It depends on your development team and philosophy.</p>\n"}, {'answer_id': 59932, 'author': 'Matt Rogish', 'author_id': 2590, 'author_profile': 'https://Stackoverflow.com/users/2590', 'pm_score': 9, 'selected': True, 'text': '<blockquote>\n  <p><strong>NOTE</strong> that this is a general look at stored procedures not regulated to a specific\n  DBMS. Some DBMS (and even, different\n  versions of the same DBMS!) may operate\n  contrary to this, so you\'ll want to\n  double-check with your target DBMS\n  before assuming all of this still holds.</p>\n  \n  <p>I\'ve been a Sybase ASE, MySQL, and SQL Server DBA on-and off since for almost a decade (along with application development in C, PHP, PL/SQL, C#.NET, and Ruby). So, I have no particular axe to grind in this (sometimes) holy war.</p>\n</blockquote>\n\n<p>The historical performance benefit of stored procs have generally been from the following (in no particular order):</p>\n\n<ul>\n<li>Pre-parsed SQL</li>\n<li>Pre-generated query execution plan</li>\n<li>Reduced network latency</li>\n<li>Potential cache benefits</li>\n</ul>\n\n<p><strong>Pre-parsed SQL</strong> -- similar benefits to compiled vs. interpreted code, except on a very micro level. </p>\n\n<p><em>Still an advantage?</em> \nNot very noticeable at all on the modern CPU, but if you are sending a single SQL statement that is VERY large eleventy-billion times a second, the parsing overhead can add up.</p>\n\n<p><strong>Pre-generated query execution plan</strong>. \nIf you have many JOINs the permutations can grow quite unmanageable (modern optimizers have limits and cut-offs for performance reasons). It is not unknown for very complicated SQL to have distinct, measurable (I\'ve seen a complicated query take 10+ seconds just to generate a plan, before we tweaked the DBMS) latencies due to the optimizer trying to figure out the "near best" execution plan. Stored procedures will, generally, store this in memory so you can avoid this overhead.</p>\n\n<p><em>Still an advantage?</em> \nMost DBMS\' (the latest editions) will cache the query plans for INDIVIDUAL SQL statements, greatly reducing the performance differential between stored procs and ad hoc SQL. There are some caveats and cases in which this isn\'t the case, so you\'ll need to test on your target DBMS.</p>\n\n<p>Also, more and more DBMS allow you to provide optimizer path plans (abstract query plans) to significantly reduce optimization time (for both ad hoc and stored procedure SQL!!).</p>\n\n<blockquote>\n  <p><strong>WARNING</strong> Cached query plans are not a performance panacea. Occasionally the query plan that is generated is sub-optimal.\n  For example, if you send <code>SELECT *\n  FROM table WHERE id BETWEEN 1 AND\n  99999999</code>, the DBMS may select a\n  full-table scan instead of an index\n  scan because you\'re grabbing every row\n  in the table (so sayeth the\n  statistics). If this is the cached\n  version, then you can get poor\n  performance when you later send\n  <code>SELECT * FROM table WHERE id BETWEEN\n  1 AND 2</code>. The reasoning behind this is\n  outside the scope of this posting, but\n  for further reading see:\n  <a href="http://www.microsoft.com/technet/prodtechnol/sql/2005/frcqupln.mspx" rel="noreferrer">http://www.microsoft.com/technet/prodtechnol/sql/2005/frcqupln.mspx</a>\n  and\n  <a href="http://msdn.microsoft.com/en-us/library/ms181055.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms181055.aspx</a>\n  and <a href="http://www.simple-talk.com/sql/performance/execution-plan-basics/" rel="noreferrer">http://www.simple-talk.com/sql/performance/execution-plan-basics/</a></p>\n  \n  <p>"In summary, they determined that\n  supplying anything other than the\n  common values when a compile or\n  recompile was performed resulted in\n  the optimizer compiling and caching\n  the query plan for that particular\n  value. Yet, when that query plan was\n  reused for subsequent executions of\n  the same query for the common values\n  (‘M’, ‘R’, or ‘T’), it resulted in\n  sub-optimal performance. This\n  sub-optimal performance problem\n  existed until the query was\n  recompiled. At that point, based on\n  the @P1 parameter value supplied, the\n  query might or might not have a\n  performance problem."</p>\n</blockquote>\n\n<p><strong>Reduced network latency</strong>\nA) If you are running the same SQL over and over -- and the SQL adds up to many KB of code -- replacing that with a simple "exec foobar" can really add up.\nB) Stored procs can be used to move procedural code into the DBMS. This saves shuffling large amounts of data off to the client only to have it send a trickle of info back (or none at all!). Analogous to doing a JOIN in the DBMS vs. in your code (everyone\'s favorite WTF!)</p>\n\n<p><em>Still an advantage?</em>\nA) Modern 1Gb (and 10Gb and up!) Ethernet really make this negligible. \nB) Depends on how saturated your network is -- why shove several megabytes of data back and forth for no good reason?</p>\n\n<p><strong>Potential cache benefits</strong>\nPerforming server-side transforms of data can potentially be faster if you have sufficient memory on the DBMS and the data you need is in memory of the server.</p>\n\n<p><em>Still an advantage?</em>\nUnless your app has shared memory access to DBMS data, the edge will always be to stored procs.</p>\n\n<p>Of course, no discussion of Stored Procedure optimization would be complete without a discussion of parameterized and ad hoc SQL.</p>\n\n<p><strong>Parameterized / Prepared SQL</strong><br>\nKind of a cross between stored procedures and ad hoc SQL, they are embedded SQL statements in a host language that uses "parameters" for query values, e.g.:</p>\n\n<pre><code>SELECT .. FROM yourtable WHERE foo = ? AND bar = ?\n</code></pre>\n\n<p>These provide a more generalized version of a query that modern-day optimizers can use to cache (and re-use) the query execution plan, resulting in much of the performance benefit of stored procedures.</p>\n\n<p><strong>Ad Hoc SQL</strong>\nJust open a console window to your DBMS and type in a SQL statement. In the past, these were the "worst" performers (on average) since the DBMS had no way of pre-optimizing the queries as in the parameterized/stored proc method.</p>\n\n<p><em>Still a disadvantage?</em>\nNot necessarily. Most DBMS have the ability to "abstract" ad hoc SQL into parameterized versions -- thus more or less negating the difference between the two. Some do this implicitly or must be enabled with a command setting (SQL server: <a href="http://msdn.microsoft.com/en-us/library/ms175037.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms175037.aspx</a> , Oracle: <a href="http://www.praetoriate.com/oracle_tips_cursor_sharing.htm" rel="noreferrer">http://www.praetoriate.com/oracle_tips_cursor_sharing.htm</a>).</p>\n\n<p><strong>Lessons learned?</strong>\nMoore\'s law continues to march on and DBMS optimizers, with every release, get more sophisticated. Sure, you can place every single silly teeny SQL statement inside a stored proc, but just know that the programmers working on optimizers are very smart and are continually looking for ways to improve performance. Eventually (if it\'s not here already) ad hoc SQL performance will become indistinguishable (on average!) from stored procedure performance, so any sort of <em>massive</em> stored procedure use ** solely for "performance reasons"** sure sounds like premature optimization to me.</p>\n\n<p>Anyway, I think if you avoid the edge cases and have fairly vanilla SQL, you won\'t notice a difference between ad hoc and stored procedures.</p>\n'}, {'answer_id': 59946, 'author': 'Chris Miller', 'author_id': 206, 'author_profile': 'https://Stackoverflow.com/users/206', 'pm_score': 1, 'selected': False, 'text': '<p>Using stored procedures for CRUD operations is probably overkill, but it will depend on the tools be used and your own preferences (or requirements).  I prefer inline SQL, but I make sure to use parameterized queries to prevent SQL injection attacks.  I keep a print out of this <a href="http://xkcd.com/327/" rel="nofollow noreferrer">xkcd comic</a> as a reminder of what can go wrong if you are not careful.</p>\n\n<p>Stored procedures can have real performance benefits when you are working with multiple sets of data to return a single set of data.  It\'s usually more efficient to process sets of data in the stored procedure than sending them over the wire to be processed at the client end.</p>\n'}, {'answer_id': 59949, 'author': 'Jake Hackl', 'author_id': 5247, 'author_profile': 'https://Stackoverflow.com/users/5247', 'pm_score': 0, 'selected': False, 'text': '<p>Yes, they are faster most of time. SQL composition is a huge performance tuning area too. If I am doing a back office type app I may skip them but anything production facing I use them for sure for all the reasons others spoke too...namely security. </p>\n'}, {'answer_id': 60580, 'author': 'Evan', 'author_id': 6277, 'author_profile': 'https://Stackoverflow.com/users/6277', 'pm_score': 1, 'selected': False, 'text': '<p>Realising this is a bit off-topic to the question, but if you are using a lot of stored procedures, make sure there is a consistent way to put them under some sort of source control (e.g., subversion or git) and be able to migrate updates from your development system to the test system to the production system.</p>\n\n<p>When this is done by hand, with no way to easily audit what code is where, this quickly becomes a nightmare.</p>\n'}, {'answer_id': 60587, 'author': 'fuzzbone', 'author_id': 5027, 'author_profile': 'https://Stackoverflow.com/users/5027', 'pm_score': 3, 'selected': False, 'text': '<p>The one topic that no one has yet mentioned as a benefit of stored procedures is security.  If you build the application exclusively with data access via stored procedures, you can lockdown the database so the ONLY access is via those stored procedures.  Therefor, even if someone gets a database ID and password, they will be limited in what they can see or do against that database.</p>\n'}, {'answer_id': 60642, 'author': 'JeffV', 'author_id': 445087, 'author_profile': 'https://Stackoverflow.com/users/445087', 'pm_score': 0, 'selected': False, 'text': '<p>IMHO...</p>\n\n<p>Restricting "C_UD" operations to stored procedures can keep the data integrity logic in one place. This can also be done by restricting"C_UD" operations to a single middle ware layer.</p>\n\n<p>Read operations can be provided to the application so they can join only the tables / columns they need.</p>\n'}, {'answer_id': 60964, 'author': 'Andrei Rînea', 'author_id': 1796, 'author_profile': 'https://Stackoverflow.com/users/1796', 'pm_score': 0, 'selected': False, 'text': "<p>Stored procedures can also be used instead of parameterized queries (or ad-hoc queries) for some other advantages too :</p>\n\n<ul>\n<li>If you need to correct something (a sort order etc.) you don't need to recompile your app</li>\n<li>You could deny access to all tables for that user account, grant access only to stored procedures and route all access through stored procedures. This way you can have custom validation of all input much more flexible than table constraints.</li>\n</ul>\n"}, {'answer_id': 209094, 'author': 'DOK', 'author_id': 27637, 'author_profile': 'https://Stackoverflow.com/users/27637', 'pm_score': 5, 'selected': False, 'text': "<p>Reasons for using stored procedures:</p>\n\n<ul>\n<li><strong>Reduce network traffic</strong> -- you have to send the SQL statement across the network. With sprocs, you can execute SQL in batches, which is also more efficient.</li>\n<li><strong>Caching query plan</strong> -- the first time the sproc is executed, SQL Server creates an execution plan, which is cached for reuse. This is particularly performant for small queries run frequently.</li>\n<li><strong>Ability to use output parameters</strong> -- if you send inline SQL that returns one row, you can only get back a recordset. With sprocs you can get them back as output parameters, which is considerably faster.</li>\n<li><strong>Permissions</strong> -- when you send inline SQL, you have to grant permissions on the table(s) to the user, which is granting much more access than merely granting permission to execute a sproc</li>\n<li><strong>Separation of logic</strong> -- remove the SQL-generating code and segregate it in the database.</li>\n<li><strong>Ability to edit without recompiling</strong> -- this can be controversial. You can edit the SQL in a sproc without having to recompile the application.</li>\n<li><strong>Find where a table is used</strong> -- with sprocs, if you want to find all SQL statements referencing a particular table, you can export the sproc code and search it. This is much easier than trying to find it in code.</li>\n<li><strong>Optimization</strong> -- It's easier for a DBA to optimize the SQL and tune the database when sprocs are used. It's easier to find missing indexes and such.</li>\n<li><strong>SQL injection attacks</strong> -- properly written inline SQL can defend against attacks, but sprocs are better for this protection.</li>\n</ul>\n"}, {'answer_id': 234324, 'author': 'Will Dieterich', 'author_id': 31233, 'author_profile': 'https://Stackoverflow.com/users/31233', 'pm_score': -1, 'selected': False, 'text': "<p>Reduced network traffic -- SP are generally worse then Dynamic SQL.  Because people don't create a new SP for every select, if you need just one column you are told use the SP that has the columns they need and ignore the rest.  Get an extra column and any less network usage you had just went away.  Also you tend to have a lot of client filtering when SP are used.</p>\n\n<p>caching -- MS-SQL does not treat them any differently, not since MS-SQL 2000 may of been 7 but I don't remember.</p>\n\n<p>permissions -- Not a problem since almost everything I do is web or have some middle application tier that does all the database access.  The only software I work with that have direct client to database access are 3rd party products that are designed for users to have direct access and are based around giving users permissions.  And yes MS-SQL permission security model SUCKS!!! (have not spent time on 2008 yet)  As a final part to this would like to see a survey of how many people are still doing direct client/server programming vs web and middle application server programming; and if they are doing large projects why no ORM.</p>\n\n<p>Separation -- people would question why you are putting business logic outside of middle tier. Also if you are looking to separate data handling code there are ways of doing that without putting it in the database.</p>\n\n<p>Ability to edit -- What you have no testing and version control you have to worry about?  Also only a problem with client/server, in the web world not problem.</p>\n\n<p>Find the table -- Only if you can identify the SP that use it, will stick with the tools of the version control system, agent ransack or visual studio to find.</p>\n\n<p>Optimization -- Your DBA should be using the tools of the database to find the queries that need optimization. Database can tell the DBA what statements are talking up the most time and resources and they can fix from there. For complex SQL statements the programmers should be told to talk to the DBA if simple selects don't worry about it.</p>\n\n<p>SQL injection attacks -- SP offer no better protection.  The only thing they get the nod is that most of them teach using parameters vs dynamic SQL most examples ignore parameters.</p>\n"}, {'answer_id': 1797473, 'author': 'Dennis Decker Jensen', 'author_id': 218656, 'author_profile': 'https://Stackoverflow.com/users/218656', 'pm_score': 3, 'selected': False, 'text': "<p>In 2007 I was on a project, where we used MS SQL Server via an ORM. We had 2 big, growing tables which took up to 7-8 seconds of load time on the SQL Server. After making 2 large, stored SQL procedures, and optimizing them from the query planner, each DB load time got down to less than 20 milliseconds, so clearly there are still efficiency reasons to use stored SQL procedures.</p>\n\n<p>Having said that, we found out that the most important benefit of stored procedures was the added maintaince-ease, security, data-integrity, and decoupling business-logic from the middleware-logic, benefitting all middleware-logic from reuse of the 2 procedures.</p>\n\n<p>Our ORM vendor made the usual claim that firing off many small SQL queries were going to be more efficient than fetching large, joined data sets. Our experience (to our surprise) showed something else.</p>\n\n<p>This may of course vary between machines, networks, operating systems, SQL servers, application frameworks, ORM frameworks, and language implementations, so measure any benefit, you THINK you may get from doing something else.</p>\n\n<p>It wasn't until we benchmarked that we discovered the problem was between the ORM and the database taking all the load.</p>\n"}, {'answer_id': 7729253, 'author': 'jmt', 'author_id': 989922, 'author_profile': 'https://Stackoverflow.com/users/989922', 'pm_score': 2, 'selected': False, 'text': '<p>To me one advantage of stored procedures is to be host language agnostic: you can switch from a C, Python, PHP or whatever application to another programming language without rewriting your code. In addition, some features like bulk operations improve really performance and are not easily available (not at all?) in host languages.</p>\n'}]
['https://Stackoverflow.com/questions/59880', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5619/']