Stories
Slash Boxes
Comments

News for nerds, stuff that matters

SQL Cookbook

Posted by samzenpus on Wed May 10, 2006 02:05 PM
from the database-dinners dept.
Simon P. Chappell writes "One of the staples of corporate I.S. development is processing data, and increasingly these days that data lives in a relational database. The lingua franca of relational database programming is the Structured Query Language (SQL), often pronounced "sequel". Many programmers find that the basics of SQL are easy to learn, but after that, it tends to get complicated. Enter the SQL Cookbook from O'Reilly." Read the rest of Simon's review.
SQL Cookbook
author Anthony Molinaro
pages 595 (9 page index)
publisher O'Reilly
rating 8/10
reviewer Simon P. Chappell
ISBN 0596009763
summary If you need help working with a database, this is the book for you.


The book is not for beginners and makes no efforts to teach any SQL. It concentrates purely on building on the base level of SQL knowledge that most programmers have. If you know the basics: Create, Read, Update and Delete (an unfortunate, yet memorable acronym) but rarely go beyond that, this book is for you. I know that I fall into this target market.

The point of the cookbook is that you need to get something done and you need to get it done sooner rather than later. Now, most of us can figure out most things given enough time, but in the real world, we rarely have enough time. The cookbooks objective is to save you time by giving you a successful approach that you could have figured out eventually anyway.

If you've previously read any other technology cookbook from O'Reilly, then you already know the structure of the recipes. For those new to the O'Reilly cookbook format, it's actually fairly straightforward. Each recipe starts out with a problem statement. Recipe one in chapter one, titled "Retrieving all Rows and Columns from a Table" has the problem statement "You have a table and want to see all of the data in it." Nice and clear. Then comes the solution. Naturally, for this problem statement we end up with a SELECT that looks like this:


select * from emp


Then the recipe has a discussion section where the solution is explained in more detail and the reasoning behind it is provided. For recipe one, the discussion explores the trade-offs between using the "*" to signify all columns versus naming each column explicitly.

The chapter structure through the book is very much one of building on the previous material. The first chapter starts with the fundamentals, the retrieving of records and then chapter two takes over with sorting the results of your query, while chapter three looks at using multiple tables.

Chapter four covers inserting, updating and deleting records. After that it's back into the world of queries, with chapter five exploring metadata queries for those times when you need to know just a little more about what's going on under the covers. Chapter six looks at working with Strings, a much harder topic than it would seem at first thought. Chapter seven addresses working with numbers and chapter eight does the same for date arithmetic with chapter nine bringing more understanding to general date manipulation. Chapter ten looks at working with ranges.

Chapter eleven dives into advanced searching in preparation for chapter twelve's information on reporting and (data) warehousing. Hierarchical queries are always challenging, so they're reserved for chapter thirteen. Finally, chapter fourteen is titled "Odds 'n' Ends" and is a general catch-all for some pretty advanced, but very infrequent problems.

I guess you either like the recipe approach or not. I love it, so I'm listing it as something to like about this book. The recipes are very well explained and while each one presents only one approach, where there are obviously multiple options, the discussion takes care to explain the reasoning behind the selection.

The writing is clear and the explanations are well laid out. Both the SQL code and the query results are presented well and are easy to read.

A very important part of the book is that it covers SQL variations for Oracle, IBM's DB2, Microsoft SQL Server and the open-source databases PostgresSQL and MySQL. Each of the recipes includes solutions for each of the five databases. While SQL is a standard, there seems to be some very relaxed definitions of full adherence to that standard; hence the book has to present up to five solutions for each problem.

Many of the recipes are advanced. While the front of the book has the entry level material, it ramps up in complexity pretty quickly. For some of us with very straightforward SQL knowledge, some of the recipes are going to take a while to fully understand and be able to use.

Many of the recipes are obviously oriented towards corporate reporting. If this is a big need for you, then this book goes along way to meeting your needs. If you have no need for corporate reporting, it's wasted paper.

This is an excellent book; it does exactly what it sets out to do and fully equips you to handle the most sophisticated database transactions.


