Stories
Slash Boxes
Comments

News for nerds, stuff that matters

MySQL Stored Procedure Programming

Posted by samzenpus on Wed Apr 18, 2007 02:28 PM
from the a-little-lite-afternoon-reading dept.
Michael J. Ross writes "MySQL may be the most popular open source relational database management system (RDBMS) in the world, but during the first decade of its existence, it lacked support for stored programs, i.e., store procedures, functions, and triggers. The major commercial RDBMS vendors — including Oracle, IBM, and Microsoft — could point to this deficiency as reason enough to choose their proprietary systems over MySQL or any other open source system, such as PostgreSQL. But with the release of MySQL version 5.0, in October 2005, the "little database engine that could" dramatically improved its position against the competition. The most comprehensive discussion of these new capabilities is in the book MySQL Stored Procedure Programming." Read below for the rest of Michael's review
MySQL Stored Procedure Programming
author Guy Harrison and Steven Feuerstein
pages 636
publisher O'Reilly Media
rating 9
reviewer Michael J. Ross
ISBN 0596100892
summary A comprehensive guide to developing MySQL stored procedures, functions, and triggers.


Written by Guy Harrison and Steven Feuerstein, and published by O'Reilly Media in March 2006 under the ISBNs 0596100892 and 978-0596100896, this book is the first one to offer database programmers a full discussion of the syntax, usage, and optimization of MySQL stored procedures, stored functions, and triggers — which the authors wisely refer to collectively as "stored programs," to simplify the manuscript. Even a year after the introduction of these new capabilities in MySQL, they have received remarkably little coverage by book publishers. Admittedly, there are three such chapters in MySQL Administrator's Guide and Language Reference (2nd Edition), written by some of the developers of MySQL, and published by MySQL Press. Yet this latter book — even though published a month after O'Reilly's — devotes fewer than 50 pages to stored programs, and the material is not in the printed book itself, but in the "MySQL Language Reference" part, on the accompanying CD. That material, in conjunction with the online reference documentation, may be sufficient for the more simple stored program development needs. But for any MySQL developer who wishes to understand in-depth how to make the most of this new functionality in version 5.0, they will likely need a much more substantial treatment — and that's exactly what Harrison and Feuerstein have created.

The authors are generous in both the technical information and development advice that they offer. The book's material spans 636 pages, organized into 23 chapters, grouped into four parts, followed by an index. The first part, "Stored Programming Fundamentals," provides an introduction and then a tutorial, both taking a broad view of MySQL stored programs. The remaining four chapters cover language fundamentals; blocks, conditional statements, and iterative programming; SQL; and error handling. The book's second part, "Stored Program Construction," may be considered the heart of the book, because its five chapters present the details of creating stored programs in general, using transaction management, using MySQL's built-in functions, and creating one's own stored functions, as well as triggers. The third part, "Using MySQL Stored Programs and Applications," explains some of the advantages and disadvantages of stored programs, and then illustrates how to call those stored programs from source code written in any one of five different programming languages: PHP, Java, Perl, Python, and Microsoft.NET. In the fourth and final part, "Optimizing Stored Programs," the authors focus on the security and tuning of stored programs, tuning SQL, optimizing the code, and optimizing the development process itself.

This is a substantial book, encompassing a great deal of technical as well as advisory information. Consequently, no review such as this can hope to describe or critically comment upon every section of every chapter of every part. Yet the overall quality and utility of the manuscript can be discerned simply by choosing just one of the aforesaid Web programming languages, and writing some code in that language to call some MySQL stored procedures and functions, to get results from a test database — and developing all of this code while relying solely upon the book under review. Creating some simple stored procedures, and calling them from some PHP and Perl scripts, demonstrated to me that MySQL Stored Procedure Programming contains more than enough coverage of the topics to be an invaluable guide in developing the most common functionality that a programmer would need to implement.

The book appears to have very few aspects or specific sections in need of improvement. The discussion of variable scoping, in Chapter 4, is too cursory (no database pun intended). In terms of the book's sample code, I found countless cases of inconsistency of formatting — specifically, operators such as "||" and "=" being jammed up against their adjacent elements, without any whitespace to improve readability. These minor flaws could be easily remedied in the next edition. Some programming books make similar mistakes, but throughout their text, which is even worse. Fortunately, most of the code in this book is neatly formatted, and the variable and program names are generally descriptive enough.

Some of the book's material could have been left out without great loss — thereby reducing the book's size, weight, and presumably price. The two chapters on basic and advanced SQL tuning contain techniques and recommendations covered with equal skill in other MySQL books, and were not needed in this one. On the other hand, sloppy developers who churn out lamentable code might argue that the last chapter, which focuses on best programming practices, could also be excised; but those are the very individuals who need those recommendations the most.

Fortunately, the few weaknesses in the book are completely overwhelmed by its positive qualities, of which there are many. The coverage of the topics is quite extensive, but without the repetition often seen in many other technical books of this size. The explanations are written with clarity, and provide enough detail for any experienced database programmer to understand the general concepts, as well as the specific details. The sample code effectively illustrates the ideas presented in the narration. The font, layout, organization, and fold-flat binding of this book, all make it a joy to read — as is characteristic of many of O'Reilly's titles.

