Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set auto increment of a primary key in the table in SQL DEVELOPER?

I have been trying to set a "w_no" to auto_increment like we do in MySQL but its been giving error.

How do we set auto increment in sql developer? Can we do by code or have to do something else?

Here is the code

CREATE TABLE ward (
      w_no      INT PRIMARY KEY AUTO_INCREMENT,
      wname     VARCHAR(30),
      w_loc     VARCHAR(30),
      phone_no  NUMERIC(10, 0),
      sno       INT
);

/*alter table ward ;*/  /*Can we do auto_increment using alter table here*/
like image 398
Serum Avatar asked Apr 14 '20 15:04

Serum


People also ask

Can we auto increment primary key?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

How can change primary key to auto increment in SQL Server?

If you're looking to add auto increment to an existing table by changing an existing int column to IDENTITY , SQL Server will fight you. You'll have to either: Add a new column all together with new your auto-incremented primary key, or. Drop your old int column and then add a new IDENTITY right after.

How do I add an auto increment to an existing table?

To add a new AUTO_INCREMENT integer column named c : ALTER TABLE t2 ADD c INT UNSIGNED NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (c); We indexed c (as a PRIMARY KEY ) because AUTO_INCREMENT columns must be indexed, and we declare c as NOT NULL because primary key columns cannot be NULL .


2 Answers

Don't use VARCHAR, use VARCHAR2

Also, if you want help, try the CREATE TABLE dialogs.

We'll create the table, PK, sequence, and trigger for you.

Or, if you're on 12c or higher version of database, you can use the IDENTITY clause.

enter image description here

Then click on the DDL page of the wizard, we'll show you the code, so you don't have to guess what the dialog is doing.

CREATE TABLE TABLE1 
(
  COLUMN1 INTEGER NOT NULL 
, COLUMN2 VARCHAR2(20) 
, COLUMN3 VARCHAR2(20) 
, CONSTRAINT TABLE1_PK PRIMARY KEY 
  (
    COLUMN1 
  )
  ENABLE 
);

CREATE SEQUENCE TABLE1_SEQ;

CREATE TRIGGER TABLE1_TRG 
BEFORE INSERT ON TABLE1 
FOR EACH ROW 
BEGIN
  <<COLUMN_SEQUENCES>>
  BEGIN
    IF INSERTING AND :NEW.COLUMN1 IS NULL THEN
      SELECT TABLE1_SEQ.NEXTVAL INTO :NEW.COLUMN1 FROM SYS.DUAL;
    END IF;
  END COLUMN_SEQUENCES;
END;
/
like image 111
thatjeffsmith Avatar answered Sep 17 '22 14:09

thatjeffsmith


I dont think Oracle introduced IDENTITY data types until 12c. In which case you should use a SEQUENCE object in place of the lack of IDENTITY type.

like image 24
alexherm Avatar answered Sep 17 '22 14:09

alexherm