You can purchase SQL Cookbook from bn.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.
  • Recommendation (Score:4, Informative)

    by PFI_Optix (936301) on Wednesday May 10 2006, @02:09PM (#15303151)
    (Last Journal: Friday March 31 2006, @11:17AM)
    As most people I know learn SQL and PHP together, if you're to the point that this book would be of benefit to you, I'd suggest also getting the PHP Cookbook. That book has done wonders on improving the quality of my code.
    • Re:Recommendation (Score:4, Insightful)

      If they write SQL like most people write PHP...yeesh.

      In my experience, the people who generally most need SQL books like this are the report guys...You know, not really IT, just kinda work on the fringes of things with Access and Crystal Reports...Don't know much about code, but are good with the data. I can see one of these being really useful. I have the Java Cookbook (and the Php cookbook, as it happens. =P), and they're pretty handy, though they fill a niche that I usually fill with google.
      [ Parent ]
      • Re:Recommendation (Score:5, Informative)

        by PFI_Optix (936301) on Wednesday May 10 2006, @02:28PM (#15303321)
        (Last Journal: Friday March 31 2006, @11:17AM)
        Google has failed me a few times with PHP issues, the cookbook has helped fill in the gaps there.

        Problems with finding answers on the web:

        1) The code for the answers to problem A and problem B don't necessarily work together

        2) The code is of questionable quality. I'm six months in to teaching myself PHP (and CSS, SQL, and a few web server applications) and I can tell you that the code I wrote just two months ago was utter crap, largely because it was based on web tutorials that completely neglected good practices.

        3) I have no prior experience or training with programming, which makes it hard to even know where to start looking for a solution. Books like this have helped me learn how to know what I need to search for.
        [ Parent ]
        • Re:Recommendation (Score:5, Informative)

          by jbarket (530468) on Wednesday May 10 2006, @02:56PM (#15303564)
          The PHP manual is the absolute must use resource.

          Not only is it obviously a complete reference guide to the language, but the user comments on each function often cover a wide variety of uses that can help solve your particular problem. More importantly, if poor quality code is posted, someone will often post a cleaned up version.

          Not to knock books at all. Just saying, there's a great free resource out there that is vastly superior to the hundreds of ad ridden script sites.
          [ Parent ]
      • Re:Recommendation by drinkypoo (Score:2) Wednesday May 10 2006, @02:44PM
      • Re:Recommendation (Score:4, Interesting)

        by WindBourne (631190) on Wednesday May 10 2006, @02:44PM (#15303463)
        (Last Journal: Friday December 01 2006, @10:51AM)
        Normally, I do staight coding on servers, sometimes the client. Most of my work does not involve huge amounts of DB work. So I get by on the DB, but I do not consider it a strength.

        Now, I am in a job where currently, I am testing data that is being modified through a series of transforms. We test by loading the end work and taking it back to the initial work (i.e. we reverse the process). We find it easy to load the data into a Postgres DB, create views with conversion functions to take end->initial and then run an assortment of queries over the data to make certain that it is correct. I have found that I do go back to several book to make sure of my sql as well as to improve the speeds (a subquery took 20 min to run while using a except gaves a similar answer in under several seconds. BIG difference considering that we are looking at many tables with a number of tests each).

        The books help.
        [ Parent ]
      • Re:Recommendation by rainman_bc (Score:2) Thursday May 11 2006, @11:11AM
      • 1 reply beneath your current threshold.
    • Re:Recommendation (Score:5, Insightful)

      by fh8510 (967845) on Wednesday May 10 2006, @02:37PM (#15303400)
      Most people I know who use SQL work in Java, Ruby, Python, C++, JDBC, ODBC, ASP.NET, Hibernate, etc. Please, there are so many SQL related technologies. PHP is not the be-all, end-all one. The beauty of SQL is that it's a language, platform independent way to define and manipulate relational data. It's a data-centric way to deal with data. Adding one of the related language to the mix just muddles things.
      [ Parent ]
    • Re:Recommendation by flogic42 (Score:1) Wednesday May 10 2006, @02:46PM
    • Re:Recommendation by Crizp (Score:2) Wednesday May 10 2006, @06:07PM
    • Re:PHP cookbook by gregarican (Score:2) Wednesday May 10 2006, @02:32PM
    • 2 replies beneath your current threshold.
  • Shit, I've been calling it squirrel all this time!
    • Re:sequel? by iggymanz (Score:2) Wednesday May 10 2006, @02:20PM
      • 1 reply beneath your current threshold.
    • Re:sequel? by ottffssent (Score:3) Wednesday May 10 2006, @03:09PM
    • Re:sequel? ...... Squeal by erbmjw (Score:2) Wednesday May 10 2006, @03:42PM
    • Re:sequel? by Anonymous Coward (Score:1) Wednesday May 10 2006, @03:54PM
    • 2 replies beneath your current threshold.
  • Microsofties say "sequel" (Score:1, Informative)

    by Anonymous Coward on Wednesday May 10 2006, @02:16PM (#15303212)
    Unix MEN say S.Q.L.
  • BN vs. Amazon (Score:5, Informative)

    by CheeseTroll (696413) on Wednesday May 10 2006, @02:17PM (#15303223)
    You could pay $39 from BN, or $26.37 at Amazon.

    This looks like a very handy reference for those of us who can read SQL statements alright, but have grown lazy with all the GUI SQL-statement builders that exist now.
  • The practical SQL handbook (Score:5, Informative)

    by WindBourne (631190) on Wednesday May 10 2006, @02:19PM (#15303238)
    (Last Journal: Friday December 01 2006, @10:51AM)
    For those of you just starting out, try the the practical sql handbook. [amazon.com] I recently glanced through edition 3. I started at edition one years ago. It still remains an awesome book.
  • Joe Celko (Score:4, Informative)

    by ytsejam-ppc (134620) on Wednesday May 10 2006, @02:23PM (#15303285)
    There are a few books by Joe Celko like SQL For Smarties that are in the position of honor on my bookshelf. If you're beyond "select * from emp" and want to really learn how to efficiently get things done in a relational database, Celko is your guy.

    • Re:Joe Celko by andynms (Score:1) Wednesday May 10 2006, @02:34PM
    • Re:Joe Celko by Sezzler (Score:1) Wednesday May 10 2006, @03:54PM
    • Re:Joe Celko by ZenFu (Score:1) Thursday May 11 2006, @02:41PM
    • 3 replies beneath your current threshold.
  • More Cooking with SQL (Score:5, Funny)

    by digitaldc (879047) * on Wednesday May 10 2006, @02:31PM (#15303348)
    SELECT eggs (*) AS ingredients
    FROM Refrigerator
    GROUP BY NO.dozen
    INSERT INTO my_fryingpan (eggs1, butter1)
    UPDATE my_table SET toast = 'lightly browned'
    INSERT hole INTO toast
    MERGE eggs INTO toast
    USING (
    SELECT Eggs, Toast)
    CREATE Breakfast eggy_toast
    DELETE FROM my_table WHERE plate = 'N'
  • by jdbartlett (941012) on Wednesday May 10 2006, @02:37PM (#15303396)
    SQL, you say? Never heard of it. Must be something new.
  • Speak more slowly, please... (Score:4, Funny)

    by TopShelf (92521) on Wednesday May 10 2006, @02:38PM (#15303407)
    (http://forechecker.blogspot.com/ | Last Journal: Friday September 07, @08:16PM)
    One of the staples of corporate I.S. development is processing data, and increasingly these days that data lives in a relational database.

    Thank you, Mr. Obvious!
  • There is also a MySQL Cookbook (Score:2, Informative)

    by vrTeach (37458) on Wednesday May 10 2006, @02:41PM (#15303433)
    As with the author of this review, I really like the cookbook format. I've made heavy use of the MySQL cookbook, also from O'Reilly, by Paul DuBois. It is excelent, and just about everything that Simon P. Chappell says about the SQL Cookbook applies, except of course the focus on just MySQL. I'm glad to hear of the SQL cookbook because I'll be developing for postgresql as well as MySQL in the near future. Thanks.
  • sql (Score:3, Funny)

    by flogic42 (948616) on Wednesday May 10 2006, @02:41PM (#15303434)
    (http://spherical-cows.blogspot.com/)
    Select * From SovietRussia Where Article AND ReadsYOU
  • SQL is a standard. Is it? (Score:1, Informative)

    by hypersql (954649) on Wednesday May 10 2006, @02:48PM (#15303494)
    What I have always found funny about SQL is that, while it's very 'old' (in software terms), and mature, and widely used, there is in fact no real standard. There never was. From the article:

    SQL variations ... While SQL is a standard, there seems to be some very relaxed definitions of full adherence to that standard...

    Or, as Jim Starkey said: 'SQL isn't a standard but a theme'. For a book, it means list 5 different dialects. For regular developers (not database specialists) it means knowing only one dialect really well. For an application it means, running only with one database (mostly). It would be really cool the industry could get together and define a 'real' standard. Could be a subset of SQL (http://ldbc.sf.net/ [sf.net]) or a new language (http://newsql.sf.net/ [sf.net]). Things would get simpler then.

    (Side note: LDBC and NewSQL are both projects I started, but interest was quite low; currently I'm working on a new database engine http://www.h2database.com/ [h2database.com] where I try to be compatible as much as possible with existing databases)

    Or is there some other solution? I don't think that that O/R mapping tools will solve the problem completely, as there is always the need interactive database queries. Maybe the Microsoft extension to C# (forgot the name) could be a solution? Other ideas?

    • Re:SQL is a standard. Is it? by Aladrin (Score:2) Wednesday May 10 2006, @03:09PM
    • Re:SQL is a standard. Is it? (Score:5, Informative)

      by orthogonal (588627) on Wednesday May 10 2006, @04:10PM (#15304145)
      (Last Journal: Sunday April 16 2006, @10:03PM)
      there is in fact no real standard

      Yes, there's a great deal of nonconformance and extensions.

      But, there is a standard, in fact, five: SQL-86, SQL-89, SQL-92, SQL:1999 and SQL:2003 (yeah, dashes replaced by colons, go figure). SQL:2003 can be purchased from ANSI or ISO, just like the C or C++ standards.

      Various sites [www.tar.hu] list product conformance to the standards.

      When I write SQL, I pretty rigorously stick to SQL-99, as that's likely to be supported by most vendors. If I need to deviate from that, I make sure I know how to replicate the vendor-specific code in SQL-99 (e.g, postgresql's inherits keyword -- it's useful for sub-typing, but it can be effected by using joins and views).

      If the non-standard code is DML (not DDL), I'll do my best to encapsulate it in a stored procedure or a view, and let the rest of my code call the encapsulated abstraction. This is just the same layering you'd do in any programming language to wall off platform-specific code. And just as you'd typedef in C or create abstract types in C++, you create UDTs in SQL too.

      Here's an example, using a useful testing date "function" that is cross-dialect, doesn't rely on any user-supplied function support, and can be incorporated into live code.

      -- postgresql
      CREATE DOMAIN datetime_type timestamp null;
      create view system_datetime as select 1 as id, now() as date_now ;

      -- MS SQL server
      create type datetime_type from datetime null;
      create view system_datetime as select 1 as id, getdate() as date_now ;


      -- code below is SQL dialect independent
      -- works on postgresql or MS SQL server


      -- code to use actual current date or fake date for testing purposes
      -- all DML that wants the current system timestamp should instead join on (or subselect) the view date_now
      -- this view always returns a single row

      create table test_date ( id int, test_date datetime_type ) ;
      insert test_date values ( 1, null ) ;

      create view date_now as
      select
      coalesce(
      ( select test_date from test_date where id = 1) ,
      ( select date_now from system_datetime where id = 1)
      ) as date_now ;

      -- note: for Sybase, replace coalesce with isnull

      -- see what invoices were due as of January 1:
      update test_date set test_date = '1/1/2006' ;

      select * from invoices a, date_now b
      where a.issue_date <= b.date_now
      and ( a.paid_date > b.date_now or a.paid_date is null )

      -- look at real invoices due as of now
      -- Query is the same, we just null out the fake date:

      update test_date set test_date = null ;

      select * from invoices a, date_now b
      where a.issue_date <= b.date_now
      and ( a.paid_date > b.date_now or a.paid_date is null )


      (And yes, you can hire me.)
      [ Parent ]
    • Re:SQL is a standard. Is it? by oh_my_080980980 (Score:1) Wednesday May 10 2006, @04:17PM
    • Re:SQL is a standard. Is it? by clive_p (Score:2) Wednesday May 10 2006, @04:47PM
    • 1 reply beneath your current threshold.
  • Sample chapter (Score:4, Informative)

    by sootman (158191) on Wednesday May 10 2006, @02:51PM (#15303513)
    (Last Journal: Thursday July 12, @12:30PM)
    Chapter 11: Searching [oreilly.com]
    40 pages, 500k PDF
    • 1 reply beneath your current threshold.
  • Yawn... (Score:1)

    by flyweight_of_fury (972871) on Wednesday May 10 2006, @03:06PM (#15303636)
    Great - yet another book that teaches me the "ins-and-outs" of the "Northwind" database. Seriously, when are publishers and authors going to come out with more original content? For instance - content for those of us that AREN'T designing HR or order entry apps?

    Ah well, it could be worse - it could be teaching me how to build another class registration system....
    • Re:Yawn... by geekoid (Score:2) Wednesday May 10 2006, @03:37PM
    • Re:Yawn... by RorthronTheWise (Score:1) Wednesday May 10 2006, @03:48PM
      • Re:Yawn... by flyweight_of_fury (Score:1) Wednesday May 10 2006, @04:09PM
        • 1 reply beneath your current threshold.
    • 1 reply beneath your current threshold.
  • by tfcdesign (667499) on Wednesday May 10 2006, @03:15PM (#15303711)
    (Last Journal: Monday October 13 2003, @03:10PM)
    is a book full of sample queries.

    Half the time I am using PHP for something SQL could do in a couple simple commands.
  • five stars (Score:1)

    by dankelley (573611) on Wednesday May 10 2006, @04:08PM (#15304126)
    (Average of 1 Customer Reviews)
  • Not for beginners?!? Doubtful (Score:2, Informative)

    by GalacticCmdr (944723) on Wednesday May 10 2006, @04:23PM (#15304235)

    I am not sure how anyone can resolve the following found in the review - emphasis mine.

    The book is not for beginners and makes no efforts to teach any SQL. It concentrates purely on building on the base level of SQL knowledge that most programmers have. If you know the basics: Create, Read, Update and Delete (an unfortunate, yet memorable acronym) but rarely go beyond that, this book is for you. I know that I fall into this target market.

    Recipe one in chapter one, titled "Retrieving all Rows and Columns from a Table" has the problem statement "You have a table and want to see all of the data in it." Nice and clear. Then comes the solution. Naturally, for this problem statement we end up with a SELECT that looks like this:

    select * from emp

    How can a book not be for beginners when the first recipe teaches the most basic SQL command possible? I have this book and it is a very good book, but like most technical books it kills a great deal of trees needlessly to pad its count. You can probably rip more than 100 pages out of the book that is mindless beginner crap and self-flogging and actually have a very good technical reference for mid-level SQL people.

  • set theory (Score:1)

    by tabby (592506) on Wednesday May 10 2006, @04:40PM (#15304357)
    (http://misondau.spaces.live.com/)
    I spend a lot of work hours reading/debugging/re-writing other peoples MSSQL stored procs. While it seems the people before me didn't understand the idea of a set-based language at all (CURSORS! CURSORS! CURSORS!) I understand the concept but have little experience implementing it. Can anyone suggest a SQL reference that puts emphasis on teaching how to implement set-based logic in stored procs, rather than just procedural batches?
    • 1 reply beneath your current threshold.
  • SQL is growing long in the tooth. It is time to replace it with something better that learns from lessons of the past. One proposal is Tutorial D, by Chris Date. I have also proposed "TQL" (or SMEQL due to a name comflict with another product) as a draft SQL replacement. Unlike Tutorial D, SMEQL uses a prefix notation for the main relational operaters. This makes it easier to extend by DBA's. If you don't like the out-of-the-box set of relational operators, you can define your own (using the existing ones). I have even created a wannabe book cover [geocities.com] for SMEQL.
  • ebooks / standards (Score:1)

    by lon3st4r (973469) on Thursday May 11 2006, @02:07AM (#15306574)
    Are there any good e-books one could refer to for SQL? Is there a freely available standards document which describe how `base` SQL "should" be, like say the ANSI standards for C?
  • by Dr.Ruud (98254) on Thursday May 11 2006, @04:12AM (#15306801)
    From the pdf of _Chapter 11_ [oreilly.com]

    select a.ename,
                  (select count(*)
                      from emp b
                    where b.ename <= a.ename) as rn
        from emp a

    I would layout that like

    SELECT a.ename,
                  (SELECT COUNT(*)
                      FROM emp AS b
                    WHERE b.ename <= a.ename) AS rn
        FROM emp AS a

    or like

    select a.ename,
                  (select count(*)
                      from emp as b
                    where b.ename <= a.ename) as rn
        from emp as a

  • SQL for Smarties (Score:3, Informative)

    by nrrd (4521) on Thursday May 11 2006, @11:35AM (#15309465)
    (http://www.polaski.com/)
    SQL for smarties is the best advanced SQL book I've seen. Highly recommended for developers, and should be on the bookshelf of any DBA.
    • 1 reply beneath your current threshold.
  • by DavidTurner (614097) on Friday May 12 2006, @01:26AM (#15315717)
    I'd buy this book in an instant if it could give me a good (efficient) solution for this query: return the set of most recent sales grouped by customer. [Stands back and smirks while flocks of geeks bang their heads against relational algebra]
  • Re:Mispronunciation (Score:1, Informative)

    by pclminion (145572) on Wednesday May 10 2006, @02:39PM (#15303422)
    SQL started out being called SEQUEL (and pronounced as such) until it was changed to SQL due to trademark issues. IMHO, the historical pronunciation is a valid precedent. See the History section of the SQL Wikipedia entry.
    [ Parent ]
  • Re:Mispronunciation (Score:1, Interesting)

    by Anonymous Coward on Wednesday May 10 2006, @02:53PM (#15303533)
    Chris Date has stated in many of his books on RDMS theory and practice, several of which were published before many Slashdotters were born, that SQL is pronounced 'sequel'. Good enough for me.
    [ Parent ]
  • 10 replies beneath your current threshold.