[MySQL] ์ œ์•ฝ์กฐ๊ฑด (Constraint) - NOT NULL, DEFAULT, PRIMARY KEY, AUTO_INCREMENT / CRUD


Constraint (์ œ์•ฝ์กฐ๊ฑด)


  1. NOT NULL

  2. UNIQUE

  3. PRIMARY KEY

  4. FOREIGN KEY

  5. DEFAULT


Null / Not Null

  • Null = N / Not Null = NN

  • Null์€ ๊ณต๋ฐฑ์ด ์•„๋‹Œ โ€˜๋ฏธ์ž…๋ ฅ ์ƒํƒœโ€™๋ฅผ ์˜๋ฏธ

  • Not Null ์„ค์ •

    • CREATE TABLE table_name
          (
              column_name data_type NOT NULL
          );
      
  • null๊ฐ’ ์ž…๋ ฅ ๋ฐฉ๋ฒ•

    • ex)

        CREATE TABLE people(
            num     int,
            name    char(10)
        );
      
        INSERT INTO people (num)
        VALUES
        (1);
      
        # or
              
        INSERT INTO people (num, name)
        VALUES
        (2, null);
      


Default

  • ๋ฏธ์ž…๋ ฅ ์ƒํƒœ์ผ ๊ฒฝ์šฐ ๋ฏธ๋ฆฌ ์ง€์ •ํ•œ ๊ธฐ๋ณธ๊ฐ’์ด ์ž…๋ ฅ๋จ

  • ๊ธฐ๋ณธ๊ฐ’ ์„ค์ •

    • CREATE TABLE table_name
          (
              column_name data_type DEFAULT 'default_value'
          );
      


Primary Key

  • ํ”„๋ผ์ด๋จธ๋ฆฌํ‚ค(=๊ธฐ๋ณธํ‚ค) ์„ค์ •

    • CREATE TABLE table_name
          (
              column_name data_type PRIMARY KEY
          );
      
      OR
      
      CREATE TABLE table_name
          (
              column_name data_type,
              PRIMARY KEY(column_name)
          );
      
    • Not Null : ๋ฏธ์ž…๋ ฅ ์ƒํƒœ์˜ ๊ฐ’ ํ—ˆ์šฉํ•˜์ง€ ์•Š์Œ

    • ์œ ์ผ์„ฑ : ์ค‘๋ณต๊ฐ’ ๋ถˆ๊ฐ€๋Šฅ, ์ค‘๋ณต๋˜๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ปฌ๋Ÿผ์— ์‚ฌ์šฉ

    • ์˜์†์„ฑ : ๋ฐ์ดํ„ฐ๊ฐ€ ์˜์†์„ฑ์„ ๊ฐ€์ ธ์•ผ ํ•จ

    • PK๋Š” ํ•˜๋‚˜์˜ ํ…Œ์ด๋ธ” ๋‹น ํ•œ ๊ฐœ๋งŒ ์‚ฌ์šฉ ๊ฐ€๋Šฅ

    • PK ๋Œ€์ƒ ์ปฌ๋Ÿผ ์ค‘ PK๋กœ ์ง€์ •๋˜์ง€ ์•Š์€ ์ปฌ๋Ÿผ : Unique Key (ํ›„๋ณดํ‚ค / ๋Œ€์ฒดํ‚ค / ์œ ์ผํ‚ค)๋กœ ์ง€์ •

    • MySQL์—์„œ์˜ Unique๋Š” ๋ฏธ์ž…๋ ฅ ํ—ˆ์šฉ


AUTO_INCREMENT

  • ์ž๋™ ์ฆ๊ฐ€ ์†์„ฑ

  • PK, UNIQUE๊ฐ€ ์ง€์ •๋œ ์ปฌ๋Ÿผ์—์„œ๋งŒ ์‚ฌ์šฉ ๊ฐ€๋Šฅ

  • ์ž…๋ ฅ๋œ๊ฒƒ ์ค‘ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ๋ฝ‘์•„์™€์„œ +1

  • AUTO_INCREMENT ๊ฐ’ ์ดˆ๊ธฐํ™”ํ•˜๊ธฐ

    • ALTER TABLE table_name AUTO_INCREMENT=์‹œ์ž‘ํ• ์ˆซ์ž;



CRUD


  1. CREATE - INSERT

  2. READ - SELECT

  3. UPDATE - UPDATE

  4. DELETE - DELETE


CREATE / DELETE


UPDATE

  • ๋ฐ์ดํ„ฐ ์ˆ˜์ •

    • UPDATE table_name SET ์ˆ˜์ •ํ• column_name = ์ˆ˜์ •๊ฐ’ WHERE ์กฐ๊ฑด์ ˆ;


SELECT

  • ๋ฐ์ดํ„ฐ ์กฐํšŒ

    • SELECT * FROM table_name WHERE ์กฐ๊ฑด์ ˆ;

      • SELECT * FROM table_name WHERE column_name = ์ˆซ์ž/โ€™๋ฌธ์ž์—ดโ€™;

      • NOT EQUAL ( != ) : SELECT * FROM table_name WHERE column_name != ์ˆซ์ž/โ€™๋ฌธ์ž์—ดโ€™;

    • SELECT column_name1, column_name2 FROM table_name;

    • SELECT column_name AS alias FROM table_name;

Categories:

MySQL