[ Home ]

SQL Tricks cover

SQL Tricks
by Chris Fehily

Download this book’s companion files.


This cookbook of advanced techniques is for anyone who knows the basics of SQL and wants to move beyond simple SELECT-FROM-WHERE queries. You’ll find solutions to problems that analysts, app developers, and database programmers often face, from simple tasks, like picking random rows, to complex operations, like traversing hierarchies. Each recipe includes a discussion of the underlying logic, important concepts, and best practices. Take full advantage of standard (ANSI/ISO) SQL, or use DBMS-specific features that dramatically extend the power of standard SQL. Use the scores of code examples directly in real-world DBMS applications, or as a source of insight for related problems.

Prices and formats

Paperback ($14.99 list)
   Amazon paperback (US, UK, FR, DE, ES, IT)

Ebook ($9.99 list)
   Amazon Kindle (US, CA, UK, FR, DE, ES, IT, JP, BR)
   Apple iBooks (US, CA, MX, AU, NZ, UK, IE, DE, IT, SE, NL, DK, JP, BR, more)
   Barnes & Noble Nook
   Google Play


1. Running SQL Programs
2. Calculating Running Statistics
3. Generating Sequences
4. Finding Sequences, Runs, and Regions
5. Limiting the Number of Rows Returned
6. Assigning Ranks
7. Calculating a Trimmed Mean
8. Picking Random Rows
9. Handling Duplicates
10. Creating a Telephone List
11. Retrieving Metadata
12. Working with Dates
13. Calculating a Median
14. Finding Extreme Values
15. Changing Running Statistics Midstream
16. Pivoting Results
17. Working with Hierarchies


This book’s examples use the sample database books, described in “The Sample Database” in the introduction. To create books, download the zip file sql_tricks_files.zip, expand it, and follow the instructions for your DBMS, listed below. The file readme.txt describes the distribution.

If you’re running a DBMS locally (that is, on your own computer), then you’re the database administrator (DBA) and have all the privileges you need. If you’re connecting to a DBMS on a network server, then ask your DBA for connection parameters and the privileges to create, query, update, and drop databases and tables.