SQL INSERT INTO Statement π₯ΒΆ
Prerequisites: CREATE TABLE
Mentor's Note: Creating a table is like building a bookshelf.
INSERT INTOis the act of putting a book on that shelf. You must make sure the book fits the shelf's size and category! π‘
π The Scenario: The Club Membership ποΈΒΆ
Imagine you are at the entrance of a club.
- The Form: You need to provide your Name, Age, and Email.
- The Action: Once you fill it out, the club "inserts" your form into their member file.
- The Rule: If you don't provide a Name (NOT NULL), you can't join!
π¨ Visual Logic: Data FlowΒΆ
graph TD
A[Value 1: 'VD'] --> B[Column: Name]
A2[Value 2: 25] --> B2[Column: Age]
B --> C[(Table)]
B2 --> C
π» 1. The Basic SyntaxΒΆ
There are two ways to use INSERT.
A. Specifying Column Names (Best Practice)ΒΆ
Use this when you are only filling some columns or want to be safe.
B. Without Column NamesΒΆ
Use this ONLY if you are providing values for every single column in the exact order they were created.
-- β οΈ Risky if table structure changes!
INSERT INTO students
VALUES (102, 'Priya', 'Mumbai', '[email protected]');
π» 2. Inserting NULL Values βͺΒΆ
If a column allows it, you can leave it empty using the NULL keyword.
π» 3. Inserting Dates π ΒΆ
Dates are usually written as strings inside single quotes. The format depends on your database settings.
π Common Mistakes to AvoidΒΆ
- Wrong Order: Putting the Age where the Name should be.
- Missing Quotes: Forgetting single quotes
'for strings and dates. - Constraint Violation: Trying to insert a duplicate value into a Primary Key column.