Sunday, January 25, 2015

SQL Notes: Problem using LIMIT in your code?

I want to get only the first row of my select SQL.
Why? Because I wanted to get the max of the alpha numeric document number system.
The best way to do that (but this depends on the pattern) to a document number with good pattern like ABCXXXXX01 (X stands for digits), is to order it by DESC.

Problem is it's going to return a bunch of results, so instead of creating another method just to do that, why not limit the result to 1? The only problem is I'm ecountering this LIMIT error in PostgreSQL. So I have to find another way to fetch this 1 row.

So below are other ways to get that 1 row (data below are from: freedb2)
For example, in Microsoft SQL Server you would use TOP:
SELECT TOP 10 column FROM table
MySQL and PostgreSQL SQL would use LIMIT like so:
SELECT column FROM table LIMIT 10
PostgreSQL v8.3 and later can also use this more standard SQL:
SELECT column FROM table FETCH FIRST 10 ROWS ONLY
An Oracle programmer would write
SELECT column FROM table WHERE ROWNUM <= 10
In Sybase, you would set rowcount
SET rowcount 10
SELECT column FROM tablez
So obviously, what worked for postgres is FETCH FIRST instead of LIMIT.
Now, I'm good. I've used this sql in Adempiere code. :)
Just spreading this good documentations from FreeDB2.