Question

i am new to SQL.

I have used "order by" to sort two large tables on SQL, netezza of IBM.

The table is:

 col1  INT
 col2  INT
 col3  INT
 col4  DOUBLE PRECISION

 INSERT INTO mytable
 SELECT * 
 FROM table1 AS t1
 ORDER BY t1.col1 , t1.col2, t1.col3, t1.col4 ASC

After sorting, I check the top 100 rows:

SELECT *
FROM mytable
LIMIT 100;

But, I got different results everytime when i run the SQL query for top 100 rows.

When I export the table to a txt file, the same thing.

Why ?

Thanks !

Was it helpful?

Solution

The order in which you insert data into the table is meaningless. Running a query has absolutely no guarantee on the order rows are returned, unless you explicitly specify it using the order by clause. Since there's no guarantee on the order of rows, there's no guarantee what the "top 100" are, and hence you may very well get different results each time you run the query.

If you do specify the order in your query, however, you should get consistent results (assuming that there's only one possible outcome for the top 100 rows, and not, e.g., 200 rows which any 100 of which could be considered valid results):

SELECT   *
FROM     mytable
ORDER BY col1, col2, col3, col4 ASC
LIMIT    100;

OTHER TIPS

The sequence is not guaranteed, although it may match the order in which the data was inserted. If you need it in a particular sequence, use ORDER BY.

you need to use order by to the select query and its not mandatory to write ASC explicitly after order by clause as sorting by default will in ascending order

SELECT *
FROM mytable t1
ORDER BY t1.col1 , t1.col2, t1.col3, t1.col4 
LIMIT 100;

You need to apply an order by to your Select statement

The ORDER BY belongs on the SELECT query too:

SELECT *
FROM mytable t1
ORDER BY t1.col1 , t1.col2, t1.col3, t1.col4 ASC
LIMIT 100;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top