SQL INSERT INTO Statement 📥¶
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.