Basic Statements: SELECT, INSERT, UPDATE, DELETE
These four SQL statements form the foundation of everyday database operations. Mastering them is essential for any SQL professional.
SELECT
The SELECT
statement retrieves data from one or more tables.
Basic Syntax:
SELECT column1, column2
FROM table_name
WHERE condition
ORDER BY column1 ASC;
Example:
SELECT first_name, last_name
FROM employees
WHERE department = 'Sales'
ORDER BY last_name;
Key Points:
SELECT *
retrieves all columns.WHERE
filters rows.ORDER BY
sorts the result set.- Use
JOIN
to combine tables.
INSERT
The INSERT
statement adds new rows of data to a table.
Basic Syntax:
INSERT INTO table_name (column1, column2)
VALUES (value1, value2);
Example:
INSERT INTO employees (first_name, last_name, department)
VALUES ('Alice', 'Smith', 'Marketing');
Key Points:
- You must match the order of columns and values.
- Some columns can have default values or auto-increment.
- Use
INSERT INTO ... SELECT
to insert data from another table.
UPDATE
The UPDATE
statement modifies existing data in a table.
Basic Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;
Example:
UPDATE employees
SET department = 'HR'
WHERE employee_id = 1001;
Key Points:
- Always use
WHERE
to avoid updating every row. - Multiple columns can be updated in a single statement.
- Transactions can be used to safely update large sets.
DELETE
The DELETE
statement removes rows from a table.
Basic Syntax:
DELETE FROM table_name
WHERE condition;
Example:
DELETE FROM employees
WHERE department = 'Temporary';
Key Points:
- Always use
WHERE
withDELETE
to avoid deleting all rows. TRUNCATE
removes all rows but is faster and cannot be rolled back in some systems.CASCADE
may be needed to delete related rows when foreign keys are involved.
Summary
Statement | Purpose | Example Use |
---|---|---|
SELECT | Retrieve data | Get a list of employees |
INSERT | Add new data | Add a new employee |
UPDATE | Modify data | Change an employee’s department |
DELETE | Remove data | Delete a terminated employee |
Learning these statements inside out will help you read, write, and maintain data with confidence.