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.
Related
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)
I want to swap columns within Visual Fox Pro 9 in table_1 before inserting its rows into table_2 so as to avoid data losses caused by datatype variations. I tried these two options based on other solutions on stackoverflow, but I get syntax error messages for both command inputs. The name field is of datatype = character(5)and it needs to be after the subdir field.
ALTER table "f:\csp" modify COLUMN name character(5) after subdir
ALTER table "f:\csp" change COLUMN name name character(5) after subdir
I attempted these commands based on solutions here:
How to move columns in a MySQL table?
You never need to change the column order, and you never should rely on column order to do something.
For inserting into another table from this one you could simply select the columns in the order you desired (and their column names do not even need to be the same in the case of "insert ... select ... "). ie:
insert into table_2 (subdir, name) ;
select subdir, name from table_1
Another way is to use the xBase commands like:
select table_2
append from table_1
In the case of latter, VFP would do the match on column names.
All in all, relying on column ordering is dangerous. If you really want to do that, then you can still do, in a number of ways. One of them is to select all data into a temp table, recreate the table in the order you want and fill back from temp (might not be as easy as it sounds if there are existing dependencies such as referential integrity - also you need to recreate the indexes).
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
select bottom rows in natural order
People imagine that i have this table :
persons
columns of the table are NAME and ID
and i insert this
insert into persons values ('name','id');
insert into persons values ('John','1');
insert into persons values ('Jack','3');
insert into persons values ('Alice','2');
How can i select this information order by the insertion? My query would like :
NAME ID
name id
John 1
Jack 3
Alice 2
Without indexs (autoincrements), it's possible?
I'm pretty sure its not. From my knowldege sql data order is not sequetional with respect to insertion. The only idea I have is along with each insertion have a timestamp and sort by that time stamp
This is not possible without adding a column or table containing a timestamp. You could add a timestamp column or create another table containing IDs and a timestamp and insert in to that at the same time.
You cannot have any assumptions about how the DBMS will store data and retrieve them without specifying order by clause. I.e. PostgreSQL uses MVCC and if you update any row, physically a new copy of a row will be created at the end of a table datafile. Using a plain select causes pg to use sequence scan scenario - it means that the last updated row will be returned as the last one.
I have to agree with the other answers, Without a specific field/column todo this... well its a unreliable way... While i have not actually ever had a table without an index before i think..
you will need something to index it by, You can go with many other approaches and methods... For example, you use some form of concat/join of strings and then split/separate the query results later.
--EDIT--
For what reason do you wish not to use these methods? time/autoinc
Without storing some sort of order information during insert, the database does not automatically keep track of every record ever inserted and their order (this is probably a good thing ;) ). Autoincrement cannot be avoided... even with timestamp, they can hold same value.
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).
I want to run the following sql command:
ALTER TABLE `my_table` ADD UNIQUE (
`ref_id` ,
`type`
);
The problem is that some of the data in the table would make this invalid, therefore altering the table fails.
Is there a clever way in MySQL to delete the duplicate rows?
SQL can, at best, handle this arbitrarily. To put it another way: this is your problem.
You have data that currently isn't unique. You want to make it unique. You need to decide how to handle the duplicates.
There are a variety of ways of handling this:
Modifying or deleting duplicate rows by hand if the numbers are sufficiently small;
Running statements to update or delete duplicate that meet certain criteria to get to a point where the exceptions can be dealt with on an individual basis;
Copying the data to a temporary table, emptying the original and using queries to repopulate the table; and
so on.
Note: these all require user intervention.
You could of course just copy the table to a temporary table, empty the original and copy in the rows just ignoring those that fail but I expect that won't give you the results that you really want.
if you don't care which row gets deleted, use IGNORE:
ALTER IGNORE TABLE `my_table` ADD UNIQUE (
`ref_id` ,
`type`
);
What you can do is add a temporary identity column to your table. With that you can write query to identify and delete the duplicates (you can modify the query little bit to make sure only one copy from the set of duplicate rows are retained).
Once this is done, drop the temporary column and add unique constraint to your original column.
Hope this helps.
What I've done in the past is export the unique set of data, drop the table, recreate it with the unique columns and import the data.
It is often faster than trying to figure out how to delete the duplicate data.
There is a good KB article that provides a step-by-step approach to finding and removing rows that have duplicate values. It provides two approaches - a one-off approach for finding and removing a single row and a broader solution to solving this when many rows are involved.
http://support.microsoft.com/kb/139444
Here is a snippet I used to delete duplicate rows in one of the tables
BEGIN TRANSACTION
Select *,
rank() over (Partition by PolicyId, PlanSeqNum, BaseProductSeqNum,
CoInsrTypeCd, SupplierTypeSeqNum
order by CoInsrAmt desc) as MyRank
into #tmpTable
from PlanCoInsr
select distinct PolicyId,PlanSeqNum,BaseProductSeqNum,
SupplierTypeSeqNum, CoInsrTypeCd, CoInsrAmt
into #tmpTable2
from #tmpTable where MyRank=1
truncate table PlanCoInsr
insert into PlanCoInsr
select * from #tmpTable2
drop table #tmpTable
drop table #tmpTable2
COMMIT
This worked for me:
ALTER TABLE table_name ADD UNIQUE KEY field_name (field_name)
You will have to find some other field that is unique because deleting on ref_id and type alone will delete them all.
To get the duplicates:
select ref_id, type from my_table group by ref_id, type having count(*)>1
Xarpb has some clever tricks (maybe too clever): http://www.xaprb.com/blog/2007/02/06/how-to-delete-duplicate-rows-with-sql-part-2/