-1

I created table and I inserted some values.

create table deposit1_groupc_tja05
(
  Account_id number(25),
  Account_type varchar(25),
  Balance number(9,2) not null,
  Transaction_amount number(9,2) not null,
  Transaction_Date varchar(50),
  Transaction_type varchar(25)
) 

Now I need to order them by Transaction_Date? How do I alter that?

ChrisM
  • 1,576
  • 6
  • 18
  • 29
Pravin
  • 47
  • 1
  • 7

3 Answers3

1

In MySQL's default storage engine, InnoDB, the table is always stored ordered by its primary key, which is the clustered index.

You don't declare a primary key in the example you show, so InnoDB will be ordered by an invisible primary key, so the storage order will be the order in which you inserted rows.

You can use ALTER TABLE to declare a primary key. This will reorder the storage by primary key. If you use Transaction_Date, a varchar, it will be ordered alphabetically, not by date. You should use a DATE data type if you want it ordered by date.

If you want a given query result set to be ordered by another column besides the primary key, then just use an ORDER BY clause. You can get a result set ordered differently from the table's storage order.

If you don't use an ORDER BY clause in your query, the result set has no guaranteed order in general (and per the SQL standard), and it's up to the implementation. In the case of InnoDB, there's still no guarantee it will always work this way, but practically, in current versions, a query with no ORDER BY returns rows in the order it reads them from the index (which may be the clustered index / primary key).

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
  • The implementation is not the abstraction. The OP doesn't say they want the *storage* ordered. And there is no guarantee that a result set for a query without ORDER BY is in any order regardless of storage order. – philipxy Aug 28 '17 at 10:29
  • @philipxy, Indeed, the OP's question is vague, and I guess we're not going to get any clarification from them. – Bill Karwin Aug 28 '17 at 14:15
0

There is no way to order the table in the way you are describing.

If you wanted to select the data in order then use the following

SELECT * 
FROM deposit1_groupc_tga05
ORDER BY Transaction_Date

You should also create the table with Transaction_Date as datetime

ChrisM
  • 1,576
  • 6
  • 18
  • 29
0

If you can't change the Transaction_Date column to datetime, then you need to cast the date in the query like this:

SELECT * FROM deposit1_groupc_tga05
ORDER BY STR_TO_DATE(Transaction_Date, '%c/%e/%Y %H:%i')

Or depending on the format the date is inserted, you need to change the format string.

Lamar
  • 1,761
  • 4
  • 24
  • 50