How to reorder rows in a table SQL - sql

just wondering how to reorder rows in this table? I want to have 2015 through 2019 ASCENDING as happiness_rank increases, but 2015 automatically goes to the bottom of the table.
I have tried using
UPDATE table_name ORDER BY happiness_rank;
but that doesn't work, and similarly ALTER TABLE doesn't seem to work either. I know I can do it with SELECT but that doesn't save the table, and when I try to do UPDATE with SELECT and ORDER BY it doesn't work.
h_score
happiness_rank
economy_gdp_per_capita
2
1.52733
4
1.56497955322266
5
1.420
6
1.452
2015
1
1.39651

SELECT query is always used while reading table, so the info about how your tables is stored in SQL is pointless to you. If I am missing something, please tell me as even during export - you will use SELECT query.

You can do one of the following according to your needs:
If your table does not have any Indexes or Foreign Keys then simply use ALTER
ALTER TABLE tablename ORDER BY happiness_rank ASC;
However, it does not make sense to order them on insert. I wouldn't do this. (Not Recommended)
Add a new column with datatype integer which is sorted ASC and set it as the primary key. Usually, this is the column that has some unique ID and is an auto-generated sequence. (Recommended)

Related

Triggers update insert

It is possible to maintain a table of a database organized alphabetically
through triggers whenever you insert a new row like this:
INSERT INTO Software (name_software) VALUES ('linux');
name_software
1 windows
2 CAD
name_software
1 CAD
2 linux
3 windows
I am using the sybase central. I apologize if my post seems very inconsistent tried to explain in the simplest way.
Thank you.
The order of rows in a table (physically in the database) is decided by a clustered index. Put one on the name_software column and that's it.
But
1) you really don't "need" to sort the data in the table physically like this. It is a database... :) You can sort it by a query.
2) clustered index is most often on primary key and there can of course be only one on a table...
You want to re-order the entire table (and re-seed the identity column for that table) each time you insert (or update) a record?
Why can't you include ORDER BY ASC in your query when retrieving data instead?

Updating rows in order with SQL

I have a table with 4 columns. The first column is unique for each row, but it's a string (URL format).
I want to update my table, but instead of using "WHERE", I want to update the rows in order.
The first query will update the first row, the second query updates the second row and so on.
What's the SQL code for that? I'm using Sqlite.
Edit: My table schema
CREATE table (
url varchar(150),
views int(5),
clicks int(5)
)
Edit2: What I'm doing right now is a loop of SQL queries
update table set views = 5, click = 10 where url = "http://someurl.com";
There is around 4 million records in the database. It's taking around 16 seconds in my server to make the update. Since the loop update the row in order, so the first query update the first row; I'm thinking if updating the rows in order could be faster than using the WHERE clause which needs to browse 4 million rows.
You can't do what you want without using WHERE as this is the only way to select rows from a table for reading, updating or deleting. So you will want to use:
UPDATE table SET url = ... WHERE url = '<whatever>'
HOWEVER... SqlLite has an extra feature - the autogenerated column, ROWID. You can use this column in queries. You don't see this data by default, so if you want the data within it you need to explicitly request it, e.g:
SELECT ROWID, * FROM table
What this means is that you may be able to do what you want referencing this column directly:
UPDATE table SET url = ... WHERE ROWID = 1
you still need to use the WHERE clause, but this allows you to access the rows in insert order without doing anything else.
CAVEAT
ROWID effectively stores the INSERT order of the rows. If you delete rows from the table, the ROWIDs for remaining rows will NOT change - hence it is possible to have gaps in the ROWID sequence. This is by design and there is no workaround short of re-creating the table and re-populating the data.
PORTABILITY
Note that this only applies to SQLite - you may not be able to do the same thing with other SQL engines should you ever need to port this. It would be MUCH better to add an EXPLICIT auto-number column (aka an IDENTITY field) that you can use and manage.

Change the order of database columns

