You are on page 1of 5

Services Team Contact Us Links Store

Rates Custom ers Papers PostGIS in Action

Back to Papers and Articles


SQL Cheat Sheet: Query By Example

Copyright 2005 Paragon Corporation

( July 02, 2005)

Why Use SQL Over procedural?


Structured Query Language (SQL) is a set-based language as opposed to a procedural language. It is the defacto language of relational databases. The difference between a set-based language vs. a procedural language is that in a set-based language you define what set of data you want or want to operate on and the atomic operation to apply to each element of the set. You leave it up to the Database process to decide how best to collect that data and apply your operations. In a procedural language, you basically map out step by step loop by loop how you collect and update that data. There are two main reasons why SQL is often better to use than procedural code.

It is often much shorter to write - you can do an update or summary procedure in one line of code that would take you several lines of procedural. For set-based problems - SQL is much faster processor-wise and IO wise too because all the underlining looping iteration is delegated to a database server process that does it in a very low level way and uses IO/processor more efficiently and knows the current state of the data - e.g. what other processes are asking for the data.

Example SQL vs. Procedural


If you were to update say a sales person of all customers in a particular region your procedural way would look something like this
d ou n t i le o f i fr s ( " s t a t e " )=" N H "t h e n r s ( " s a l e s p e r s o n " )=" M i k e " e n di f r s . n e x t l o o p

The SQL way would be: U P D A T Ec u s t o m e r sS E Ts a l e s p e r s o n=" M i k e "W H E R Es t a t e=" N H " If you had say 2 or 3 tables you need to check, your procedural quickly becomes difficult to manage as you pile on nested loop after loop. In this article we will provide some common data questions and processes that SQL is well suited for and SQL solutions to these tasks. Most of these examples are fairly standard ANSI-SQL so should work on most relational databases such as IBM DBII, PostGreSQL, MySQL, Microsoft SQL Server, Oracle, Microsoft Access, SQLite
www.paragoncorporation.com/ArticleDetail.aspx?ArticleID=27 1/5

with little change. Some examples involving subselects or complex joins or the more complex updates involving 2 or more tables may not work in less advanced relational databases such as MySQL, MSAccess or SQLite. These examples are most useful for people already familiar with SQL. We will not go into any detail about how these work and why they work, but leave it up to the reader as an intellectual exercise.

List all records from one table that are in another table
What customers have bought from us?
S E L E C TD I S T I N C Tc u s t o m e r s . c u s t o m e r _ i d ,c u s t o m e r s . c u s t o m e r _ n a m e F R O Mc u s t o m e r sI N N E RJ O I No r d e r sO Nc u s t o m e r s . c u s t o m e r _ i d=o r d e r s . c u s t o m e r _ i d

What items are in one table that are not in another table?
Example: What customers have never ordered anything from us? S E L E C Tc u s t o m e r s . *F R O Mc u s t o m e r sL E F TJ O I No r d e r sO N c u s t o m e r s . c u s t o m e r _ i d=o r d e r s . c u s t o m e r _ i dW H E R Eo r d e r s . c u s t o m e r _ i dI S N U L L More advanced example using a complex join: What customers have not ordered anything from us in the year 2004 - this one may not work in some lower relational databases (may have to use an IN clause) S E L E C Tc u s t o m e r s . *F R O Mc u s t o m e r sL E F TJ O I No r d e r sO N ( c u s t o m e r s . c u s t o m e r _ i d=o r d e r s . c u s t o m e r _ i dA N D y e a r ( o r d e r s . o r d e r _ d a t e )=2 0 0 4 )W H E R Eo r d e r s . o r d e r _ i dI SN U L L
Please note that year is not an ANSI-SQL function and that many databases do not support it, but have alternative ways of doing the same thing. SQL Server, MS Access, MySQL support year(). PostGreSQL you do date_part('year', orders.order_date) SQLite - substr(orders.order_date,1,4) - If you store the date in form YYYY-MM-DD Oracle - EXTRACT(YEAR FROM order_date) or to_char(order_date,'YYYY')

