What are the orders of the following SQL statements from most to least efficient?
NOTE: Let the syntaxes be language agnostic (i.e. use TOP 1 in the proper place instead of LIMIT 1). Assume that table_name is the name of the table, column_name is the name of a column, id is the name of a column with a primary key, and the table has tens of thousands of records.
SELECT FIRST(column_name) FROM table_nameSELECT column_name FROM table_name LIMIT 1SELECT column_name FROM table_name WHERE id=1 --assumes the first id is 1SELECT column_name FROM table_name WHERE id=(SELECT MIN(id) FROM table_name)
AND
SELECT LAST(column_name) FROM table_nameSELECT column_name FROM table_name ORDER BY id DESC LIMIT 1SELECT column_name FROM table_name WHERE id=(SELECT COUNT(id) FROM table_name) --assumes no values have been skippedSELECT column_name FROM table_name WHERE id=(SELECT MAX(id) FROM table_name)
I don’t know how to benchmark these statements but my guess is 2, 3, 1, 4 for getting the first record and 3, 2, 1, 4 for getting the last record.
I am guessing but; FIRST and LAST are grouping operations. For the query engine to get their results it would need to collect the data first.
The others just need to return the first row it finds.
If there’s an index on ‘id’ ordering it descending is not very expensive.