tailieunhanh - SQL PROGRAMMING STYLE- P8

SQL PROGRAMMING STYLE- P8:Im mot trying to teach you to program in SQL in this book. You might want to read that again. If that is what you wanted, there are better books. This ought to be the second book you buy, not the first. I assume that you already write SQL at some level and want to get better at it. If you want to learn SQL programming tricks, get a copy of my other book, SQL for Smarties (3rd edition, 2005). | Thinking in SQL It ain t so much the things we don t know that get us into trouble. It s the thing we know that just ain t so. Artemus Ward Charles Farrar Browne American humorist 1834-1867 T . . HE BIGGEST HURDLE in learning SQL is thinking in sets and logic instead of in sequences and processes. I just gave you a list of heuristics in the previous chapter but let s take a little time to analyze why mistakes were made. You now have some theory but can you do diagnostics I tried to find common errors that new programmers make but perhaps the most difficult thing to learn is thinking in sets. Consider the classic puzzle shown in Figure . The usual mistake people make is trying to count the 1 x 1 x 2 bricks one at a time. This requires the ability to make a threedimensional mental model of the boxes which is really difficult for most of us. The right approach is to look at the whole block as if it were completely filled in. It is 4 x 5 x 5 units or 50 bricks. The corner that is knocked off is 3 bricks which we can count individually so we must have 47 bricks in the block. The arrangement inside the block does not matter at all. 184 CHAPTER 10 THINKING IN SQL ----------- Figure Classic block puzzle. All of these examples are based on actual postings in a newsgroup that have been translated into SQL PSM to remove proprietary features. In some cases I have cleaned up the data element names and in others I have left them. Obviously I am guessing at motivation for each example but I think I can defend my reasoning. Bad Programming in SQL and Procedural Languages As an example of not learning any relational approaches to a problem consider a posting in the newsgroup in January 2005 The title was How to Find a Hole in Records which already tells you that the poster is thinking in terms of a file system and not an RDBMS. The original table declaration had the usual newbie id column without a key or any constraints. The table modeled