Database Query using SQL
What this domain tests
This domain tests command classification, table creation, and the SELECT family: filtering rows, sorting, aggregating, grouping and joining tables.
Command families and core syntax
- DDL changes structure:
CREATE,ALTER,DROP,TRUNCATE. DML changes data:INSERT,UPDATE,DELETE;SELECTis the query command. SELECT col1, col2 FROM table WHERE condition ORDER BY col DESC;Filtering operators includeBETWEEN,IN,LIKE(%for many characters,_for one) andIS NULL.- Aggregates:
COUNT(*),COUNT(col)(ignores NULLs),SUM,AVG,MIN,MAX. GROUP BYforms groups;HAVINGfilters those groups after aggregation;WHEREfilters individual rows before grouping.- Joins:
INNER JOIN,LEFT JOIN,RIGHT JOINwithON table1.key = table2.key. Two tables joined with no condition give a Cartesian product. - Functions:
UPPER,LOWER,LENGTH,CONCAT,ROUND,ABS,YEAR,IFNULL.
Worked example
SELECT dept, AVG(salary) FROM emp WHERE salary > 10000 GROUP BY dept HAVING COUNT(*) > 2 ORDER BY AVG(salary) DESC; Reasoning, in execution order: WHERE first removes employees earning 10000 or less; remaining rows are grouped by department; HAVING keeps only departments with more than two such employees; finally the surviving groups are sorted by average salary, highest first.
Traps that cost marks
Using HAVING where WHERE belongs, or the reverse; assuming COUNT(col) counts NULLs; writing = NULL instead of IS NULL; selecting a non-aggregated column that is absent from GROUP BY; confusing DELETE (removes rows), TRUNCATE (empties the table) and DROP (removes the table); omitting the join condition and accidentally producing every row pair.