Home CRUD Operations
Post
Cancel

CRUD Operations

  • CRUD OPERATION

    • CREATE
      • Databases, Tables or Views
      • Users, prermissions and security groups
    • READ
      • Example: SELECT statements
    • UPDATE
      • Amend existing database records
    • DELETE
  • CREATE

    • CREATE TABLE unique table name
    • (column name, data type, size)
    1
    2
    3
    4
    5
    
          CREATE TABLE test_table(
              test_date date,
              test_name, varchar(20),
              test_int int
          )
    

    A few considerations when creating a table

    • Table and column names
    • Type of data each column will store
    • Size or amount of data stored in the column
  • INSERT

    Syntax:

    1
    2
    3
    
          INSERT INTO table_name(col1, col2, col3)
          VALUES
              ('value1', 'value2', value3)
    
  • INSERT SELECT

    Syntax:

    1
    2
    3
    4
    5
    6
    7
    8
    
      INSERT INTO table_name (col1, col2, col3)
      SELECT
          column1, 
          column2, 
          column3
      FROM other_table
      WHERE
          -- conditions apply
    

    Note:

    • Don’t Use SELECT *
    • Be specific in case table structure changes
  • UPDATE

    Syntax:

    1
    2
    3
    4
    
      UPDATE table
      SET column = value,
      WHERE 
          -- Condition(s);
    

    Don’t forget the WHERE clause!

    1
    2
    3
    4
    5
    6
    
      UPDATE table
      SET
          column1 = value1,
          column2 = value2
      WHERE
          -- Coondition(s);
    
  • DELETE

    Syntax:

    1
    2
    3
    4
    
      DELETE 
      FROM table
      WHERE
          -- Conditions
    
  • TRUNCATE

    It clears the entire table at once

    1
    
      TRUNCATE TABLE table_name
    
  • Declaring Variables

    We declare variables to avoid repition

    1
    2
    
          DECLARE @test_int INT
          DECLARE @my_artist VARCHAR(100)
    
  • Using SET to set valuies to variables

    1
    2
    
          SET @test_int = 5
          SET @my_artist = 'AC/CD"
    

    Using variables to select columns from artist table where name is set to the value stored in @my_artist

    1
    2
    3
    
          SELECT *
          FROM artist
          WHERE name = @my_artist;
    
  • Temporary Tables

    1
    2
    3
    4
    5
    6
    7
    
          SELECT
              col1, 
              col2, 
              col3 INTO #my_temp_table
          FROM my_existing_table
          WHERE
              -- Conditions
    

    #my_temp_table exists until connection or session ends

    1
    2
    
      -- Remove table manually
      DROP TABLE #my_temp_table
    
This post is licensed under CC BY 4.0 by the author.