“Never do in code what you can get the SQL server to do well for you” – Is this a recipe for a bad design

design-patternssql

It's an idea I've heard repeated in a handful of places. Some more or less acknowledging that once trying to solve a problem purely in SQL exceeds a certain level of complexity you should indeed be handling it in code.

The logic behind the idea is that for the large majority of cases, the database engine will do a better job at finding the most efficient way of completing your task than you could in code. Especially when it comes to things like making the results conditional on operations performed on the data. Arguably with modern engines effectively JIT'ing + caching the compiled version of your query it'd make sense on the surface.

The question is whether or not leveraging your database engine in this way is inherently bad design practice (and why). The lines become blurred further when all the logic exists inside the database and you're just hitting it via an ORM.

Best Answer

In layman's words:

These are things that SQL is made to do and, believe it or not, I've seen done in code:

  • joins - codewise it'd require complex array manipulation
  • filtering data (where) - codewise it'd require heavy inserting and deleting of items in lists
  • selecting columns - codewise it'd require heavy list or array manipulation
  • aggregate functions - codewise it'd require arrays to hold values and complex switch cases
  • foreign key integrity - codewise it'd require queries prior to insert and assumes nobody will use the data outside app
  • primary key integrity - codewise it'd require queries prior to insert and assumes nobody will use the data outside app

Doing these things instead of relying in SQL or the RDBMS leads to writing tons of code with no added value, meaning more code to debug and maintain. And it dangerously assumes the database will only be accessed via the application.

Related Topic