Insert Into Table top of the rows in sql - sql

I need to insert a row at the top of my table. Is there a way to do that?
I am aware of "Order By" and that is not going to work. I need to change the actual table (Please do not suggest Order By. Most of the threads I found here only suggests that).
The column contains dates. The table is already ordered by desc when the data is input. Everyday, I need to add a row that has the current date and populate the rest of the data based on that. That row has to be on the top.
I have an ID Column. It is not a primary key. It goes 1, 2, 3...
The new date that is added should ideally be inserted on row 1 with it's ID being 1 (That's not absolutely vital though). I am okay with ID being all over the place but the dates have to be all descending.
Edit: I have added screenshots of the table before insert and after. The table has some 300 rows of data. As you can see, after the insert, the current date goes to the bottom. I want to change that.
Please help. Thanks

If you read the following response to a question asked previously, it will detail why you must use order by due to the order of the rows being returned never being guaranteed:
Default row order in SELECT query
Therefore just insert the data into the table, what SQL does with it in the background is irrelevant to you, what is relevant is the order in which you request them to be retrieved. Therefore Order By is the way to get the data out in the order that you want.
I'm struggling to understand what you mean by:
The table is already ordered by desc when the data is input.
It should be a two stage process:
1) Insert Data
INSERT INTO [TABLENAME] VALUES ([ID], [risk_date_day], [Risk1], [Risk2], [Risk3], [Risk4], [Risk5], [Grand Total], [1Per], [2Per], [3Per], [4Per], [5Per]);
--Naturally replace the values between square brackets with the correct values for data entry.
2) Retrieve Data
SELECT [ID], [risk_date_day], [Risk1], [Risk2], [Risk3], [Risk4], [Risk5], [Grand Total], [1Per], [2Per], [3Per], [4Per], [5Per]
FROM [TABLENAME]
ORDER BY [risk_date_day] DESC;
This will return the data with the latest date at the top.
However if you are in fact saying that the date you could enter on any particular day may not necessarily be the latest date, then this will not work. In which case I would suggest adding a field called DateOfEntry and use that field to do the Order By.

Related

How can I remove Null value from first column but keep the value of the 2nd and thirds columns

I am Omar, a new learner of SQL.
I have a large excel sheet that I want to analyze by SQL.
It has the following columns (Manufacturers, Products, sales)
the problem is, in the first column 'Manufacturers,' the manufacturer name has only been entered once per one manufacturer. while for the rest of the below rows, the cells are empty until the next manufacturer.
Please refer to the attached image for more understanding.
How can I remove these null values in my query results while keeping the values of the product column value?
thank you
The main problem you have is that SQL tables represent unordered sets. So, if you have only your specified columns, you cannot reconstruct the Excel format.
To solve this, you want to load the data into a table that has an identity or auto-incremented column, in order to preserve the insertion order. The exact details depend on the database. Let me call this column id.
Then you can "spread" the value where it is missing. One method is:
select t.*,
max(manufacturer) over (partition by manufacturer_grp) as imputed_manufacturer
from (select t.*,
count(manufacturer) over (order by id) as manufacturer_grp
from t
) t

SQL Insert Row In-between Two Rows

How do I insert a row between here?
Data is not intended to be stored SQL tables in any particular order, so it's not appropriate to insert a row at a particular position. You use an SQL SELECT query to extract the data you want and ORDER BY to specify how it is sorted. If you really want to have this row in a particular position, add an ID column as the primary key and number the ID column values in the sequence that you want. Whatever you are using to view your rows will order them by the ID column by default. However, you're going to experience this same problem every time you want to add a new row as SQL tables are not intended to be used in this way.

How to renumber a table column

I have a SQLite table sorted by column ID. But I need to sort it by another numerical field called RunTime.
CREATE TABLE Pass_2 AS
SELECT RunTime, PosLevel, PosX, PosY, Speed, ID
FROM Pass_1
The table Pass_2 looks good, but I need to renumber the ID column from 1 .. n without resorting the records.
It is a principle of SQL databases that the underlying tables have no natural or guaranteed order to their records. You must specify the order in which you want to see the records when SELECTing from a table using an ORDER BY clause.
You can obtain the records you want using SELECT * FROM your_table ORDER BY RunTime, and that is the correct and reliable way to do this in any SQL database.
If you want to attempt to get the records in Pass_2 to "be" in RunTime order, you can add the ORDER BY clause to the SELECT you use to create the table but remember: you are not guaranteed to get the records back in the order in which they were added to the table.
When might you get the records back in a different order? This is most likely to happen when your query can be answered using columns in a covering index -- in that case the records are more likely to be returned in index order than any "natural" order (but again, no guarantees with an ORDER BY clause).
If you want a new ID column starting at 1, then use the ROW_NUMBER() function. Instead of ID in your query use this ROW_NUMBER() OVER(ORDER BY Runtime) AS ID.... This will replace the old ID column with a freshly calculated column

