These ten statements cover most of what you will write in day-to-day work and in a first SQL interview. The examples use a simple employees table, so you can paste them into any practice database.
1. SELECT
SELECT retrieves data from one or more tables. It is the most basic and fundamental SQL query. Use * for all columns, or list the columns you need, like SELECT column1, column2.
SELECT * FROM employees;
This returns every column of the employees table.
2. WHERE
WHERE filters rows based on a condition. It works with SELECT, UPDATE and DELETE, and you can combine several conditions with AND and OR.
SELECT * FROM employees WHERE department = 'sales';
This returns only the employees who work in sales.
3. GROUP BY
GROUP BY groups rows that share a value in one or more columns. It is usually used with an aggregate function such as SUM, AVG or COUNT, to get one result per group.
SELECT department, AVG(salary)
FROM employees
GROUP BY department;
This returns the average salary of each department.
4. JOIN
JOIN combines rows from two or more tables using a related column. The common types are INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL OUTER JOIN. The ON clause says which columns must match.
SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments
ON employees.department_id = departments.department_id;
This lists each employee with the name of their department. INNER JOIN keeps only employees who have a matching department.
5. ORDER BY
ORDER BY sorts the result by one or more columns, ascending (the default) or descending.
SELECT name, salary FROM employees ORDER BY salary DESC;
This returns every employee, highest salary first.
6. INSERT
INSERT adds a new row to a table. VALUES lists the data for each column, in the same order as the column list.
INSERT INTO employees (name, department, salary)
VALUES ('John Smith', 'IT', 50000);
This adds John Smith to the IT department with a salary of 50000.
7. UPDATE
UPDATE changes existing rows. SET gives the new values and WHERE picks which rows change. Leave WHERE out and every row is updated, so check it twice.
UPDATE employees SET salary = 55000 WHERE name = 'John Smith';
This raises John Smith's salary to 55000.
8. DELETE
DELETE removes rows. As with UPDATE, WHERE decides which rows go. Without it, the whole table is emptied.
DELETE FROM employees WHERE name = 'John Smith';
This removes John Smith from the table.
9. DISTINCT
DISTINCT removes duplicates from a result, so you see each value once.
SELECT DISTINCT department FROM employees;
This returns each department name one time, however many employees it has.
10. LIMIT
LIMIT caps the number of rows a query returns. It is available in MySQL and PostgreSQL. SQL Server uses TOP, and Oracle uses FETCH FIRST n ROWS ONLY.
SELECT * FROM employees ORDER BY salary DESC LIMIT 5;
This returns the five highest-paid employees.
Next step: try these on real practice data in the SQL practice sets.
