sqlsql-serversql-order-byunordered

SQL Server Insert on the last Row


I have a statement which Inserts a new row to the table in my database, but the new row is added on the first row of the table. I want to add a new row on the end of the table, how would I do this?

INSERT INTO myTable(IFACTUURREGELNUMMER, FACTUURNUMMER, REGELNUMMER, KOSTCODE, DOSSIERNUMMER, OMSCHRIJVING, RELATIE, PRIJS, AANTAL, BEDRAG, VALUTA, BTWCODE, BTWBEDRAG)
    VALUES (@INVOICELINENUMBERM, @INVOICENUMBER, @RULENUMBER, @COSTCODE, @CASENUMBER, @DESCRIPTION,@RELATION, @PRICE, @QUANTITY, @AMOUNT, @CURRENCIES, @BTWCODE, @BTWAMOUNT)

Solution

  • There is no first or last in a table.

    Anyway: You can use ORDER BY

    SELECT * FROM myTable ORDER BY IFACTUURREGELNUMMER DESC
    

    You can also have multiple expressions in the ORDER BY

    SELECT * FROM myTable ORDER BY IFACTUURREGELNUMMER DESC, INVOICENUMBER ASC
    

    Some Database Managment Systems (DMS) like Oracle or Postgres also allow you to order by NULLS:

    SELECT * FROM myTable ORDER BY IFACTUURREGELNUMMER DESC,
                                   INVOICENUMBER ASC NULLS LAST
    SELECT * FROM myTable ORDER BY IFACTUURREGELNUMMER DESC, 
                                   INVOICENUMBER ASC NULLS FIRST