Note: You can also do the above with an IN clause, but an IN tends to be slower Same question with an IN clause S E L E C Tc u s t o m e r s . *F R O Mc u s t o m e r sW H E R Ec u s t o m e r s . c u s t o m e r _ i dN O T I N ( S E L E C Tc u s t o m e r _ i dF R O Mo r d e r sW H E R Ey e a r ( o r d e r s . o r d e r _ d a t e )= 2 0 0 4 )

Fun with Statistics - Aggregates


How many customers do we have in Massachusetts and California? S E L E C Tc u s t o m e r _ s t a t eA ss t a t e ,C O U N T ( c u s t o m e r _ i d )A st o t a lF R O M c u s t o m e r sW H E R Ec u s t o m e r _ s t a t eI N ( ' M A ' ,' C A ' )G R O U PB Yc u s t o m e r _ s t a t e What states do we have more than 5 customers?
S E L E C Tc u s t o m e r _ s t a t e ,C O U N T ( c u s t o m e r _ i d )A st o t a l
www.paragoncorporation.com/ArticleDetail.aspx?ArticleID=27 2/5

F R O Mc u s t o m e r s G R O U PB Yc u s t o m e r _ s t a t e H A V I N GC O U N T ( c u s t o m e r _ i d )>5

How many states do we have customers in?


S E L E C TC O U N T ( D I S T I N C Tc u s t o m e r _ s t a t e )A St o t a l F R O Mc u s t o m e r s

Note the above does not work in Microsoft Access or SQLite - they do not support COUNT(DISTINCT ..)

Alternative but slower approach for the above - for databases that don't support COUNT(DISTINCT ..), but support derived tables
S E L E C Tc o u n t ( c u s t o m e r _ s t a t e )F R O M( S E L E C TD I S T I N C Tc u s t o m e r _ s t a t eF R O Mc u s t o m e r s ) ;

List in descending order of orders placed customers that have placed more than 5 orders
S E L E C Tc u s t o m e r _ i d ,c u s t o m e r _ n a m e ,C O U N T ( o r d e r _ i d )a st o t a l F R O Mc u s t o m e r sI N N E RJ O I No r d e r sO Nc u s t o m e r s . c u s t o m e r _ i d=o r d e r s . c u s t o m e r _ i d G R O U PB Yc u s t o m e r _ i d ,c u s t o m e r _ n a m e H A V I N GC O U N T ( o r d e r _ i d )>5 O R D E RB YC O U N T ( o r d e r _ i d )D E S C

How do you insert records in a table?


Value Insert
I N S E R TI N T Oc u s t o m e r s ( c u s t o m e r _ i d ,c u s t o m e r _ n a m e ) V A L U E S ( ' 1 2 3 4 5 ' ,' G I SE x p e r t s ' )

Copy data from one table to another table


I N S E R TI N T Oc u s t o m e r s ( c u s t o m e r _ i d ,c u s t o m e r _ n a m e ) S E L E C Tc u s _ k e y ,c u s _ n a m e F R O Mj i m m y s c u s t o m e r sW H E R Ec u s t o m e r _ n a m eL I K E' B % '

Creating a new table with a bulk insert from another table


S E L E C T* I N T Oa r c h i v e c u s t o m e r s F R O Mj i m m y s c u s t o m e r sW H E R Ea c t i v e=0

How do you update records in a table?


Update from values U P D A T Ec u s t o m e r sS E Tc u s t o m e r _ s a l e s p e r s o n=' B i l l y 'W H E R E c u s t o m e r _ s t a t e=' T X ' Update based on information from another table U P D A T Ec u s t o m e r sS E Tr a t i n g=' G o o d 'F R O Mo r d e r sW H E R Eo r d e r d a t e> ' 2 0 0 5 0 1 0 1 'a n do r d e r s . c u s t o m e r _ i d=c u s t o m e r s . c u s t o m e r _ i d
www.paragoncorporation.com/ArticleDetail.aspx?ArticleID=27 3/5

