mysqlsqlsequence

How do I create a sequence in MySQL?


I'm trying to create a sequence in MySQL (I'm very new to SQL as a whole). I'm using the following code, but it causes an error:

CREATE SEQUENCE ORDID INCREMENT BY 1 START WITH 622;

ORDID refers to a field in a table I'm using. How do I create the sequence properly?

Edit:

Allegedly, MySQL doesn't use sequences. I'm now using the following code, but this is causing errors too. How do I fix them?

CREATE TABLE ORD (
ORDID NUMERIC(4) NOT NULL AUTO_INCREMENT START WITH 622,
//Rest of table code

Edit:

I think I found a fix. For phpMyAdmin (which I was using) you can use the following code.

ALTER TABLE ORD AUTO_INCREMENT = 622;

I have no idea why it prefers this, but if anyone else needs help with this then here you go. :)


Solution

  • Check out this article. I believe it should help you get what you are wanting. If your table already exists, and it has data in it already, the error you are getting may be due to the auto_increment trying to assign a value that already exists for other records.

    In short, as others have already mentioned in comments, sequences, as they are thought of and handled in Oracle, do not exist in MySQL. However, you can likely use auto_increment to accomplish what you want.

    Without additional details on the specific error, it is difficult to provide more specific help.

    UPDATE

    CREATE TABLE ORD (
      ORDID INT NOT NULL AUTO_INCREMENT,
      //Rest of table code
      PRIMARY KEY (ordid)
    )
    AUTO_INCREMENT = 622;
    

    This link is also helpful for describing usage of auto_increment. Setting the AUTO_INCREMENT value appears to be a table option, and not something that is specified as a column attribute specifically.

    Also, per one of the links from above, you can alternatively set the auto increment start value via an alter to your table.

    ALTER TABLE ORD AUTO_INCREMENT = 622;
    

    UPDATE 2 Here is a link to a working sqlfiddle example, using auto increment.
    I hope this info helps.