tags:

views:

110

answers:

3

What are some cool SQL shorthands that you know of?

For example, something I learned today is you can specify to group by an index:

SELECT col1, col2 FROM table GROUP BY 2

This will group by col2

+2  A: 

Ordinals - using numbers that are a reference to the place in the SELECT clause - can be used in the GROUP BY and ORDER BY clauses. But I don't recommend them because if the order changes, there'll be impact to your query.

Table aliasing is a must. IE:

SELECT
  FROM THIS_IS_MY_UNGODLY_TABLE_NAME timutn

...means I can use timutn rather than type the entire table name when I want/need to be clear which table a column comes from. It's essential when you have to join a table to itself, and who really wants to type the entire table name all the time anyway?

What really got me into table aliasing was that some SQL IDEs have smart enough intellisense to provide only a list of the columns for that table if you use the table alias.

OMG Ponies
+1, I use alias all the time.
x2
Not GROUP BY in SQL Server.
gbn
+3  A: 

See Aaron Bertrand's "Bad Habits in SQL to kick" series - he has a post on this and highly recommends not using that notation:

http://sqlblog.com/blogs/aaron%5Fbertrand/archive/2009/10/06/bad-habits-to-kick-order-by-ordinal.aspx

Marc

marc_s
+1  A: 

If your conditions for your query aren't known when you actually run it, WHERE 1=1 is useful

eg

$query = 'SELECT * FROM table ';

<?php if ( $something ) { ?>
$sql.= 'WHERE something = ' . $variable;
<?php } else { ?>
$sql.= 'WHERE something = ' . $another;
<?php } ?>

If there's lots of branching going on it can be such a pain ( and no I don't believe in building query strings either but this is just for the sake of the example ).

Easier way:

$query = 'SELECT * FROM table WHERE 1=1 ';

<?php if ( $something ) { ?>
$sql.= 'AND something = ' . $variable;
<?php } else { ?>
$sql.= 'AND something = ' . $another;
<?php } ?>

Of course I would probably use a wrapper/class that has a where method in which I can specify conditions.

meder
Can you explain why you use this and what benefits it gives?
gbn
ah I see. So you can build up SQL statements in client code more easily, hoping you don't leave yourself open to SQL injection... ;-)
gbn