One of the most powerful new features in MySQL 4.1 is subqueries, which make it possible to nest multiple SQL queries within each other. This introductory segment of a two-part tutorial demonstrates how to use this new feature to build sophisticated data retrieval queries, illustrating (among other things) how to use subqueries in WHERE and HAVING clauses, with comparison and logical operators, with aggregate functions, and with inner, left, right and self joins.
If you've been following this column over the past few months, you've probably already picked up on the fact that I'm a big fan of MySQL, the free, open-source RDBMS. MySQL has a huge fan following all over the world - the site claims that over 30,000 copies of the software are downloaded *every day* by developers and users - and, with large corporate houses like SAP taking an interest in its future development, it's quickly becoming a worthy alternative to commercial products.
Earlier versions of MySQL (the 3.23.x series) were pretty basic, as far as SQL databases go - they supported simple data creation and manipulation constructs like INSERT, UPDATE, DELETE and SELECT, and included support for fundamental things like comparison and logical operators, aggregate functions, indices, primary keys and sequences. However, they lacked support for more advanced features - transaction processing, subqueries, multi-table operations - focusing instead on delivering the basic set of services reliably and efficiently. MySQL 4.x, though, has shaken things up a little - its chock-full of new features (including all the items mentioned above), and promises to aggressively continue innovating and adding new capabilities to its already bulging feature-set.
One of the newest features in MySQL, and one of its most eagerly-anticipated ones, is subqueries. Subqueries have been on the MySQL wishlist for a while; they've finally made an appearance in MySQL 4.1, and, as someone who's been playing with them for a little while, I can tell you that they're pretty useful. Sadly, however, since the software is still under development, there isn't too much information available at the moment on their full capabilities in the MySQL context.
That's where this article comes in. Over this two-part tutorial, I will be introducing you to subqueries, which make it possible for you to do all kinds of creative things with your SQL queries. Regardless of whether you've a novice who's never heard of subqueries before but are eager to find out how they can enrich your life, or someone who's been tinkering with MySQL for a while (like me), I think you'll find the next few pages interesting. So come on in, and let's get started.