Store data sorted into new table - sql

Good afternoon all,
I have two columns that I am trying to sort into a table, memberid and then total spend. When I run the following query:
Select Memberid, totalspend
from Table
order by totalspend;
my data returns the way that I expect it to. When I try and run:
Select MemberID, TotalSpend
into SampleTable
from Table
order by TotalSpend
SQL does not retain the sort.
The research that I have done so far suggests that the select into statement should work but for some reason it it not. I have tried converting the Totalspend to a float, int or varchar and still no luck.
I need my data sorted so that I can perform calculations on the table based on top x rows.
I am currently using SQL Server 2017.
Thank you,
Richard

SQL does not retain the sort.
This is soooo true. SQL tables represent unordered sets. No ordering. Get it?
That said, you can sort of impose order on the data. Here are two methods:
You can define a primary key. The data is physically sorted on the data pages (in SQL Server) based on the primary key.
You can define an identity column. In conjunction with order by, the identity column will capture the ordering.
Strictly speaking these have no effect on the result set from a query on the table. Instead, they are methods for storing the ordering in the data.
What is true about tables being unordered is also true about result sets. So if you run:
Select MemberID, TotalSpend
from SampleTable;
The result set is unordered. That means that even with a primary key or an identity column or both, SQL Server can return the rows in whatever order it so desires. It can even return the data in different orders on different runs.
Fixing this is easy. If you want the data in a particular order, simply add the following to your query:
order by TotalSpend
If you have an index on the column, then the sorting would normally use the index (unless the data is very small), so very little overhead would be incurred.

Related

SQL query does not return correct results

I am trying to filter between two dates on a SQL server from a PHP process.
This is the query:
select *
from webStocks
where FECHAMODIFICADO between '2020-06-03 17:16:02' and '2020-06-04 17:16:03'
ORDER BY webStocks.FECHAMODIFICADO DESC
This is the result:
The result is not what I want. In the table I have the following information and it should be the result.
What am I doing wrong in the query?:(
I'd try to make sure the date column actually contains 'timestamp' data type.
If it doesn't, the following code should fix it:
SELECT *
FROM webStocks
where CAST(FECHAMODIFICADO AS timestamp) BETWEEN '2020-06-03 17:16:02' AND '2020-06-04 17:16:03'
ORDER BY webStocks.FECHAMODIFICADO DESC
You can see more information about this kind of statements here.
(this solution is valid mostly for MySQL, but will probably work with either CAST or CONVERT statement with other SQL servers).
SQL tables represent unordered sets. That means that when you run a query with no ORDER BY, the results can be in any order -- and even in different orders on different runs.
In this case, you have an ORDER BY. But the column has duplicates. The same principle applies: rows with the same key value can be in any order -- and even in different orders on different runs.
So, you need to add a new key to capture the order that you want. It is not obvious from your data. But the results would at least be stable if you used:
ORDER BY webStocks.FECHAMODIFICADO DESC, CodeArticulo
It is also odd that your WHERE clause includes very specific times. But the data in these rows is all occurring at midnight. Usually midnight is not such an active time, if the time stamps represent human behavior.

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

ORDER BY query giving two different outputs

I have a student table with 8 records in columns [name, address, TotalFees].
Even though I execute two same ORDER BY queries on single table I get two different outputs. I have attached the screenshot below.
Same query on same table with different output:
The issue that you have is that the keys for the order by do not uniquely define each row. In particular, "khar" is repeated for most of the rows (your results suggest that you are using a case-insensitive collation).
In SQL databases, the sort is not stable. A stable sort is one that preserves the original ordering of values with the same key. Because the sort is not stable, the results -- for identical keys -- can come out in any order.
Why isn't the sort stable? That is easy in retrospect. SQL tables and result sets represent unordered sets. There is no initial ordering, so the sorting is not stable.
The normal way to address this is to include a unique id as the final key in the order by: order by address, id. With your data, though, it is unclear what the unique key is.
Combination of Address and Name won't produce duplicates so you can try this,
select *From student
order by address,name
select top 3 * From student
order by address,name

Unique sort order for postgres pagination

While trying to implement pagination from server side in postgres, i came across a point that while using limit and offset keywords you have to provide an ORDER BY clause on a unique column probably the primary key.
In my case i am using the UUID generation for Pkeys so I can't rely on a sequential order of increasing keys. ORDER BY pkey DESC - might not result in newer rows on top always.
So i resorted to using Created Date column - timestamp column which should be unique.
But my question comes what if the UI client wants to sort by some other column? in the event that it might not always be a unique column i resort to ORDER BY user_column, created_dt DESC so as to maintain predictable results for postgres pagination.
is this the right approach? i am not sure if i am going the right way. please advise.
I talked about this exact problem on an old blog post (in the context of using an ORM):
One last note about using sorting and paging in conjunction. A query
that implements paging can have odd results if the ORDER BY clause
does not include a field that represents an empirical sequence in the
data; sort order is not guaranteed beyond what is explicitly specified
in the ORDER BY clause in most (maybe all) database engines. An
example: if you have 100 orders that all occurred on the exact same
date, and you ask for the first page of this data sorted by this date,
then ask for the second page of data sorted the same way, it is
entirely possible that you will get some of the data duplicated across
both pages. So depending on the query and the distribution of data
that is “sortable,” it can be a good practice to always include a
unique field (like a primary key) as the final field in a sort clause
if you are implementing paging.
http://psandler.wordpress.com/2009/11/20/dynamic-search-objects-part-5sorting/
The strategy of using a column that uniquely identifies a record as pkey or insertion_date may not be possible in some cases.
I have an application where the user sets up his own grid query then it can simply put any column from multiple tables and perhaps none is a unique identifier.
In a case that can be useful you use rownum. You simply select the rownum and use his sort in over function. It would be something like:
select col1, col2, col3, row_number() over(order by col3) from tableX order by col3
It's important that over(order by *) match with order by *. Thus your paging will have consistent results every time.

Insert data into sqlserver 2000 database, the order change, why?

Insert 200 data througn for-loop into sqlserver 2000 database, the order change, why ?
When I use mysql, it doesn't have the matter.
i mean:
when you insert 2, then insert 3, then insert 1, in mysql you will see 2,3,1 like the order you insert. But in sqlsever2000 that may not.
The order in which rows are stored doesn't really matter. Actually SQL tables don't have any ordering. If order matters to you, you need to query using an ORDER BY clause.
There are no guarantees on the order of the results of a select statement, unless you add an ORDER BY clause. You might get the results back in the order of insertion, but it's not guaranteed.
If you have an index on the table, it might appear that your data is being ordered in a way that you're not expecting. Normally, you'll just have an identity column as your surrogate primary key, which means your inserted data will show up in "order" if you just do a select *, but if you have indexes on other columns the data might be ordered differently when you do select *.
You can control physical ordering by creating a clustered index on that columns. Only one clustered index is allowed per table. Cluster index make sure when you perform SELECT you will always get data in order which was defined when creating cluster index.