Oracle

Chapter 5 - DDL (Data Definition Language)

ALTER TABLE

The ALTER TABLE command in Oracle allows you to modify the structure of an existing table without having to recreate it. This is useful when you need to make adjustments to your table schema, such as adding, modifying, or deleting columns, as well as adding constraints. For beginners, understanding how to use the ALTER TABLE command is essential for maintaining and evolving a database structure. Below are examples of how to use the ALTER TABLE command with tables designed for a library system.

  1. Adding a New Column to the author Table

    • Suppose you want to add a new column middle_name to the author table.
    ALTER TABLE author
    ADD middle_name VARCHAR2(50);
    
  2. Modifying the Data Type of a Column in the books Table

    • You can modify the length of the title column in the books table if you realize that more characters are needed.
    ALTER TABLE books
    MODIFY title VARCHAR2(150);
    
  3. Adding a New Foreign Key Constraint to the membership Table

    • If you want to ensure that each membership is associated with a specific library, you can add a foreign key linking the membership table to the library table.
    ALTER TABLE membership
    ADD library_id NUMBER;
    
    ALTER TABLE membership
    ADD CONSTRAINT fk_library
    FOREIGN KEY (library_id) REFERENCES library(library_id);
    
  4. Dropping a Column from the rentals Table

    • If the return_date column is no longer needed in the rentals table, you can remove it.
    ALTER TABLE rentals
    DROP COLUMN return_date;
    
  5. Renaming a Column in the library Table

    • To rename a column, such as changing branch_name to library_name, use the ALTER TABLE command.
    ALTER TABLE library
    RENAME COLUMN branch_name TO library_name;
    
  6. Adding a NOT NULL Constraint to the books Table

    • You may want to enforce that the title column in the books table cannot have NULL values.
    ALTER TABLE books
    MODIFY title VARCHAR2(150) NOT NULL;
    

Additional Notes:

  • The ADD clause is used to add a new column or constraint.
  • The MODIFY clause changes the definition of an existing column.
  • The DROP clause allows you to remove a column from the table.
  • Constraints like FOREIGN KEY and NOT NULL can be added or modified after a table is created.

Using the ALTER TABLE command gives flexibility in managing your database structure as the needs of your application change.

Tansy SQL Course | ALTER TABLE| Chapter 5 | Lesson 2 - Video Thumbnail
Comments(0 comments)

Comments Not Found