Pratelan Tabel Alter SQL

Pranyatan ALTER TABLE ing SQL digunakake kanggo nambah, ngowahi utawa mbusak kolom tabel.

Kita uga bisa nggunakake pratelan ALTER TABLE kanggo nambah utawa nyelehake macem-macem watesan tabel.



SQL ALTER TABLE - Tambah Kolom Anyar

Kanggo nambah kolom anyar menyang tabel sing ana, kita nggunakake sintaks:


ALTER TABLE table_name ADD column_name datatype;

Tuladhane

Kode ing ngisor iki nambah kolom 'Start_Date' menyang tabel 'Karyawan':

ALTER TABLE Employees ADD Start_Date date;

SQL ALTER TABLE - Copot Column

Kanggo mbusak kolom saka tabel sing ana, kita nggunakake sintaks:


ALTER TABLE table_name DROP COLUMN column_name;

Tuladhane

Kode ing ngisor iki mbusak kolom 'Start_Date' saka tabel 'Karyawan':



ALTER TABLE Employees DROP COLUMN Start_Date;

SQL ALTER TABLE - Ubah kolom

Kita bisa nggunakake ALTER TABLE pratelan kanggo ngowahi datatype kolom nggunakake sintaksis:

ALTER TABLE table_name MODIFY column_name datatype;

Tuladhane

Kode ing ngisor iki ngganti datatype kolom 'Start_Date' saka date menyang year:

ALTER TABLE Employees MODIFY Start_Date year;

SQL ALTER TABLE - Database Demo

Umpama kita duwe tabel sing diarani 'Karyawan' kanthi kolom ing ngisor iki:


+------------+-----------+----------+ | EmployeeID | FirstName | LastName | +------------+-----------+----------+ | 1

| Mark
| Otto
| | 2

| Jacob
| Thornton | | 3

| Su
| Bird
| | 4

| Sam
| Burger | +------------+-----------+----------+

Tambah Column

Saiki kita pengin nambah tabel 'Karyawan' lan nambah kolom anyar sing diarani 'Start_Date'

ALTER TABLE Employees ADD Start_Date date;

Output:

+------------+-----------+----------+------------+ | EmployeeID | FirstName | LastName | Start_Date | +------------+-----------+----------+------------+ | 1

| Mark
| Otto
|

| | 2

| Jacob
| Thornton |

| | 3

| Su
| Bird
|

| | 4

| Sam
| Burger |

| +------------+-----------+----------+------------+

Ngowahi Kolom

Sabanjure, kita pengin ngowahi datatype kolom 'Start_Date' saka date menyang year:

ALTER TABLE Employees MODIFY Start_Date year;

Busak Kolom

Kita pengin mbusak kolom 'Start_Date' saka tabel 'Karyawan'. Kita nggunakake:


ALTER TABLE Employees DROP COLUMN Start_Date;

Output:

+------------+-----------+----------+ | EmployeeID | FirstName | LastName | +------------+-----------+----------+ | 1

| Mark
| Otto
| | 2

| Jacob
| Thornton | | 3

| Su
| Bird
| | 4

| Sam
| Burger | +------------+-----------+----------+