SQL Syntax


  1. Create Table
    
    CREATE TABLE table1 (   
        id INT PRIMARY KEY,
        name VARCHAR(20),
    );
        
    
    CREATE TABLE table1 (   
        id INT,
        name VARCHAR(20),
        PRIMARY KEY(id),
    );
        

    Other Constraints: NOT NULL,UNIQUE,AUTO_INCREMENT, DEFAULT 'sth'.

  2. Access column format
  3. DESCRIBE table1;

  4. Delete table
  5. DROP TABLE table1;

  6. Add column
  7. ALTER TABLE table1 ADD discount DECIMAL(3,2);

    3 digits, 2 decimal places.

  8. Drop column
  9. ALTER TABLE table1 DROP COLUMN discount;

  10. Insert data
  11. 
    INSERT INTO table1 VALUES(1,'Jack');
    INSERT INTO table1(id) VALUES(2);
    INSERT INTO table1(name) VALUES('Leo'); #AUTO_INCREMENT
        

    Notes: Cannot insert duplicate values.

  12. Update rows
  13. 
    UPDATE table1;
    SET name = 'Kim' # SET VAL1 = val1, VAL2 = val2, ...
    WHERE id = 2; # OR, AND 
        
  14. Delete rows
  15. 
    DELETE FROM table1
    WHERE id=1 AND name='Leo';
        
  16. Queries
    1. Basic
    2. 
      SELECT * FROM table1;
      SELECT id,name FROM table1;
      SELECT table1.id,table1.name FROM table1;
          
    3. ARRANGE IN ORDER
    4. 
      ORDER BY name;
      ORDER BY id,name ASC; # order by id, then by name
      ORDER BY name DESC;
          
    5. Limit the number of rows
    6. 
      LIMIT 10;
          
    7. Select columns with specific values
      
      WHERE id > 0  AND name = 'Jack';
      WHERE id > 0  AND name <> 'Jack';
      WHERE id > 0  AND name IN ('Jack','Leo');
          

    References