SQL Server date column sorting dates automatically - sql

I have a table with a date column. I am inserting dates in that column using a DateTimePicker in C#.
Everything works fine. But I want the dates inserted in the table to be ordered. Currently when I add today's date in one row and then add yesterday's date or any past date, it gets added in the 2nd row ofc.
I want that to be added in 1st row instead. Before today's date, to make all the dates in order.
Is there any property of the date column I can use to ensure the dates order?

There is absolutely NO implicit order in SQL Server datatables! No index, no clustered index, no trick... A simple SELECT * FROM table may come back with sorted data - or not...
If you need your data sorted in a special way you must add an ORDER BY
Now one solution for your problem:
Create an updateable VIEW (https://msdn.microsoft.com/en-us/library/ms180800.aspx) on your table which is ordered like you want it. Than commuicate through this view...
Important is: Even when you specify SELECT TOP 100 PERCENT * FROM YourTable ORDER BY YourColumn the VIEW would not come back with sorted data...
The trick here is to introduce the sorting with a ROW_NUMBER()
I took for testing one of my tables. To make it more difficult I took one with an IDENTITY column.
And please keep in mind: The only sure order is the outermost ORDER BY
CREATE VIEW vwOneTableWithIdentityID
AS
SELECT ROW_NUMBER() OVER(ORDER BY SortColumn) AS OrderedInx
,* FROM OneTableWithIdentityID
GO
SELECT * FROM vwOneTableWithIdentityID;
GO
SET IDENTITY_INSERT OneTableWithIdentityID ON;
INSERT INTO vwOneTableWithIdentityID(OneTableWithIdentityIDID,AnotherID,SortColumn) VALUES(-5,1081,'aabc');
SET IDENTITY_INSERT OneTableWithIdentityID OFF;
GO
SELECT * FROM vwOneTableWithIdentityID
GO
DELETE FROM vwOneTableWithIdentityID WHERE OneTableWithIdentityIDID=-5;
GO
SELECT * FROM vwOneTableWithIdentityID;
GO
DROP VIEW vwOneTableWithIdentityID;

The physical order of a record is dependent on CLUSTER INDEX.
if you want DBMS order your data physically without
ORDER BY
clauses, create a clustered index on the field you want.

Related

Why doesn't the last inserted row in Firebird show up at the end of table

When I insert a row in a Firebird database, it doesn't show at the end of the table and it inserted before other row. Why is this?
Firebird doesn't use clustered tables, nor does it order data by insert. When you insert a row, Firebird adds the row to the first datapage of the table it can find that has sufficient space available. As a result, it may end up anywhere relative to other rows of the table.
If you want to enforce a specific order to the data you view, you need to add an order by clause to your select statement, specifying by which columns you want to order the data. Without an order by, the order of the result of a select is not deterministic, and may be the result of physical order in data pages, order of data in an index used to find rows, and other factors.

Different behaviour MSSQL2008 versus 2016 when inserting data

I came across an old script that in essence does the following:
CREATE TABLE #T (ColA VARCHAR (20), ID INT)
INSERT INTO #T VALUES ('BBBBBBBB', 1), ('AAAAAAA', 4), ('RRRRRR', 3)
CREATE TABLE #S (ColA VARCHAR (100), ID INT)
INSERT INTO #S
SELECT * FROM #T
ORDER BY ID -- odd to do an order by in an insert statement, but that's the code as it is...
SELECT * FROM #S
DROP TABLE #T, #S
First, I want to mention that I am aware of the fact that tables such as the ones I created here do not have an actual order, we just order the resultset if we want.
However, if you run the script above on a SQL version 2008, you will get the results ordered in the order that was specified in the insert statement. On a 2016 machine, this is not the case. There it returns the rows in the order they were created in the first place. Does anyone know what changes cause this different behaviour?
Thanks a lot!
As to your example - nothing is changed. The relation in the relation theory is represented in the SQL with a table. And the relation is not ordered. So, you are not allowed to defined how rows are ordered when they are materialized - and you should not care about this.
If you want to SELECT the data in a ordered way each time, you must specified unique order by criteria.
Also, in your example - you can SELECT the data one billion times and the data can be returned as "you inserted" it each time, but on the very next time you can get different results. The engine returns the data in the "best" way according to it when there is no order specified, but this can change anytime.
As you know - unless order by is specified, the database engine returns the rows in an arbitrary order - How this order is generated has to do with the internal parts of the database engine - the algorithm may change between versions, even between service packs, without any need for documentation since it's known to be arbitrary.
Please note that arbitrary is not the same as random - meaning you should not expect to get different row order each time you run the query - in fact, you will probably get the same row order every time until something changes - that might be a restart to the server, a rebuild of an index, another row added to the table, an index created or removed - I can't say because it's not documented anywhere.
Moreover, unless you have an Identity column in your table, the optimizer will simply ignore the order by clause in the insert...select statement, exactly because what you already wrote in your question - Database tables have no intrinsic order.
Order the result set of a query by the specified column list and,
optionally, limit the rows returned to a specified range. The order
in which rows are returned in a result set are not guaranteed unless
an ORDER BY clause is specified.
MSSQL Docs

Trigger to order a table by date (SQL)

I would like to know how to order a table by date(the oldest date first) after the insert of a new value in the same table using a trigger.
Thank you
RDBMSs (or at least the common ones) have no notion of ordering a table - a table is just a bunch of rows, which the database may return in any arbitrary order.
Your way to control this order is to explicitly declare what order you want them with an order by clause in your query:
SELECT *
FROM my_table
ORDER BY last_modification_time

SQLite: How to update order data in table?

I want to update a table to change the order of the data so it's ordered by some_column DESC.
I can do this by Selecting * and ordering by some_column DESC, and then inputting the data into a new table, but that's alot of hassle, so I'm wondering if there is another solution?
So what I want is to change this:
name|cost
John|50
Pete|75
Dojo|60
Neal|100
to
name|cost
Neal|100
Pete|75
Dojo|60
John|50
using the update statement. Is that possible?
You cannot rely on the way data is physically stored in the SQL table. The best you can do is create a VIEW on that table which is ordered the way you want it to be, and use that in your subsequent queries:
CREATE VIEW ordered_view AS
SELECT name, cost
FROM mytable
ORDER BY cost DESC;
SELECT name, cost FROM ordered_view;

Getting a specific number of rows from Database using RowNumber; Inconsistent results

Here is my SQL query:
select * from TABLE T where ROWNUM<=100
If i execute this and then re-execute this, I don't get the same result. Why?
Also, on a sybase system if i execute
set rowcount 100
select * from TABLE
even on re-execution i get the same result?
Can someone explain why? and provide possible solution for RowNum
Thanks
If you don't use ORDER BY in your query you get the results in natural order.
Natural order is whatever is fastest for the database at the moment.
A possible solution is to ORDER BY your primary key, if it's an INT
SELECT TOP 100 START AT 0 * FROM TABLE
ORDER BY TABLE.ID;
If your primary key is not a sequentially incrementing integer and you don't have another column to order by (such as a timestamp) you may need to create an extra column SORT_ORDER INT and increment in automatically on insert using either an Autoincrement column or a sequence and an insert trigger, depending on the database.
Make sure to create an index on that column to speed up the query.
You need to specify an ORDER BY. Queries without explicit ORDER BY clause make no guarantee about the order in which the rows are returned. And from this result set you take the first 100 rows. As the order in which the rows can be different every time, so can be your first 100 rows.
You need to use ORDER BY first, followed by ROWNUM. You will get inconsistent results if you don't follow this order.
select * from
(
select * from TABLE T ORDER BY rowid
) where ROWNUM<=100