Table of Contents

    Data manipulation language - MySQL

    SQL CATEGORY • DML

    Data Manipulation Language (DML) in MySQL

    The Commands That Bring Your Database to Life — Insert, Update, Delete & Query Data

    What is DML?

    Data Manipulation Language (DML) is a category of SQL commands used to manage and manipulate the data stored inside database tables. While DDL defines the structure of the database, DML works with the actual data — adding, modifying, retrieving, and deleting records.

    DML commands are the most frequently used SQL commands in real-world applications. Every time you sign up on a website, place an order, update your profile, or delete a post — DML commands are running behind the scenes inside MySQL.

    "DDL builds the house; DML brings life into it. Without DML, a database is just an empty shell."

    Easy Analogy

    Think of DDL as building an empty notebook with pages and sections. DML is the act of writing, editing, and erasing content inside it. The notebook structure stays the same; only the content changes.

    Main DML Commands in MySQL

    MySQL provides four core DML commands to manage data within tables:

    DML COMMANDS
    INSERT UPDATE DELETE SELECT
    Command Purpose Example Use
    INSERTAdds new records into a tableAdd a new student
    UPDATEModifies existing recordsChange a student's city
    DELETERemoves records from a tableDelete a graduated student
    SELECTRetrieves data from a tableView all students
    Note: Although SELECT is sometimes classified under DQL (Data Query Language), it is widely accepted as part of DML because it works with data, not structure.

     1. INSERT Command

    The INSERT command is used to add new rows of data into a table.

    Insert a Single Record

    
    INSERT INTO Students (name, age, city, course)
    VALUES ('Rumman Ansari', 25, 'Kolkata', 'Computer Science');
    

    Insert Multiple Records at Once

    
    INSERT INTO Students (name, age, city, course) VALUES
    ('Aditi Sharma', 22, 'Delhi', 'Data Science'),
    ('Rohan Mehta', 24, 'Mumbai', 'AI & ML'),
    ('Priya Singh', 23, 'Bangalore', 'Cybersecurity');
    

    Insert Without Column Names (All Columns)

    
    -- Values must match the exact column order of the table
    INSERT INTO Students 
    VALUES (105, 'Arjun Verma', 26, 'Pune', 'Cloud Computing');
    

    Insert Data from Another Table

    
    -- Copy data from one table to another
    INSERT INTO Students_Backup (name, age, city, course)
    SELECT name, age, city, course FROM Students
    WHERE city = 'Kolkata';
    
    Pro Tips:
    • Use column names explicitly for clarity and safety
    • Use NULL for columns where no value is available
    • Use DEFAULT to insert default values
    • Use INSERT IGNORE to skip duplicates silently

     2. UPDATE Command

    The UPDATE command is used to modify existing records in a table. Always pair it with a WHERE clause to avoid updating all rows.

    Update a Single Column

    
    UPDATE Students 
    SET age = 26 
    WHERE name = 'Rumman Ansari';
    

    Update Multiple Columns

    
    UPDATE Students 
    SET city = 'Hyderabad', course = 'Cloud Computing' 
    WHERE student_id = 102;
    

    Update Using Expressions

    
    -- Increase everyone's age by 1
    UPDATE Students 
    SET age = age + 1;
    
    -- Apply discount to product prices
    UPDATE Products 
    SET price = price * 0.90 
    WHERE category = 'Electronics';
    

    Update Using a Condition with JOIN

    
    UPDATE Students s
    JOIN Courses c ON s.course_id = c.course_id
    SET s.fee = c.fee
    WHERE c.course_name = 'Data Science';
    
    Warning Never run UPDATE without a WHERE clause — it will update every row in the table!

     3. DELETE Command

    The DELETE command is used to remove existing rows from a table. It can be rolled back if used within a transaction.

    Delete a Specific Record

    
    DELETE FROM Students 
    WHERE student_id = 101;
    

    Delete Records with Conditions

    
    -- Delete all students from a specific city
    DELETE FROM Students 
    WHERE city = 'Delhi';
    
    -- Delete records older than a certain date
    DELETE FROM Orders 
    WHERE order_date < '2023-01-01';
    

    Delete Using JOIN

    
    DELETE s FROM Students s
    JOIN Courses c ON s.course_id = c.course_id
    WHERE c.course_name = 'Discontinued Course';
    

    Delete All Records (But Keep Structure)

    
    DELETE FROM Students;
    
    DELETE vs TRUNCATE:
    • DELETE — Removes specific rows, can use WHERE, can be rolled back
    • TRUNCATE — Removes all rows instantly, resets AUTO_INCREMENT, cannot rollback

     4. SELECT Command

    The SELECT command is used to retrieve data from one or more tables. It is the most widely used SQL command.

    Select All Columns

    
    SELECT * FROM Students;
    

    Select Specific Columns

    
    SELECT name, city, course FROM Students;
    

    Select with WHERE Clause

    
    SELECT * FROM Students 
    WHERE age > 22 AND city = 'Kolkata';
    

    Select with ORDER BY

    
    SELECT * FROM Students 
    ORDER BY name ASC;
    
    SELECT * FROM Students 
    ORDER BY age DESC;
    

    Select with LIMIT

    
    -- Top 3 oldest students
    SELECT * FROM Students 
    ORDER BY age DESC 
    LIMIT 3;
    
    -- Pagination — Skip 5, fetch next 5
    SELECT * FROM Students 
    LIMIT 5 OFFSET 5;
    

    Select with DISTINCT

    
    -- Get unique city names
    SELECT DISTINCT city FROM Students;
    

    Select with GROUP BY and Aggregate Functions

    
    SELECT city, COUNT(*) AS total_students
    FROM Students
    GROUP BY city
    ORDER BY total_students DESC;
    

    Select with JOIN

    
    SELECT s.name, c.course_name, c.duration
    FROM Students s
    INNER JOIN Courses c ON s.course_id = c.course_id;
    

    Important DML Operators

    DML commands become powerful when combined with operators that help filter and refine data.

    Operator Purpose Example
    =, !=, >, <ComparisonWHERE age > 18
    AND, OR, NOTLogical operatorsWHERE city='Kolkata' AND age>20
    BETWEENRange filterWHERE age BETWEEN 20 AND 25
    INMultiple values matchWHERE city IN ('Delhi','Mumbai')
    LIKEPattern matchingWHERE name LIKE 'R%'
    IS NULLCheck for NULL valuesWHERE email IS NULL
    EXISTSSubquery checkWHERE EXISTS (SELECT 1 FROM Orders)

    Example: Combining DML Operators

    
    SELECT name, city, age 
    FROM Students 
    WHERE (city IN ('Kolkata', 'Mumbai')) 
      AND (age BETWEEN 20 AND 25) 
      AND (name LIKE 'A%')
    ORDER BY age DESC;
    

    DML & Transactions

    One of the biggest advantages of DML over DDL is that DML changes can be controlled using transactions. This means you can commit changes permanently or roll back if something goes wrong.

    
    START TRANSACTION;
    
    UPDATE Accounts SET balance = balance - 5000 WHERE acc_id = 1;
    UPDATE Accounts SET balance = balance + 5000 WHERE acc_id = 2;
    
    -- If both succeed
    COMMIT;
    
    -- If something fails
    -- ROLLBACK;
    
    Why It Matters Transactions ensure ACID compliance, protecting your data from partial updates or accidental losses.

    DDL vs DML — Side-by-Side Comparison

    DDL (Data Definition Language) DML (Data Manipulation Language)
    Defines structureManipulates data
    Commands: CREATE, ALTER, DROP, TRUNCATECommands: INSERT, UPDATE, DELETE, SELECT
    Auto-committedCan be rolled back
    Affects schemaAffects records
    Used during designUsed during operations
    Rarely executedFrequently executed

    Key Characteristics of DML

     Advantages

    • Allows complete data control
    • Supports transactions (COMMIT, ROLLBACK)
    • Can be combined with WHERE for precision
    • Powerful with JOINs and Subqueries
    • Highly flexible and reusable
    • Essential for real-world apps

     Limitations

    • Can accidentally affect all rows
    • Performance issues on large datasets
    • Improper joins may corrupt data
    • Requires careful indexing for speed
    • Transactions must be handled correctly

    Real-World Applications of DML

     Where DML is Used Every Day

    • E-commerce: Adding new products, updating stock, deleting orders
    • Banking: Recording transactions, transferring funds
    • Social Media: Posting, editing, deleting content
    • Education: Adding student marks, updating attendance
    • Healthcare: Updating patient records, deleting expired files
    • Logistics: Tracking shipments, updating delivery status
    • Web Apps: User registration, profile updates, content posting
    • Reporting: Generating data summaries via SELECT

    Common Mistakes to Avoid

    Mistake #1 Running UPDATE or DELETE without a WHERE clause — affects entire table.
    Mistake #2 Forgetting to use BEGIN TRANSACTION for critical multi-step operations.
    Mistake #3 Using SELECT * in production — slows queries and exposes unnecessary data.
    Best Practice Always test DML queries on a development copy before running in production.

    Best Practices for Using DML

     Pro Tips for Beginners

    • Always include a WHERE clause in UPDATE and DELETE
    • Use transactions for multi-step operations
    • Use prepared statements to prevent SQL injection
    • Use indexes on frequently filtered columns
    • Avoid SELECT * — fetch only required columns
    • Backup data before bulk DELETE or UPDATE
    • Validate input data before INSERT operations
    • Use LIMIT while testing UPDATE/DELETE queries
    • Log every critical data change for audit trails
    • Use EXPLAIN to analyze and optimize queries

    Final Analogy

    If DDL is the architect who designs the database, DML is the resident who actually lives and works inside it — writing letters (INSERT), updating diaries (UPDATE), tearing pages (DELETE), and reading stories (SELECT).

     Key Takeaway

    DML (Data Manipulation Language) is the heartbeat of every database — empowering applications to store, retrieve, and evolve data in real time. Master INSERT, UPDATE, DELETE, and SELECT, and you'll master the life cycle of data itself.

    Practice Quiz 30 MCQs Smart Learning

    Master This Topic with Smart Practice

    Reinforce what you just learned by solving high-quality MCQs. Improve accuracy, boost confidence, and prepare like a topper.

    Topic-wise MCQs
    Instant Results
    Improve Accuracy
    Exam Ready Practice
    Login & Start Quiz Create Free Account
    Save progress • Track results • Learn faster