views:

944

answers:

4

What is the most efficient way to select the first and last element only, from a column in SQLite?

Thanks.

+2  A: 

Probably like this:

SELECT dbo.Table.FirstCol, dbo.Table.LastCol FROM Table

You get minor efficiency enhancements from specifying the table name and schema.

magnifico
+9  A: 

The first and last element from a row?

SELECT column1, columnN
FROM mytable;

I think you must mean the first and last element from a column:

SELECT MIN(column1) AS First,
       MAX(column1) AS Last
FROM mytable;


See http://www.sqlite.org/lang_aggfunc.html for MIN() and MAX().

I'm using First and Last as column aliases.

Bill Karwin
Be sure to have an index on that column
Joe Philllips
Maybe not if it's a one-time query - it works fine anyway.
le dorfier
Yes column, sorry, still asleep
Tommy
Thanks, that works. I haven't seen a statement like this before. First and last are the sql functions?
Tommy
First and Last are column aliases; The work is being done by the Aggregate Functions MIN() and MAX().
Chris Shaffer
+3  A: 

The most efficient way would be to know what those fields were called and simply select them.

SELECT `first_field`, `last_field` FROM `table`;
Michael Wales
¿WTF? first and last *row* from a *column*, not first and last column from the row.
vartec
@vartec The question was originally stated "What is the most efficient way to select the first and last element only, from a row in SQL?"
Michael Wales
+3  A: 

if it's just one column:

SELECT min(column) as first, max(column) as last FROM table

if you want to select whole row:

SELECT 'first',* FROM table ORDER BY column DESC LIMIT 1
UNION 
SELECT 'last',* FROM table ORDER BY column ASC LIMIT 1
vartec