Oracle

Chapter 6 - DML (Data Manipulation Language)

INSERT

In Oracle, the INSERT statement is part of the Data Manipulation Language (DML) and is used to add new rows of data into a table. This is a fundamental operation for modifying the data stored in a database. An INSERT operation requires specifying the table name, the columns that will receive values, and the actual values to be inserted.

Here’s a breakdown of how INSERT works in Oracle:

  1. Basic Syntax

    • You can insert data into all columns or specific columns.
    • If inserting into all columns, ensure the values match the column order.
  2. Inserting into All Columns

    INSERT INTO authors VALUES (1, 'George Orwell', 'george.orwell@example.com');
    
    • This assumes the authors table has three columns: author_id, name, and email.
  3. Inserting into Specific Columns

    INSERT INTO books (book_id, title, author_id)
    VALUES (1, '1984', 1);
    
    • Here, the INSERT specifies only three columns of the books table and inserts values for them.

Steps for Using the INSERT Statement

  1. Identify the Table

    • The first step is determining which table you want to insert data into.
    • For example, you might want to add a new record to the membership table.
  2. Specify the Columns

    • You can insert data into all columns or specific columns.
      • If you omit columns, ensure that they either have default values or allow NULL.
    • Example:
      INSERT INTO membership (member_id, member_name, join_date)
      VALUES (101, 'John Doe', TO_DATE('2024-09-18', 'YYYY-MM-DD'));
      
  3. Provide the Values

    • Values must be provided for all specified columns.
      • The order of values must match the column order.
      • The data types of values must be compatible with the column data types.
    • For example:
      • If a column is of type VARCHAR, the value must be a string.
      • If a column is of type DATE, you may need to use a date conversion function like TO_DATE().
  4. Committing the Transaction

    • Once the data is inserted, you typically need to commit the transaction.
      COMMIT;
      
    • This makes the changes permanent.
  5. Error Handling

    • Ensure that all required columns are included.
      • Missing values or incorrect data types can result in an error.
    • If an error occurs, use ROLLBACK to undo the changes.

Example: Adding a New Rental Record

INSERT INTO rentals (rental_id, book_id, member_id, rental_date, return_date)
VALUES (301, 1, 101, TO_DATE('2024-09-18', 'YYYY-MM-DD'), NULL);
  • This inserts a new rental where book_id = 1, member_id = 101, and the rental date is 2024-09-18.
  • The return_date is left as NULL since the book hasn’t been returned yet.

By following these steps, beginners can effectively use the INSERT statement to add new data into Oracle tables.

Tansy SQL Course | INSERT | Chapter 6 | Lesson 1 - Video Thumbnail
Comments(0 comments)

Comments Not Found