Please note the date format varies depending on the database you are using and what date format you have it set to.

Update based on information from a derived table


U P D A T Ec u s t o m e r s S E Tt o t a l o r d e r s=o r d e r s u m m a r y . t o t a l F R O M( S E L E C Tc u s t o m e r _ i d ,c o u n t ( o r d e r _ i d )A st o t a l F R O Mo r d e r sG R O U PB Yc u s t o m e r _ i d )A so r d e r s u m m a r y W H E R Ec u s t o m e r s . c u s t o m e r _ i d=o r d e r s u m m a r y . c u s t o m e r _ i d Please note the update examples involving additional tables do not work in MySQL, MSAccess, SQLite.

MS Access Specific syntax for doing multi-table UPDATE joins U P D A T Ec u s t o m e r sI N N E RJ O I No r d e r sO Nc u s t o m e r s . c u s t o m e r _ i d= o r d e r s . c u s t o m e r _ i dS E Tc u s t o m e r s . r a t i n g=' G o o d ' MySQL 5 Specific syntax for doing multi-table UPDATE joins U P D A T Ec u s t o m e r s ,o r d e r sS E Tc u s t o m e r s . r a t i n g=' G o o d 'W H E R E o r d e r s . c u s t o m e r _ i d=c u s t o m e r s . c u s t o m e r _ i d Articles of Interest PostgreSQL 8.3 Summary of new and old PostgreSQL functions and SQL constructs complete xml query and export, and other new 8.3 features, with Cheat Sheet examples. SQLite If you are looking for a free and lite fairly SQL-92 compliant relational database, look no further. SQLite has ODBC drivers, PHP 5 already comes with an embedded SQLite driver, there are .NET drivers, freely available GUIs , and this will run on most Oses. All the data is stored in a single .db file so if you have a writeable folder and the drivers, thats all you need. So when you want something lite and don't want to go thru a database server install as you would have to with MySQL, MSSSQL, Oracle, PostgreSQL, or don't have admin access to your webserver and you don't need database group user permissions infrastructure, this is very useful. It also makes a nice transport mechanism for relational data as the size the db file is pretty much only limited to what your OS will allow for a file (or 2 terabytes which ever is lower). PostgreSQL Date Functions The Future of SQL by Craig Mullins Summarizing data with SQL (Structured Query Language) Procedural Versus Declarative Languages PostgreSQL Cheat Sheet Summary of PostGresql Date functions in 8.0 version Provides a very good definition of what set-based operations are and why SQL is superior for these tasks over procedural, as well as a brief history of the language. Article that defines all the components of an SQL statement for grouping data. We wrote it a couple of years ago, but it is still very applicable today.

Provides some useful anlaogies for thinking about the differences between procedural languages and a declarative language such as SQL Cheat sheet for common PostgreSQL tasks such as granting user rights, backing up databases, table maintenance, DDL commands (create, alter etc.), limit queries Covers MySQL datatypes, standard queries, functions

MySQL Cheat Sheet Comparison of This is a great summary of the different offerings of Standard SQL, PostGreSQL, DB2, MSSQL, MySQL, and Oracle. It demonstrates by different SQL
www.paragoncorporation.com/ArticleDetail.aspx?ArticleID=27 4/5

implementations clear example how each conforms or deviates from the ANSI SQL Standards with join syntax, limit syntaxx, views, inserts, boolean, handling of NULLS
SQL Cookbook Anthony Molinaro New $24.49 Best $17.97 Del.icio.us | Reddit | Digg | BlinkList | Furl Learning SQL Alan Beaulieu New $22.31 Best $13.49 Spurl | Simpy

Back to Papers and Articles


Services Rates Papers Staff Links Contact Us

Last rejuvenated: 2/24/2013 6:32:35 A M

2013 Paragon Corporation A ll Rights Reserved

www.paragoncorporation.com/ArticleDetail.aspx?ArticleID=27

5/5

You might also like