Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL with LIMIT1 returns all records

Tags:

sql

I made a mistake and entered:

SELECT * FROM table LIMIT1

instead of

SELECT * FROM table LIMIT 1 (note the space between LIMIT and 1)

in the CLI of MySQL. I expected to receive some kind of parse error, but I was surprised, because the query returned all of the records in the table. My first thought was "stupid MySQL, I bet that this will return error in PostgreSQL", but PostgreSQL also returned all records. Then tested it with SQLite - with the same result.

After some digging, I realized that it doesn't matter what I enter after the table. As long as there are no WHERE/ORDER/GROUP clauses:

SELECT * FROM table SOMETHING -- works and returns all records in table

SELECT * FROM table WHERE true SOMETHING -- doesn't work - returns parse error

I guess that this is a standardized behavior, but I couldn't find any explanation why's that. Any ideas?

like image 827
strkol Avatar asked Jul 11 '12 12:07

strkol


1 Answers

Your first query is equivalent to this query using a table alias:

SELECT * FROM yourtable AS LIMIT1

The AS keyword is optional. The table alias allows you to refer to columns of that table using the alias LIMIT1.foo rather than the original table name. It can be useful to use aliases if you wish to give tables a shorter or a more descriptive alias within a query. It is necessary to use aliases if you join a table to itself.

From the SQL lite documentation:

AS keyword optional

like image 56
Mark Byers Avatar answered Oct 21 '22 09:10

Mark Byers