Moreover, any programming book that manages to lighten the load of the reader by offering a touch of humor here and there, cannot be all bad. Steven Feuerstein is the author of several well-regarded books on Oracle, and it was nice to see him poke some fun at the database heavyweight, in his choice of sample code to demonstrate the my_replace() function: my_replace( 'We love the Oracle server', 'Oracle', 'MySQL').

The prospective reader who would like to learn more about this book, can consult its Web page on O'Reilly's site. There they will find both short and full descriptions, confirmed and unconfirmed errata, a link for writing a reader review, an online table of contents and index, and a sample chapter (number 6, "Error Handling"), in PDF format. In addition, the visitor can download all of the sample code in the book (562 files) and the sample database, as a mysqldump file.

Overall, MySQL Stored Procedure Programming is adeptly written, neatly organized, and exhaustive in its coverage of the topics. It is and likely will remain the premier printed resource for Web and database developers who want to learn how to create and optimize stored procedures, functions, and triggers within MySQL.

Michael J. Ross is a Web programmer, freelance writer, and the editor of PristinePlanet.com's free newsletter. He can be reached at www.ross.ws, hosted by SiteGround.


You can purchase MySQL Stored Procedure Programming from amazon.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.
This discussion has been archived. No new comments can be posted.
Display Options Threshold:
The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
  • MySQL aren't trustworthy (Score:3, Insightful)

    by ShieldW0lf (601553) on Wednesday April 18 2007, @02:35PM (#18786829)
    You know what it is?

    It's lack of trust.

    MySQL started off making their fast little datastore that uses a little SQL syntax, and they told everyone under the sun that if MySQL didn't do it, you didn't need it, and ought to design around it.

    Referential integrity, ACID compliance, enforcement of rules... every step along the way, they tell you you don't need it and you ought to push the missing logic to the next tier, until they get it, if they get it, then they're so great.

    Couple that with the Project Mayo/DivX corporate structure, then place Postgresql next to the whole shebang as a superior alternative, and the arguments for giving MySQL any of your attention become increasingly small.

    MySQL owes its success to the fact that it was always so simple to choke it off when you were giving it to people on $5/month hosting plans, so it became popular among the very cheap.

    Period.
    • The parent comment is a classic example of FUD by Andy Tai (Score:2) Wednesday April 18 2007, @02:39PM
      • Not really FUD by Anonymous Coward (Score:3) Wednesday April 18 2007, @03:06PM
        • Re:Not really FUD (Score:5, Informative)

          by elp (45629) on Wednesday April 18 2007, @04:02PM (#18788085)
          Yep it was really irritating. A lot like the Postgres users who kept claiming the next version of their server was going to be really fast.

          In the end the postgres crowd have a right to be upset. They could have been the major player for open databases but their devs were too arrogant to listen to their users and design it to be friendly.

          For all its faults mysql is trivial to install and works out of the box for most applications. Last time I looked the default install for postgresql still seemed to be tuned as though it would never have to handle more than a handful of users. Stored procedures and TCP/IP are off by default and the auto vacuum thing needs to be set up manually. Then don't forget that while the postgres query parser does more error checking that mysql its error messages are incredibly cryptic so its MUCH hard to trouble shoot.

          Your average newbie takes one looks at it, gives up and moves to mysql. When that newbie finally grows up he has too much time invested in mysql to be bothered learning the intricacies of postgres. Every extra feature that mysql adds is one less reason for anyone to try postgres.

          Postgres is a better DB once its setup and tuned properly but considering its usability issues and that mysql users probably out number postgres users a thousand to 1 or more I think mysql is always going to be the number one opensource DB.

          [ Parent ]
      • by cyphercell (843398) on Wednesday April 18 2007, @03:12PM (#18787337)
        (http://127.0.0.1/ | Last Journal: Thursday September 20, @12:52PM)

        Does it tell anything concrete about MySQL 5? No.

        It does speak volumes about MySQL's history, though. The things he lists are are the reasons why MySQL is still compared with M$ Access. They are valid points, because MySQL as a company has a sordid past, as far as presenting something that resembles modern database theory. I'm not saying I don't appreciate MySQL, I'm just say that I thoroughly understand the frustrations. MySQL has been presented as an off the shelf enterprise contendor for years and that's only begining to resemble fact.

        [ Parent ]
    • Is 640kB enough to run a MySQL server? by faramir_fr (Score:1) Wednesday April 18 2007, @02:39PM
    • Re:MySQL aren't trustworthy by bahwi (Score:3) Wednesday April 18 2007, @02:41PM
      • Re:MySQL aren't trustworthy by Overly Critical Guy (Score:3) Wednesday April 18 2007, @03:32PM
      • Re:MySQL aren't trustworthy by Anonymous Coward (Score:1) Wednesday April 18 2007, @03:35PM
      • Re:MySQL aren't trustworthy (Score:4, Informative)

        by XorNand (517466) on Wednesday April 18 2007, @03:39PM (#18787739)

        I recently decided to move to Postgres from MySQL. There are some pretty cool things about Postgres; flexible authentication options and sequences being my current favorite. I've found that it's docs are actually pretty good (I don't know what they were like before). However, since the topic here are stored procedures, I have to really complain bitterly about Postgres's implementation of stored procedures. Creating a sproc that returns a dataset rather than just a outpur parameter is a convoluted dance. You have to exactly define the output using a "TYPE" and then iterate over the dataset using a cursor-like syntax.

        Consider this simple example that I'm currently working on. It's for an internal peer review application where coworkers give one positive and one negative comment about each other:

        DROP TYPE answers_type CASCADE;
        CREATE TYPE answers_type AS (
        positive text
        ,negative text);

        CREATE OR REPLACE FUNCTION answers_get(
        _review_id int
        ) RETURNS setof answers_type AS $$
        DECLARE
        rec answers_type;
        BEGIN

        FOR rec IN SELECT
        positive
        ,negative
        FROM answers
        WHERE review = _review_id
        ORDER BY id DESC
        LOOP
        RETURN NEXT rec;
        END LOOP;
        RETURN;
        END; $$ LANGUAGE plpgsql;

        This ends up being very unwieldy for larger and more complex stored procedures. I recently compared simple output -parameter only stored procedures [rightbrainnetworks.com] between Postgres, MySQL, and MS SQL on my blog. Fortunately it's a lot more straightforward when using that method. I'll stick with Postgres for now and just hope that this is eventually improved.

        [ Parent ]
      • Re:MySQL aren't trustworthy (Score:4, Insightful)

        by LizardKing (5245) on Wednesday April 18 2007, @04:59PM (#18788871)
        (http://www.chriswareham.net/)

        Only recently has it become superior. Documentation isn't just a feature, it's a necessity, even with the open source world, and Postgresql's documentation is finally getting to a good point.

        Unless something dramatic has happened to MySQL documentation since I last used it (version 4.1), then PostgreSQL has the better documenation and has done since as long as I've been using it. The PostgreSQL documentation reads like a coherent set of books, while MySQL documentation seems to be a random mess that grew out of some simple README file. As for the software itself, PostgreSQL has always been superior - a simple comparison of features alone bears this out, but if you want to go further take a look at the code as the same distinction is found there.

        [ Parent ]
      • Re:MySQL aren't trustworthy by JAlexoi (Score:1) Wednesday April 18 2007, @07:03PM
      • Re:MySQL aren't trustworthy by putaro (Score:2) Thursday April 19 2007, @10:24PM
      • 1 reply beneath your current threshold.
    • Names matter sometimes (Score:5, Insightful)

      by ClosedSource (238333) on Wednesday April 18 2007, @03:02PM (#18787215)
      I think part of postgresql's problem is its awful name. Just about anything would have been better (e.g. TurboSQL, AgileSQL, FastSQL, UglySQL, FatDumbAndHappySQL, etc).
      [ Parent ]
    • isnt it the same for ALL the stuff that took off : by unity100 (Score:2) Wednesday April 18 2007, @03:06PM
    • Emulated SP's by vivin (Score:2) Wednesday April 18 2007, @03:34PM
    • Wait, this sounds familiar... by Mr. Underbridge (Score:2) Wednesday April 18 2007, @03:35PM
    • Re:MySQL aren't trustworthy (Score:5, Interesting)

      by CoughDropAddict (40792) on Wednesday April 18 2007, @04:29PM (#18788459)
      Amen, brother.

      For people not familiar with MySQL's history, I would suggest a little reading from previous versions of MySQL's manual:

      How to cope without COMMIT/ROLLBACK: For the moment, we are much more for implementing the SQL server language (something like stored procedures). With this you would very seldom really need COMMIT-ROLLBACK. This would also give much better performance. [utk.edu]

      Reasons not to use foreign keys. There are so many problems with FOREIGN KEYs that we don't know where to start. [utk.edu]

      I decided long ago that the MySQL guys are clowns. MySQL's lack of features was never as big a problem as the fact that I just couldn't take these guys seriously (and the above is only a small subset of the reasons for that).
      [ Parent ]
    • Re:MySQL aren't trustworthy by Blakey Rat (Score:2) Wednesday April 18 2007, @05:10PM
    • MySQL in the Enterprise by BillGatesLoveChild (Score:2) Wednesday April 18 2007, @06:03PM
    • 2 replies beneath your current threshold.
  • MySQL vs Firebird (Score:1, Offtopic)

    by BuR4N (512430) on Wednesday April 18 2007, @02:37PM (#18786857)
    (http://www.intellipool.se/ | Last Journal: Wednesday January 31 2007, @03:49PM)
    This might come off as offtopic, but I'll take the risk.

    Is there anyone here that have experiance with both of these databases that can explain in simple terms why one would go with MySQL over Firebird ?

    No intention of starting a flamewar, I'm just interested in finding out the major pro's and con's between the two.
    • Re:MySQL vs Firebird (Score:5, Insightful)

      by PCM2 (4486) on Wednesday April 18 2007, @02:45PM (#18786979)
      (http://neilmcallister.com/)

      Is there anyone here that have experiance with both of these databases that can explain in simple terms why one would go with MySQL over Firebird ?

      My understanding is that Firebird is by any measure more sophisticated than MySQL, but it lacks the "critical mass" of users that makes it attractive to people who need to be sure they can get ready support for their software. MySQL is available on just about every cheap hosting provider around, too, which means that a lot of ready-built open source Web apps target MySQL as their database of choice.

      Put it to you this way: If the features of MySQL are "good enough" for the application you want -- which arguably goes for most of the Web apps out there -- why would you not choose MySQL? There are times when swimming upstream is a noble effort, but generally all it gets you is tired.

      If, on the other hand, you have a specific application for which you need a relational data store and you need higher-end RDBMS features, by all means, choose Firebird. Only I think in those cases most people still choose PostgreSQL, for more or less the same reasons as mentioned above.

      [ Parent ]
    • Re:MySQL vs Firebird (Score:4, Insightful)

      by LurkerXXX (667952) on Wednesday April 18 2007, @04:23PM (#18788397)
      Why would you go with MySQL over Firebird?

      Easy. The nimrod who wrote the application that you want/need to run didn't make the app database agnostic, so you are stuck with MySQL because "it's more popular". It's a catch 22. Until more folks start writing database agnostic apps, lots of us will get stuck using MySQL in places where we might prefer other databases. And so that will perpetuate MySQL being seen as being more popular... Argh.
      [ Parent ]
    • Re:MySQL vs Firebird by ceeam (Score:2) Thursday April 19 2007, @04:47AM
    • Re:MySQL vs Firebird by Bastard of Subhumani (Score:1) Thursday April 19 2007, @06:55AM
    • Re:MySQL vs Firebird by Bloke down the pub (Score:2) Thursday April 19 2007, @09:29AM
    • 2 replies beneath your current threshold.
  • What's your opinion (Score:4, Interesting)

    by CastrTroy (595695) on Wednesday April 18 2007, @02:38PM (#18786863)
    (http://www.kibbee.ca/)
    I would like to know what slashdotters think is a good level of stuff to be putting into stored procedures. I've seen organizations where every single select query is put into a stored procedure. I've also seen places that avoid it like the plague. Personally I like to keep as much business logic as possible out of the database, but I realize it can speed up things considerably, so I use it where speed is critical. Is there any hope that stored procedures will become cross platform and work on all databases, at least to the level of SQL, so that there's some kind of standard, or do they just push us towards vendor lock-in?
    • It isn't about speed (Score:5, Insightful)

      by Tony (765) * on Wednesday April 18 2007, @03:00PM (#18787195)
      (http://zoeshire.com/ | Last Journal: Thursday October 31 2002, @05:12PM)
      Stored procedures should be used to enforce data integrity and data access. The only "business logic" that should be there is the logic that applies to keeping your data whole, complete, and coherent.

      Middle-tier application layers are great to help pull data together, present model-specific views of data (say, OO/R mapping, if that is what gives you a chubby), and provide update interfaces. They can even do a first pass at making sure the database will accept the data.

      But.

      The data logic should be stored firmly in the database logic itself, using stored procedures and triggers and rules. RDBMS engines are *designed* to keep your data in good shape. Use them in that fashion, and you will be plenty happy. Don't, and you risk losing data integrity, and you sacrifice security.
      [ Parent ]
    • Re:What's your opinion (Score:5, Insightful)

      by sammy baby (14909) on Wednesday April 18 2007, @03:02PM (#18787221)
      (Last Journal: Monday February 04 2002, @03:31PM)
      Oh man, talk about a can of worms.

      On the one hand, folks who are trained to think in terms of data relationships and database development are liable to want to put as much as possible right in the database.

      On the other hand... well, forget it. There is no other hand, it's more like a shifting mass of appendages, like Shiva [wikipedia.org] on an acid binge. The other extreme are people like David Heinemeier Hansson, who want to use database to store information and otherwise stay the hell out of the way - as I believe he put it once, to be as dumb as possible.

      That may be a minority view, but the minority isn't exactly vanishingly small. eBay, for example, not only skips out on transactions (you know, the thing people like to beat up on MySQL for not having years ago), but doesn't even enforce referential integrity in the database. Stored procedures are right out. (warning: reference is a PDF [singleobject.org].)

      My own personal, under-informed and probably worthless view: I like enforce referential integrity where I can in the DB, and transactions are a good thing, but stored procedures are better left to maintenance and administration functions than anything involving business logic.

      [ Parent ]
    • Re:What's your opinion by Anonymous Coward (Score:1) Wednesday April 18 2007, @03:23PM
    • Re:What's your opinion by arivanov (Score:3) Wednesday April 18 2007, @03:41PM
    • Re:What's your opinion by shatfield (Score:3) Wednesday April 18 2007, @04:35PM
      • Re:What's your opinion (Score:4, Insightful)

        by turbidostato (878842) on Wednesday April 18 2007, @09:12PM (#18792053)
        "Don't put any business logic into sprocs."

        Do put critical enforceable bussiness logic (and I mean *bussiness* logic, not application logic) as near as possible to the data (and that usually means SP).

        "The second that you place a business rule into a sproc, the users will want the rule changed"

        That's true. And that's an advantage of stored procedures: they won't be able to change them (that's why I talked about Critical-Enforceable-Bussiness-Logic).

        "Why is this bad? Because sprocs are almost always under the control of the DBA"

        Why is this good? Because sprocs are almost always under the control of the most data management knowledgeable techie round there.

        "most of the time there is a layer of politics involved between DBAs and Software Developers"

        And that's good because that refrain them from their need (either because management pressure or pure ignorance) to do the thing the Real Stupid Way just because it's the fastest/the only way they know.

        "What usually happens is that the dev will make the change to the business logic in the middle (or even worse, GUI) tier, thereby doing twice as much work"

        So you say that such a bussiness logic should go into the middle tier instead of the RBDM because in that case the developer would do a stupid thing -like expressing it in the middle tier? This is both a circular argument and one more reason to put those kind of rules *out* of the reach of such a stupid developer.

        "Adding Database servers to a cluster isn't cheap. If you have a lot of users, and you have had to cluster your servers to accommodate more users..."

        Then you need to add more database horsepower. If you need to push or pull more data from the place the data is stored... well, you need it. No middleware is going to change that.

        "Adding more middle-tier servers is much cheaper"

        Yes. And buying a 1GB pen-drive is even cheaper than that, having in common with your "solution" that they both have nothing to do with the problem at hand. You either need to pull/push more data from where it resides or you don't. In the first case you always need more database horsepower; in the second you won't need it (and if cacheing is a good solution to your current problem then no, your problem is not that you need to push/pull more than provided and no, a cacheing solution is not a "middleware").

        Resuming:
        You will want stored procedures for your critical enforceable bussiness logic because:

        *Developers tend to suck regarding data access/management (design, integrity or efficency); DBAs a little less so (it's the work they are focused on, after all).

        *No matter how good your bussiness logic implementation on your new shiny app is, tomorrow it will be developed a new app that will access the same dataset (like the example you talk about people pumping data from Excel -presumably instead of through your pretty web app that tried to enforce this or that rule) and will surely break some bussiness logic or at the very least you will need to reimplement them again. If you don't want this to happen, enforce the rules as near to the data as possible so there's no way to overrun them.

        *Your managers are crazy. It's much more probable that your new manager (or the old one if it happens to read the last shiny brochure from "PHB's IT") decides to rewrite all your .Net software to Java or the other way around than to move from Oracle to DB2 (if just because -as you already said, privative RBDM licenses and support are *very* expensive to play with them and they are buried more profoundly in the caves of the black teachies so they make for not as good PR as a new front end with a new brighter colorset and round corners). Go defensive and give your bussiness rules a sanctuary against crazyness within your RBDM (I now this seems to be against common wisdom: the most you program as SP, the most locked to the RBDM you are. But while that's true in theory, my experience in the Real World-TM is that
        [ Parent ]
      • Re:What's your opinion by GoofyBoy (Score:2) Wednesday April 18 2007, @10:00PM
      • 1 reply beneath your current threshold.
    • case study by kpharmer (Score:2) Wednesday April 18 2007, @05:03PM
      • Re:case study by rapiddescent (Score:3) Thursday April 19 2007, @03:57AM
    • Re:What's your opinion by nuzak (Score:2) Wednesday April 18 2007, @05:04PM
    • Re:What's your opinion by Just Some Guy (Score:2) Wednesday April 18 2007, @05:05PM
    • You just gota keep DBA's out of critical path. by HornWumpus (Score:2) Wednesday April 18 2007, @08:38PM
    • Re:What's your opinion by jakerman (Score:1) Thursday April 26 2007, @11:25AM
    • 1 reply beneath your current threshold.
  • Stred pocedures (Score:5, Informative)

    by karavelov (863935) on Wednesday April 18 2007, @02:38PM (#18786873)
    (http://luben.unixsol.org/)
    "The major commercial RDBMS vendors -- including Oracle, IBM, and Microsoft -- could point to this deficiency as reason enough to choose their proprietary sstems over MySQL or any other open source system, such as PostgreSQL..." They could not point this because PostgreSQL has stored procedures for decades... fully tested, stable, offering e bunch of languages for writing functions/triggers, including Perl, Python, Tcl and their own PlSQL that is very close to Oracle's variant.
  • Deciding if MySQL is an option (Score:4, Insightful)

    by moore.dustin (942289) on Wednesday April 18 2007, @02:44PM (#18786965)

    if((estimated_rows_in_table($table) < 100000)) {
    return true;
    }
    else {
    return false;
    }
    • by gusx (898415) on Wednesday April 18 2007, @02:48PM (#18787019)
      How about...

      return (estimated_rows_in_table($table) < 100000);
      [ Parent ]
    • Re:Deciding if MySQL is an option (Score:5, Insightful)

      by coyote-san (38515) on Wednesday April 18 2007, @03:37PM (#18787699)
      Even that is generous. If you want to use a database as a simple store (and if they've fixed the tendency to hiccup and corrupt the database), MySQL may be acceptable.

      If you want a DATABASE it's not even on the table, no pun intended. The whole point of a RDBMS is that it isn't a simple store, it's a mechanism for ensuring that your collection of data is always in a sane state even if you've brought in some clueless interns for the summer or you have a disgruntled employee. Or even if you just have two developers (or one developer with a poor memory).

      ACID and referential integrity are two items that are absolute requirements. Calling something without these features a 'relational database' puts you in the same pointy-hair territory as Dilbert's boss saying that he heard the 'mauve' databases were best.

      Attribute constraints, triggers and stored procedures aren't as necessary, but they're still extremely powerful ways of ensuring the sanity of your data. Use a trigger to update a 'updated_on' field, don't just trust the developer to always update it. Use an attribute constraint to ensure that you color field is always 'R', 'G' or 'B' (or just use referential integrity to point to a color table).

      Finally, to address a question asked elsewhere stored procedures are extremely powerful security tools. By now everyone should know that using string concatenation to prepare queries is a Very Bad Idea. A potentially "don't let the door hit you in the butt on your way out" Bad Idea. Prepared statements are better, but how can you enforce it?

      Stored procedures give you an alternative. Drop INSERT and UPDATE rights and force everything to go through a corresponding stored procedure. It's a little more work but it should eliminate any risk of SQL exploits. (It's not a 100% guarantee since you can't eliminate the risk that the database itself can be compromised by carefully selected parameters.)
      [ Parent ]
    • Re:Deciding if MySQL is an option by LordLucless (Score:3) Wednesday April 18 2007, @04:00PM
    • Re:Deciding if MySQL is an option (Score:5, Informative)

      by consumer (9588) on Wednesday April 18 2007, @04:02PM (#18788079)
      I'm currently looking at a table on a production MySQL db with 176 million rows in it. It has no problems at all, other than being a huge amount of data. Your ideas about MySQL's limitations are not based on fact.
      [ Parent ]
      • Re:Deciding if MySQL is an option (Score:4, Informative)

        by kpharmer (452893) on Wednesday April 18 2007, @04:51PM (#18788771)
        > I'm currently looking at a table on a production MySQL db with 176 million rows in it. It has no problems at all,
        > other than being a huge amount of data. Your ideas about MySQL's limitations are not based on fact.

        Without partitioning you face the choice of selecting data only via a btree index (only typically works if you need to select less than 3% of the data) or scanning it all. With a more typical alternative (certainly db2, oracle, etc) you can partition the data. This can result in 10:1 differences in performance between mysql & db2/oracle for typical reporting queries.

        Without query parallelism you're single-threading all of your queries, and unable to take advance of those extra processors. Since oracle/db2 get near-linear performance benefits from parallelism, you're again suffering a 4:1 performance penalty on a four-way smp.

        Without a robust optimizer you will choke on complex queries against even moderate data - so a query that joins a dozen tables together will inevitately go into the ditch with poorly chosen nested-loop joins. Performance penalty? could easily be 100:1 in some situations.

        Of course, this doesn't mean that you can't keep 200 million rows in msyql - you certainly can. Just don't plan to get the same kind of performance out of a lot of typically complex queries against it - that you would get from oracle/db2/informix or even sql server. Not unless you spend 20x as much on the hardware anyway.

        > Your ideas about MySQL's limitations are not based on fact.
        Unfortunately, your ideas about mysql's capabilities are based upon insufficient experience
        [ Parent ]
      • Re:Deciding if MySQL is an option by moore.dustin (Score:3) Wednesday April 18 2007, @05:29PM
      • Re:Deciding if MySQL is an option by JAlexoi (Score:2) Wednesday April 18 2007, @07:27PM
      • 2 replies beneath your current threshold.
    • 2 replies beneath your current threshold.
  • Good one Ploppy (Score:3, Funny)

    by Tim Browse (9263) on Wednesday April 18 2007, @03:56PM (#18787993)

    it was nice to see him poke some fun at the database heavyweight, in his choice of sample code to demonstrate the my_replace() function:
    my_replace( 'We love the Oracle server', 'Oracle', 'MySQL').

    The long Winter evenings must just fly by.

  • by not already in use (972294) on Wednesday April 18 2007, @04:36PM (#18788575)
    While they are certainly useful in certain situations, they are a pain in the ass to debug. It would be nice if they could add some sort of vendor specific command - anything - that would allow me to see output in a console while a stored procedure/function is running. They are useful at times, but i dread writing them.
  • by ScrewTivo (458228) on Wednesday April 18 2007, @05:35PM (#18789327)
    (http://ninjadeals.blogspot.com/)
    I'll have to put on my flame suit for this one only because so many interests are out here defending non-defendable territory.

    Why does everyone love CSS for separating content from format .... then turn tail and try to put business logic into the database tier. Try moving a large MS-SQL app that utilized stored procedures to Oracle or MySQL. Tell the wife you'll see her next year!

    Presentation - Logic - Storage. Clean and simple. Stored procedures and triggers are nothing more than DB-CRACK. Easy to use in a "pinch" yet keeps you addicted forever.

    The concept of moving trigger/stored procedure coding out of the database engine is the scariest thought for Oracle/MS/IBM....yet it works surprisingly well in the freebie MySQL.

    This subject is so deep and broad it leaves the mega dollar database companies room for more FUD the HS in NYC in 1905 (check that one out in your database).

    SCALE THAT IN YOUR BOARDROOM!
  • Slow and painful (Score:2)

    by chrysalis (50680) on Thursday April 19 2007, @03:03AM (#18794797)
    (http://00f.net/)
    Hello,

    I worked a lot with MySQL stored procedures lately.

    While handy for small and simple things, MySQL stored procedures aren't that great for more complex processing.

    - Procedures are difficult to debug. There's no debugger and no way to trace what's going on except by using horrible tricks.
    - The language is somewhat limited. Doing very simple things can require dozen of lines, with juggling between local and thread-local variables. And since there's nothing like arrays or associative arrays, you have to use temporary or MEMORY tables to do the job, and it implies some more horrible tricks.
    - It's slow. Slow, Damn slow.

    This is why UDFs are still the way to go for any complex task.
    • Exactly by theolein (Score:2) Thursday April 19 2007, @05:19AM
  • by theolein (316044) on Thursday April 19 2007, @05:15AM (#18795395)
    I've used stored procedures in Mysql, and have to say that they are very limited for anything complex. There are a lot of limitations in both stored procedures and functions which make them almost unusable for real tasks. The limitations have mainly to do with what you can pass to the procedures and functions and what you can return.
  • by felix (7014) on Thursday April 19 2007, @06:33AM (#18795729)
    (http://comments.deasil.com/ | Last Journal: Tuesday June 28 2005, @02:39PM)
    It's definitely worth checking out if you use MySQL. It's well written and comprehensive. My own review was very close to this one. You can check it out on my blog [deasil.com] (or amazon).
  • by zappepcs (820751) on Wednesday April 18 2007, @02:48PM (#18787027)
    (Last Journal: Friday May 18, @11:07AM)
    I too run several databases as warehouses, and consequently I don't have a crushing need for blinding speed or speed increases due to stored procedures. Consequently all our database can be dropped off a cliff, hardware replaced and warehouse rebuilt to usability in less than a week, with NO data loss as a result of the architecture. Stored procedures would make that much more difficult, unless for some reason I completely don't understand anything about data warehousing... it could happen
    [ Parent ]
    • Re:Stored procedures BAD... story (Score:5, Insightful)

      by drmerope (771119) on Wednesday April 18 2007, @02:56PM (#18787135)
      The purpose behind stored procedures is not speed. It is about data integrity. Trigger functions are used to maintain additional coherence rules that are not easily expressed by unique, not null, referential integrity, etc. You place these rules in the database so that every consumer application of the database goes through the same logic--receives the benefits of the logic and enforces a coherent logic.
      [ Parent ]
  • Re:Stored procedures BAD... story (Score:5, Insightful)

    by dedazo (737510) on Wednesday April 18 2007, @02:49PM (#18787041)
    (Last Journal: Friday August 31, @07:08PM)

    As a manager now, I would fire anyone who uses stored procedures. Even if it is "faster."

    Rest assured that if you were one of my developers you'd be out the door in no time. The application you're describing here cannot be anything north of trivial if you were able to just switch a connection string and all your messy inline SQL statements continued to run without any changes whatsoever (which I seriously doubt). Not everyone writes trivial applications.

    There are reasons other than "fast" to using stored procedures. I've seen enough misuse of SPs, functions and triggers to fill up a book, but when done correctly they are simply superior to the alternative in just about every way.

    [ Parent ]
  • by Cyberax (705495) on Wednesday April 18 2007, @02:50PM (#18787053)
    SP are OK for complex tasks like building reports or complex searches. You won't be able to do it DB-independently, anyway. And the speed difference between SP and processing on client can often be measured in orders of magnitude.
    [ Parent ]
  • As a manager now, I would fire anyone who uses stored procedures. Even if it is "faster."

    I'm glad I don't work for you, then. Stored procedures are a tool, like any other, that come with their own set of pros and cons. In some situations, the ability to quickly migrate to an alternate database outweighs the benefits that stored procedures may provide. In other situations, it doesn't. The decision to use them or not should be based solely on business requirements, rather than the irrational hatred you seem to be using as a guide.

    [ Parent ]
  • Re:Stored procedures BAD... story (Score:3, Insightful)

    by DavidpFitz (136265) on Wednesday April 18 2007, @02:52PM (#18787081)
    (http://www.fitzg.com/ | Last Journal: Wednesday May 07 2003, @03:06AM)

    As a manager now, I would fire anyone who uses stored procedures. Even if it is "faster."

    And you'd get sued shortly thereafter for unfair dismissal ... some manager you are proving yourself to be! A more pragmatic person in a management position would know that you use the right tool for the right job.

    There are plenty of good reasons to use stored procedures in a database - they simply wouldn't exist in every serious database if they were not useful. Speed isn't the only reason to use a stored procedure, they can also make some inter-application integration much easier and allow someone in control of the data model to abstract the data collection routines from the underlying data structure - which can be very, very useful. I don't want some Java programmer thinking he knows the best way to get at data in Oracle - using a stored procedure to pass complex data structures back allows tweaking of the select statements, indexes etc... without any testing required of the app layer.

    D.
    [ Parent ]
  • Stored procedures and data integrity (Score:3, Insightful)

    by Tony (765) * on Wednesday April 18 2007, @02:53PM (#18787093)
    (http://zoeshire.com/ | Last Journal: Thursday October 31 2002, @05:12PM)
    The point of stored procedures is not to make access easier, or anything like that. The point from the RDBMS perspective is to keep your data coherent. Data integrity is THE MOST IMPORTANT role of a database. That's why 3rd normal form is important. That's why stored procedures and triggers and rules are important.

    As a database engineer, I would *definitely* fire anyone who didn't use these tools to maintain data integrity.
    [ Parent ]
  • by CastrTroy (595695) on Wednesday April 18 2007, @02:55PM (#18787127)
    (http://www.kibbee.ca/)
    In some instances, it really can speed things up. I would recommend that they not be used, except where speed is actually an issue. Most of the time you don't need it, and it definitely shouldn't be used for every query, but there are situations where it is necessary to keep the application at a usable speed.
    [ Parent ]
  • Re:Stored procedures BAD... story (Score:4, Insightful)

    by PCM2 (4486) on Wednesday April 18 2007, @02:57PM (#18787141)
    (http://neilmcallister.com/)

    As a manager now, I would fire anyone who uses stored procedures. Even if it is "faster."

    So answer me this: Now that you've made the investment to move to Oracle, can you reasonably foresee moving back to SQL Server? Seems unlikely to me. So if you'd chosen the right tool for the job in the first place, the migration wouldn't have been a problem and you would have been free to use other right tools where appropriate, e.g. stored procedures -- right?

    Really, stored procedures have their place. Oracle tends to over-sell them, but to ignore them completely seems like one more step backward in the last n years of best practices and lessons learned.

    [ Parent ]
  • by LurkerXXX (667952) on Wednesday April 18 2007, @03:05PM (#18787251)
    And I would fire any moron who refused to use them. There are numerous reasons to use them. I find it scary that anyone employs you as a manager. You must be one of those PHBs from Dilbert.
    [ Parent ]
  • by nuzak (959558) on Wednesday April 18 2007, @03:12PM (#18787339)
    > As a manager now, I would fire anyone who uses stored procedures. Even if it is "faster."

    And your boss would fire you pretty fast. But I doubt you've ever fired anyone over it or even threatened it. Pretty much everyone who pulls out this "I would fire anyone who xxx" gem is full of shit, has never managed anyone, never should, and thankfully never will.
    [ Parent ]
  • Re:Stored procedures BAD... story (Score:2, Insightful)

    by RedElf (249078) on Wednesday April 18 2007, @03:17PM (#18787413)
    (http://slashdot.org/~RedElf)

    As a manager now, I would fire anyone who uses stored procedures. Even if it is "faster."
    As a database engineer I would refuse to work for such an incompetant manager who clearly doesn't understand the technology he is managing, but chooses to micromanage the implementation.
    [ Parent ]
    • 1 reply beneath your current threshold.
  • by Chicken04GTO (957041) on Wednesday April 18 2007, @03:20PM (#18787469)
    well, you certainly sound like a manager.

    You decide an entire methodology for development is stupid because of one bad experience and you would fire anyone who dare challenge your AUTHORITAY!
    [ Parent ]
  • by Hemogoblin (982564) on Wednesday April 18 2007, @03:33PM (#18787647)
    Do you happen to be a government employee? [worsethanfailure.com]

    "Our security consultant uninstalled all the stored procedures. They were too insecure."
    "Uh, I can reinstall the procedures, I have the SQL Server CD with me."
    "Get OUT."
    [ Parent ]
  • I don't get this prevalent urge to be able to "easily switch to another RDBMS". Each RDBMS has its own quirks and moer importantly its own strengths and weaknesses in terms of performance and available features. If you use MySQL and need performance you'll probably do without transactions and referential integrity, do atomic single table updates and try to avoid deletes. If you use Oracle you may try to avoid autocommitting minimal updates and instead collect them into a bit larger transactions. How can you then easily switch from one to the other? Oracle is wasted if you run it with a database designed for mysql and MySQL lacks the features to run a database designed for oracle.

    Pick a database suitable for your task and use it as optimally as possible; easy portability be damned.

    A few scenarios where on might worry about portability: (1) you're working on a system that you're hoping to get to work with whatever database the user has access to already, (2) you've gotten tired of being raped by Oracle's licensing, and you'd like to hold the door open to switching to another database, if only as a bargaining maneuver to push for discounts/reduced prices.

    On the other hand, if you actually trust the culture of the developers working on the database you're interested in, you might very well choose to embrace the special features of that database, because the need to switch to another one at some point in the future seems very unlikely to occur.

    (And if you ask me, this means "Postgresql". Trusting to Mysql culture does not sound like a great move to me.)

    [ Parent ]
  • by barjam (37372) on Wednesday April 18 2007, @04:46PM (#18788709)
    I was working for a startup in 2002... we had to cut costs anywhere we could so we dumped Oracle licensing. Me and another guy were able to convert the entire website and all our internal applications over the course of a day.

    We were using EJBs without stored procedures and the only reason it took as long as it did was because some of the more exotic queries we were using at the time.
    [ Parent ]
  • by Bob9113 (14996) on Wednesday April 18 2007, @04:59PM (#18788863)
    (http://www.traxel.com/)
    As a manager now, I would fire anyone who uses stored procedures. Even if it is "faster."

    It is possible, and in some cases effective, to split a system's logic into presentation logic, business logic, and data access logic. If you do that, it is possible to write a good three tier system that has some of the logic in the database (I'm referring to the data access logic - for the slow folks in the crowd).

    I'm not saying that every database backed system should be this way. Nor even that every database backed system will benefit from it. But there are some systems that can benefit from it. This is particularly true when the ability to migrate between RDBMSs is a very low priority (or claimed to be a non-priority), and the decoupling of the data access logic from the business logic is a very high priority.

    Rules of thumb are nice. Absolute laws are the enemy of pragmatic system design.
    [ Parent ]
  • by HornWumpus (783565) on Wednesday April 18 2007, @08:40PM (#18791661)

    So we can not apply there and short your companies stock!

    Asshat.

    [ Parent ]
  • 5 replies beneath your current threshold.