Order by while inserting data into temp table.is not working - sql

SELECT S.ColumnName,L.ColumnName ...
INTO #Tempdata
FROM [dbo].[M] M
LEFT JOIN [dbo].[S] S ON S.PrimaryKey=M.FKey
LEFT JOIN [dbo].[L] L ON S.FK=L.PK
ORDER BY S.ColumnName

SQL tables represent unordered sets. Period.
If you want to select the data in order, you need to use:
order by columnName
in the query used for the selecting the data.
SQL Server, though, does respect an ORDER BY in an INSERT in one important way. If you have an identity column, then the identity will follow the ORDER BY. This can be convenient. But to get ordered results (consistently) you need ORDER BY in the SELECT query.

Especially in tempdb, which is often stores data with multiple files, the rows inserted are splitted across the differents files. Retrieving the data using multiple threads (one thread by file to go faster) will give any combination of mingled subsets and give an impression of hasardous order of the rows.
As it has been said, there is no ways to have an ordered storage of rows in a table, and it is the reason why SQL have a ORDER BY clause !

Related

Related rows ordering when using JOIN without ORDER BY

Let's say we have two tables:
user:
id,name
1,bob
2,alice
user_group:
id,user_id,group
1,1,g1
2,1,g2
3,2,g2
4,2,g3
We don't have guarantees that on each execution of SELECT * FROM user without ORDER BY result set will have the same order. But what about related rows in joins?
For example,
SELECT user.name, user_group.group FROM user INNER JOIN user_group ON (user.id = user_group.user_id);. Will the related(joined) rows be adjacent in the result set(take PostgreSQL for ex.)? By that I imply:
bob,g1
bob,g2
alice,g2
alice,g3
OR
alice,g3
alice,g2
bob,g2
bob,g1
and NOT this:
bob,g1
alice,g2
bob,g2
alice,g3
The order of users doesn't matter, the order of groups within each user too
It is a fundamental rule in SQL that you can never rely on the ordering of a result set unless you add an ORDER BY. If you have no ORDER BY, the ordering of the result set can, among others, depend on
the order in which PostgreSQL reads the individual tables – it could be in index order or in sequential order, and even with a sequential scan you don't always get the same order (unless you disable synchronize_seqscans)
the join strategy chosen (nested loop, hash join or merge join)
the number of rows returned by the query (if you use a cursor, PostgreSQL optimizes the query so that the first rows can be returned quickly)
That said, with your specific example and PostgreSQL as database, I think that all join strategies will not return the result set in the order you describe as undesirable. But I wouldn't rely on that: often, the optimizer finds a surprising way to process a query.
The desire to save yourself an ORDER BY often comes from a wish to optimize processing speed. But correctness is more important than speed, and PostgreSQL can often find a way to return the result in the desired order without having to sort explicitly.

Use a specific column for ordering table

I have a table for categories on my posts database, I wanna make a specific order for them, so when I'm trying to insert a new record, It's not necessary to be stored at the end of table.
What is the best way to do that?
The order of rows and columns is immaterial to the DBMS. Rows are not stored at the end and select without order by does not guarantee the order of rows. Even if data can be stored ordered in the files, due to parallel execution, result is not ordered.
If you want to get ordered dataset, use ORDER BY in your query.
If you want ot order the extracted data then you should use the order by clause
SELECT Name, Order
FROM MyTalbe
WHERE ...
ORDER BY Order
Col1 being your column with the number from 1 to N

Get data like in database order without sorting it

I have a table which has ShipCountry, ShipCity and Freight column in SQL database. I tried to retrieve data from that table by using the below query.
Select ShipCountry from CountryDetails Group by ShipCountry
If i run this query i am getting results in Ascending order. Instead of this i need data in database order. How to achieve this through SQL query?
Note: If i run the below query, it will return the data in Database order. I am getting sorted data when i added group by clause in my query.
Select ShipCountry from CountryDetails
The use of group by for ordering is improper .. (group by is for aggregation function as min, max or count)
if you need a specific order use order by instead
Select ShipCountry from CountryDetails Order by ShipCountry
otherwise if want not order use simply
Select ShipCountry from CountryDetails
Remember that the values store in db have not a proper order ..and are selected in the sequence used for retrive the data.
Each time you need an order you must esplicitally use order by
for avoid "redundant values" .. use distinct and not group by eg:
Select distinct ShipCountry from CountryDetails
As already has been stated, what you describe might lead to unexpected results fro your end users.
Let's assume you have a table without any indexes or keys (A so-called heap). A heap pretty much can be compared to a phone book (yeah, I've been around for a while) consisting of hundreds of pages, on which information is randomly ordered. A heap is exactly that; A lot of randomly ordered data. Whenever you query from such a table, the query analyzer will do its very best to figure out what the fastest way to deliver the data is.
Such decisions from the query analyzer are guided by statistics; a collection of metrics about the data and the distribution thereof. SQL Server uses these statistics to figure out the cardinality (the uniqueness of values), and thus pick the fastest way to return data.
When you simply issue a SELECT * FROM myTable on a heap, those statistics will determine the order in which your data is returned. However, this also means that over time, the statistics will change, as more data flows into the table. This has the effect that the sort order of your data today is not necessarily the sort order in which the data is returned tomorrow, or even five minutes from now.
If that is fine with your end users, then a SELECT * FROM myTable is the right solution for you. But, if you absolutely need to have the data returned in a certain order, you should always implement an ORDER BY clause.
if you want to have the same database order in most cases if you have sorted by primary key it will be the same without ordering as you say:
here the id is the primary key, and if you can not use the primary key add an identity column and use it:
id name
1 elly
2 ahmad
3 joseph
4 omar

Postgresql order of records

I have a set of records in a table. I get records via select without any order statements just select * from table so there isn't any obvious order.
Will the order of records differs after updating some records?
There is no internal order in a Postgres database table (and this is also the case with most other RDBMS). The only order which will exist at selection time is the one you specify using an ORDER BY clause. So, the answer to your question is that you should always rely on ORDER BY if you want a consistent, reproducible order in your result set.

SELECT DISTINCT without ordering the rows

I'm doing the following query:
SELECT DISTINCT column1, colum2 FROM table.... WHERE....
but I don't want that the result returned were in order.
How can I avoid that sql sort this rows?
They are not getting sort per se, they are just returning using whatever index is on your table or just scanning the whole table. If you want them sort randomly, then you need to explicitely say so on your query:
SELECT *
FROM (SELECT DISTINCT column1, colum2
FROM table....
WHERE....) A
ORDER BY NEWID()
FIDDLE DEMO
ORDER BY isn't required for SELECT DISTINCT (or anything else)...What kind of ordering are you seeing? It may just be that the data was ordered when it was entered into the system.
The select distinct has to identify duplicate rows. There are basically two ways to do this. One is to sort the data (which may be done implicitly using an index). Then duplicate rows appear next to each other. The other is to build a hash table. Duplicate rows appear in the same hash buckets.
For your query, SQL Server is choosing to sort the data. It happens to look like the data is being ordered. On a multi-threaded system, then the data might look sorted, but when you scroll through it, you'll find that the sorting is in chunks (as data is returned from each thread).