I want to change the order of column e.g. name is first column of my table and there are 10 other columns in table I want to insert a new column in 2nd position after name column.
How is this possible?
1 - It's not possible without rebuilding the table, as Martin rightly points out.
2 - It's a good practice anyways to specify what fields you want and in what order in your SELECT statements as n8wrl points out.
3 - If you really really need a fixed order on your fields, could create a view that selects the fields you want in the order you want.
Like the rows in the table, there is no meaning to the order of the columns. In fact, it is best to specify the order you want the columns in your select statements rather than using select *, so you can 'insert' new columns wherever you want just by writing your SELECT statements accordingly.
Its possible to change the order. In some instances it really matters. have a personal experience.
Anyway..this query works fine.
ALTER TABLE user MODIFY Name VARCHAR(150) AFTER address;
You can achieve this by following these steps:
remove all foreign keys and primary key of the original table.
rename the original table.
using CTAS, create the original table in the order you want.
drop the old table.
apply all constraints back to the original table.

select records from table in the order in which i inserted

consider a tale is as follows,
EmployeeId | Name | Phone_Number
Now, i insert 10 records... When i query them back, select * from myTable they are not selected in the order i inserted. I can obviously keep an autoincrement index and ORDER BY index. But i dont want to alter the table. How can i do this without altering the table?
Any ordering of result must be done using ORDER BY, if you don't use it the result will be returned in an undetermined order.
Unfortunately there is no way to do this.
Without an ORDER BY clause, there is no guaranteed order for the data to be returned in.
You would need to order by a column that indicates the inserted order, such as an IDENTITY field or a "Creation Date" field.
Isn't "EmployeeId" an auto-increment field? If it is, you can order by it to get data in order in which you inserted it.
There is no standard way to do this without adding an additional date, autoincrement index or some other counter to your table. Depending on your database there are some hacks you could do with SQL triggers to track this info in a separate table, but I suspect you don't want to do that (not all databases support them and they are not generally portable).

Change Large Number of Record Keys using Map Table

I have a set of records indexed by id numbers, I need to convert these record's indexes to a new id number. I have a two column table mapping the old numbers to the new numbers.
For example given these two tables, what would the update statement look like?
Given:
OLD_TO_NEW
oldid | newid
-----------------
1234 0987
7698 5645
... ...
and
id | data
----------------
1234 'yo'
7698 'hey'
... ...
Need:
id | data
----------------
0987 'yo'
5645 'hey'
... ...
This oracle so I have access to PL/SQL, I'm just trying to avoid it.
I'd have a unique index on OLD_TO_NEW.oldid and update on an inline view:
update (select id,
newid
from old_to_new,
my_table
where my_table.id = old_to_new.oldid)
set id = newid
UPDATE base_table SET id = (SELECT newid FROM old_to_new WHERE oldid = id)
That's how I would do it in MySQL and I think that's pretty standard.
Both of the update statements from Ramon and David Aldridge should work fine, but based on the number of records to be updated it may be faster to work with a temp table like this:
create table temp as (
select newid, data
from old_to_new join my_table on my_table.id = old_to_new.oldid);
Then truncate the old table and copy the temp table into the old table or drop the old table and rename the temp table. (Note: Add some extra statements to handle for records where you don't have new values.)
First make a database backup. I'd also personally make a table backup in a work database in case something goes wrong and you need to get back to the old way in a hurry.
The next concern is do you have related tables that will also need these ids? If no then you can update using an update statement. Write your update statment so that you can do a select and make sure that it will update properly. If you are doing a lot of records, you may want to do this in batches, say 1000 records at a time. ONe situation you may need to watch out for is if the values of the ids overlap a straight update might not work (you'll run into the unique index). In this case you need to add a column, populate it with the new values, then delte the old column and rename the new one. YOu will also need to script out all indexes, fks etc. becasue you will also need to rerun them.
Related tables becomes much more complicated, but the new column is the best way to go inthis case as well.
This is how I would do it in Microsoft SQL Server 2005. Haven't had access to an Oracle database in years so this may not work for Oracle.
UPDATE target_table
SET id = newid
FROM OLD_TO_NEW
WHERE target_table.id = OLD_TO_NEW.oldid;
You may want to index the OLD_TO_NEW.oldid so the update join can run efficiently.