How do I get row id of a row in sql server

I have one table CSBCA1_5_FPCIC_2012_EES207201222743, having two columns employee_id and employee_name
I have used following query
SELECT ROW_NUMBER() OVER (ORDER BY EMPLOYEE_ID) AS ID, EMPLOYEE_ID,EMPLOYEE_NAME
FROM CSBCA1_5_FPCIC_2012_EES207201222743
But, it returns the rows in ascending order of employee_id, but I need the rows in order they were inserted into the table.
SQL Server does not track the order of inserted rows, so there is no reliable way to get that information given your current table structure. Even if employee_id is an IDENTITY column, it is not 100% foolproof to rely on that for order of insertion (since you can fill gaps and even create duplicate ID values using SET IDENTITY_INSERT ON). If employee_id is an IDENTITY column and you are sure that rows aren't manually inserted out of order, you should be able to use this variation of your query to select the data in sequence, newest first:
SELECT
ROW_NUMBER() OVER (ORDER BY EMPLOYEE_ID DESC) AS ID,
EMPLOYEE_ID,
EMPLOYEE_NAME
FROM dbo.CSBCA1_5_FPCIC_2012_EES207201222743
ORDER BY ID;
You can make a change to your table to track this information for new rows, but you won't be able to derive it for your existing data (they will all me marked as inserted at the time you make this change).
ALTER TABLE dbo.CSBCA1_5_FPCIC_2012_EES207201222743
-- wow, who named this?
ADD CreatedDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;
Note that this may break existing code that just does INSERT INTO dbo.whatever SELECT/VALUES() - e.g. you may have to revisit your code and define a proper, explicit column list.
There is a pseudocolumn called %%physloc%% that shows the physical address of the row.
See Equivalent of Oracle's RowID in SQL Server
SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.

How to order the resulting query information being inserting into a table while leaving existing table records on top?

I am trying to insert values from a table into another existing table and have just the values I am inserting be sorted in descending order based on a specific column while leaving the existing records at the top of the table. How do I do that? I have tried to use an Order By statement but whether I use the column name of the table I'm pulling from or the destination table's column name I get an error. Also this is being run in VBA using DoCmd.RunSQL.
Here is my existing query:
INSERT INTO AllMetersAvgRSSI
(longitude,latitude,AvgRSSI)
Select
Prem.longitude, Prem.latitude,
DataByColl.[Avg RSSI]
From [Prem]
Left
Join DataByColl ON (Prem.meter_miu_id
= DataByColl.[MIU ID])
Order BY [AvgRSSI] desc
Final Result
I continued to fiddle with this and discovered than you can use an order by just like I have shown above to do exactly as I was trying to do. The problem I was apparently having was caused by the names of the column I wanted sorted being changed only from Avg RSSI to AvgRSSI. When I changed the destination table to have the same field name as the source table it orders the incoming information while leaving the existing information alone. I also did a test where I changed the name of the destination table to AverageRSSI and it worked the same way. So in the end it was the names of the fields being differed only by a space that was causing the problem. The final Query is:
INSERT INTO AllMetersAvgRSSI
(longitude,latitude,[Avg RSSI])
Select
Prem.longitude, Prem.latitude,
DataByColl.[Avg RSSI]
From [Prem]
Left
Join DataByColl ON (Prem.meter_miu_id
= DataByColl.[MIU ID])
Order BY [Avg RSSI] desc
Ordering in an INSERT makes no sense from a database standpoint. How the database puts the rows into a table depends on the underlying physical structure of the table, not the order in which they are inserted.
Maybe your application relies on an auto incrementing column being in a certain order which would then be dependent on the order of insertion, but if that's the case then I would say that you've made a mistake in your database design as there shouldn't be business logic designed around an auto incrementing column.
Remove the ORDER BY from your INSERT statement and if you need to retrieve rows in a particular order later then use an ORDER BY there.
Create a temp table, add the first result set in the desired order. Insert your new values into the table, query the table to return your new results with an order by into your temp table, select your temp table the results will be in the order you added them unless you do another order by.
Don't forget to drop your temp table after displaying the results.