Skip to content

Instantly share code, notes, and snippets.

@ApOgEE
Created December 29, 2023 09:53
Show Gist options
  • Save ApOgEE/0e3bf96f7b4779c390cac1a7c98494ec to your computer and use it in GitHub Desktop.
Save ApOgEE/0e3bf96f7b4779c390cac1a7c98494ec to your computer and use it in GitHub Desktop.
Cara Create Dan guna id_sequence dalam mysql atau mariadb

Guna ID Sequence dalam mysql atau mariadb

OK, selain dari Autoincrement, kita juga boleh guna sequential ID.

Cara nak create seq_contoh_saya yang bermula dengan nilai 13000 dan increment dia bertambah 1:

CREATE SEQUENCE IF NOT EXISTS seq_contoh_saya START WITH 13000 INCREMENT BY 1;

Lepas kita create sequence ni, kita boleh dapatkan nilai sequence dengan panggil:

SELECT NEXTVAL(seq_contoh_saya) id_seterusnya;

Setiap kali kita panggil SELECT NEXTVAL tu , id sequence tu akan auto increment.

Selain dari itu, kita juga boleh terus guna nextval ni ketika insert macam ni:

INSERT INTO tb_contoh (id, nama, umur) VALUES (NEXTVAL(seq_contoh_saya), 'Ahmad', '50');

Dengan cara ni, kita akan dapat id yang baru setiap kali insert.

@ApOgEE
Copy link
Author

ApOgEE commented Feb 13, 2024

Hanya untuk MariaDB kerana MySQL tiada SEQUENCE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment