Predict the output of: SELECT job, COUNT(*) AS n FROM emp WHERE salary >= 25000 GROUP BY job HAVING COUNT(*) > 1 ORDER BY n DESC, job;
SQL is the standard declarative language of relational databases: DDL defines tables and constraints, DML queries and changes rows, DCL grants privileges and TCL controls transactions. Clause order, NULL logic and DELETE vs TRUNCATE vs DROP answer a large share of PSC questions.
SQL (Structured Query Language) started life as SEQUEL, designed by Donald Chamberlin and Raymond Boyce at IBM in 1974 for the System R prototype. It became an ANSI standard in 1986 and an ISO standard in 1987; major revisions are SQL-92, SQL:1999 (triggers, recursive queries, object features), SQL:2003 (window functions, MERGE), SQL:2011 (temporal data), SQL:2016 (JSON) and SQL:2023. Every vendor adds its own dialect — Oracle's PL/SQL, Microsoft's T-SQL, MySQL and SQLite extensions.
| Sub-language | Statements | Purpose |
|---|---|---|
| DDL — data definition | CREATE, ALTER, DROP, TRUNCATE, RENAME, COMMENT | Define and change schema objects |
| DML — data manipulation | SELECT, INSERT, UPDATE, DELETE, MERGE | Query and change rows (SELECT is sometimes called DQL) |
| DCL — data control | GRANT, REVOKE | Give and take away privileges |
| TCL — transaction control | COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION | End or partly undo transactions |
SQL is declarative: a query states the result wanted and the optimizer chooses the steps. Keywords are case-insensitive (select = SELECT), statements end with a semicolon, string literals use single quotes ('Kochi'), comments are -- to end of line or /* … */, and string comparisons may or may not be case-sensitive depending on the product.
| Type | Holds | Notes |
|---|---|---|
| INTEGER (INT), SMALLINT, BIGINT | Whole numbers | Ranges differ by product |
| NUMERIC(p, s) = DECIMAL(p, s) | Exact decimals: p digits in all, s of them after the point | NUMERIC(7,2) holds up to 99999.99 — use for money |
| REAL, FLOAT, DOUBLE PRECISION | Approximate floating point | Rounding errors: 0.1 + 0.2 ≠ 0.3 exactly |
| CHAR(n) | Fixed-length string, blank-padded to n | CHAR(10) stores 'Kochi' as 'Kochi' plus 5 spaces |
| VARCHAR(n) (Oracle VARCHAR2) | Variable-length string up to n characters | Stores only the characters used |
| TEXT / CLOB, BLOB | Large text, binary objects | Documents, images |
| DATE, TIME, TIMESTAMP, INTERVAL | Dates, times, durations | Oracle's DATE also stores the time of day |
| BOOLEAN | TRUE, FALSE (or UNKNOWN) | MySQL maps it to TINYINT(1) |
| ENUM('a','b'), SET('x','y') (MySQL) | One value from a list / any subset of a list | MySQL-specific |
SQLite is unusual: it uses dynamic typing with type affinity. A column declared VARCHAR(20) gets TEXT affinity but the length is not enforced, and DECIMAL(10,2) gets NUMERIC affinity. Declaring standard types still documents intent and keeps scripts portable.
PRAGMA foreign_keys = ON; -- SQLite only: enforce foreign keys
CREATE TABLE dept (
dept_id INTEGER PRIMARY KEY,
dname VARCHAR(20) NOT NULL UNIQUE,
location VARCHAR(20)
);
CREATE TABLE emp (
emp_id INTEGER PRIMARY KEY,
ename VARCHAR(30) NOT NULL,
job VARCHAR(20),
salary DECIMAL(10,2) CHECK (salary > 0),
hire_date DATE,
dept_id INTEGER REFERENCES dept(dept_id),
manager_id INTEGER REFERENCES emp(emp_id)
);
CREATE TABLE project (
proj_id INTEGER PRIMARY KEY,
pname VARCHAR(30) NOT NULL,
dept_id INTEGER REFERENCES dept(dept_id),
budget DECIMAL(12,2) CHECK (budget >= 0)
);
CREATE TABLE works_on (
emp_id INTEGER REFERENCES emp(emp_id),
proj_id INTEGER REFERENCES project(proj_id),
hours INTEGER,
PRIMARY KEY (emp_id, proj_id)
);
INSERT INTO dept VALUES
(10, 'Accounts', 'Thrissur'),
(20, 'Research', 'Kochi'),
(30, 'Sales', 'Kozhikode'),
(40, 'Operations', 'Kochi');
INSERT INTO emp VALUES
(101, 'Anil', 'President', 90000, '2015-01-10', 10, NULL),
(102, 'Bindu', 'Manager', 60000, '2016-03-15', 20, 101),
(103, 'Charles', 'Manager', 55000, '2017-06-01', 30, 101),
(104, 'Divya', 'Analyst', 50000, '2018-07-20', 20, 102),
(105, 'Eby', 'Analyst', 50000, '2019-02-11', 20, 102),
(106, 'Fathima', 'Salesman', 30000, '2019-09-05', 30, 103),
(107, 'Gopal', 'Salesman', 28000, '2020-01-17', 30, 103),
(108, 'Hari', 'Clerk', 22000, '2021-04-12', 10, 101),
(109, 'Indu', 'Clerk', 20000, '2022-08-30', 20, 104),
(110, 'Jose', 'Clerk', 25000, '2023-11-02', NULL, 103);
INSERT INTO project VALUES
(1, 'Payroll', 10, 400000),
(2, 'AI Lab', 20, 900000),
(3, 'CRM', 30, 500000),
(4, 'Website', 20, 300000);
INSERT INTO works_on VALUES
(102, 1, 10), (102, 2, 20), (102, 3, 10), (102, 4, 10),
(104, 2, 30), (104, 4, 20),
(105, 1, 20), (105, 2, 20), (105, 4, 10),
(106, 3, 40),
(107, 3, NULL),
(108, 1, 30);Two quick ways to copy a table: CREATE TABLE emp_copy AS SELECT * FROM emp; copies structure and data (add WHERE 1 = 0 to copy only the structure); MySQL's CREATE TABLE emp2 LIKE emp; copies the structure including indexes. Neither CTAS form copies primary or foreign keys.
| Task | Standard / Oracle / MySQL | SQLite |
|---|---|---|
| Add a column | ALTER TABLE emp ADD email VARCHAR(40); | ALTER TABLE emp ADD COLUMN email VARCHAR(40); |
| Change a column's type | Oracle/MySQL: ALTER TABLE emp MODIFY ename VARCHAR(50); — SQL Server/PostgreSQL: ALTER COLUMN | Not supported — rebuild the table |
| Rename a column | ALTER TABLE emp RENAME COLUMN email TO mail; | Same (3.25+) |
| Drop a column | ALTER TABLE emp DROP COLUMN mail; | Same (3.35+) |
| Add a constraint | ALTER TABLE emp ADD CONSTRAINT chk_sal CHECK (salary < 200000); | Not supported |
| Drop a constraint | ALTER TABLE emp DROP CONSTRAINT chk_sal; | Not supported |
| Rename a table | ALTER TABLE project RENAME TO projects; (Oracle also RENAME project TO projects;) | ALTER TABLE … RENAME TO … |
| Remove a table | DROP TABLE emp_old; — Oracle … CASCADE CONSTRAINTS drops referencing FKs | DROP TABLE IF EXISTS emp_old; |
| Empty a table | TRUNCATE TABLE works_on; | No TRUNCATE — DELETE FROM works_on; is optimised to a fast truncate |
| DELETE | TRUNCATE | DROP | |
|---|---|---|---|
| Category | DML | DDL | DDL |
| Removes | Selected rows (WHERE) or all rows | All rows | Rows, structure, indexes, privileges, triggers |
| WHERE clause | Yes | No | No |
| How | Row by row, each change logged | Deallocates data pages; minimal logging | Removes the table from the catalog |
| Rollback | Yes, until COMMIT | No in Oracle and MySQL (implicit commit); yes in PostgreSQL and SQL Server | No (Oracle can FLASHBACK from the recycle bin) |
| Fires DELETE triggers | Yes | No | No |
| Speed on a big table | Slowest | Fast | Fast |
| Identity / auto-increment | Not reset | Reset | Gone with the table |
| Table still exists? | Yes | Yes (empty) | No |
-- one row, all columns in table order
INSERT INTO dept VALUES (50, 'Legal', 'Kollam');
-- named columns; omitted columns get DEFAULT or NULL
INSERT INTO dept (dept_id, dname) VALUES (60, 'Audit');
-- several rows at once (SQL-92 row constructors; Oracle uses INSERT ALL or one row per INSERT)
INSERT INTO dept (dept_id, dname) VALUES (70, 'Stores'), (80, 'Security');
-- INSERT ... SELECT copies rows from a query
CREATE TABLE emp_archive AS SELECT * FROM emp WHERE 1 = 0;
INSERT INTO emp_archive SELECT * FROM emp WHERE hire_date < '2018-01-01'; -- 3 rows: Anil, Bindu, Charles
UPDATE emp SET salary = salary + 2000 WHERE job = 'Clerk'; -- 3 rows: Hari 24000, Indu 22000, Jose 27000
UPDATE emp SET job = 'Senior Analyst', salary = salary + 5000 WHERE emp_id = 104;
DELETE FROM works_on WHERE hours IS NULL; -- 1 row (Gopal's CRM entry)UPDATE and DELETE without WHERE affect every row — the most expensive typo in SQL. A good habit is to run the same WHERE as a SELECT first. Values in SET are computed from the row's old values, so SET a = b, b = a swaps two columns in standard SQL.
MERGE (SQL:2003, Oracle, SQL Server) inserts a row if it is new and updates it if it exists — an upsert. SQLite and PostgreSQL write INSERT … ON CONFLICT (dept_id) DO UPDATE SET location = excluded.location, and MySQL writes INSERT … ON DUPLICATE KEY UPDATE ….
SELECT [DISTINCT] column_list -- 5 (6: DISTINCT)
FROM table_list -- 1
WHERE row_condition -- 2
GROUP BY grouping_columns -- 3
HAVING group_condition -- 4
ORDER BY sort_list -- 7
LIMIT n OFFSET m; -- 8 (Oracle/SQL standard: FETCH FIRST n ROWS ONLY)The logical order explains three classic errors: an aggregate in WHERE (groups not formed yet), a SELECT alias in WHERE (alias not defined yet — standard SQL, Oracle, MySQL and PostgreSQL reject it, though SQLite tolerates it), and a non-grouped column in the SELECT list of a grouped query. The physical execution may differ — the optimizer may use an index first — but the result must be as if this order were followed.
| Predicate | Example | Rows from emp |
|---|---|---|
| Comparison = <> != < > <= >= | salary > 50000 | Anil, Bindu, Charles |
| BETWEEN (inclusive) | salary BETWEEN 30000 AND 50000 | Divya, Eby, Fathima (30000 and 50000 included) |
| IN list | job IN ('Analyst', 'Clerk') | Divya, Eby, Hari, Indu, Jose |
| LIKE with _ (one char) | ename LIKE '_i%' | Bindu, Divya — second letter i |
| LIKE with % (any string) | ename LIKE '%a' | Divya, Fathima — ending in a |
| IS NULL | dept_id IS NULL | Jose |
| Dates as ISO strings (SQLite) | hire_date BETWEEN '2019-01-01' AND '2020-12-31' | Eby, Fathima, Gopal |
In LIKE patterns, % matches any sequence of zero or more characters and _ exactly one. To search for a literal % or _, declare an escape character: remark LIKE '%50\%%' ESCAPE '\' finds remarks containing '50%'. Case sensitivity differs: SQLite (for ASCII) and MySQL (default collation) ignore case, Oracle and PostgreSQL do not — so ename LIKE '%i%' returns 6 names in SQLite (Indu included) but 5 in Oracle.
NULL means 'unknown or not applicable'. Any comparison with NULL — even NULL = NULL — yields UNKNOWN, the third truth value. WHERE keeps a row only when its condition is TRUE, so both FALSE and UNKNOWN rows are dropped. Arithmetic with NULL gives NULL (salary + NULL = NULL); use COALESCE(x, 0) (Oracle NVL, MySQL/SQLite IFNULL) to substitute a value.
| p | q | p AND q | p OR q | NOT p |
|---|---|---|---|---|
| TRUE | UNKNOWN | UNKNOWN | TRUE | FALSE |
| FALSE | UNKNOWN | FALSE | UNKNOWN | TRUE |
| UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN |
WHERE dept_id = NULL returns 0 rows even though Jose's dept_id is NULL; WHERE dept_id <> 20 returns 5 rows, silently excluding Jose. Use IS NULL / IS NOT NULL, and add OR dept_id IS NULL when NULL rows must be included (6 rows). Operator precedence is NOT, then AND, then OR — use parentheses.DISTINCT removes duplicate rows of the whole select list: SELECT DISTINCT dept_id FROM emp gives 4 rows (10, 20, 30 and NULL — duplicates of NULL collapse into one), while SELECT DISTINCT job, dept_id gives 8 distinct combinations. ORDER BY sorts ascending by default; add DESC per column, list several keys, or use a column position (ORDER BY 2 DESC). SQLite and MySQL sort NULLs first in ascending order, Oracle and PostgreSQL last (override with NULLS FIRST / NULLS LAST).
SELECT ename,
salary * 12 AS annual,
UPPER(ename) AS upper_name,
LENGTH(ename) AS len,
SUBSTR(ename, 1, 3) AS abbr,
strftime('%Y', hire_date) AS hired_in,
CASE WHEN salary >= 60000 THEN 'A'
WHEN salary >= 30000 THEN 'B'
ELSE 'C' END AS grade
FROM emp e -- e is a table alias
WHERE e.dept_id = 10
ORDER BY annual DESC;
-- Anil | 1080000 | ANIL | 4 | Ani | 2015 | A
-- Hari | 264000 | HARI | 4 | Har | 2021 | C| Kind | SQLite | Oracle | MySQL |
|---|---|---|---|
| Concatenate | 'Ker' || 'ala' | || or CONCAT(a, b) | CONCAT('Ker', 'ala') |
| Substring / length | SUBSTR, LENGTH | SUBSTR, LENGTH | SUBSTRING, CHAR_LENGTH |
| Case, trim, replace | UPPER, LOWER, TRIM, REPLACE | UPPER, LOWER, INITCAP, TRIM | UPPER, LOWER, TRIM, REPLACE |
| Rounding | ROUND(x, 2), ABS, x % y | ROUND, TRUNC, CEIL, FLOOR, MOD | ROUND, TRUNCATE, CEIL, FLOOR, MOD |
| Today | date('now') | SYSDATE, CURRENT_DATE | CURDATE(), NOW() |
| Date parts / arithmetic | strftime('%Y', d), julianday(d2) − julianday(d1) | EXTRACT(YEAR FROM d), ADD_MONTHS, MONTHS_BETWEEN | YEAR(d), DATEDIFF(d2, d1), DATE_ADD |
| NULL substitute | IFNULL, COALESCE | NVL, COALESCE | IFNULL, COALESCE |
| First n rows | LIMIT n OFFSET m | FETCH FIRST n ROWS ONLY (12c+), ROWNUM | LIMIT m, n or LIMIT n OFFSET m |
Integer arithmetic catches people out: in SQLite, PostgreSQL and SQL Server 7 / 2 is 3 while 7 / 2.0 is 3.5 (MySQL and Oracle give 3.5 for both). CASE comes in two forms — the searched form above, and the simple form CASE job WHEN 'Clerk' THEN 1 WHEN 'Analyst' THEN 2 ELSE 3 END. A CASE with no matching branch and no ELSE returns NULL.
GRANT SELECT, INSERT ON emp TO clerk;
GRANT UPDATE (salary) ON emp TO hr_mgr WITH GRANT OPTION; -- column privilege, may be passed on
GRANT SELECT ON dept TO PUBLIC; -- every user
CREATE ROLE payroll;
GRANT SELECT, UPDATE ON emp TO payroll;
GRANT payroll TO anu; -- roles bundle privileges
REVOKE INSERT ON emp FROM clerk;
REVOKE UPDATE ON emp FROM hr_mgr CASCADE; -- also from users hr_mgr granted it toObject privileges include SELECT, INSERT, UPDATE (optionally per column), DELETE, REFERENCES (to create foreign keys), EXECUTE (routines) and ALL PRIVILEGES. WITH GRANT OPTION lets the grantee grant the same privilege to others; revoking with CASCADE removes those dependent grants too, while RESTRICT refuses the revoke if any exist. Oracle cascades object-privilege revokes automatically.
BEGIN; -- START TRANSACTION in MySQL
UPDATE emp SET salary = salary + 1000 WHERE emp_id = 108; -- Hari 22000 → 23000
SAVEPOINT s1;
DELETE FROM works_on WHERE emp_id = 108; -- Hari's assignment removed
ROLLBACK TO s1; -- undo only the work after s1 (standard: ROLLBACK TO SAVEPOINT s1)
COMMIT; -- make the salary change permanent
-- result: Hari earns 23000 and still has his works_on row (108, 1, 30)COMMIT makes all changes of the transaction permanent and visible; ROLLBACK undoes them all; SAVEPOINT marks a point that ROLLBACK TO can return to without ending the transaction (RELEASE SAVEPOINT forgets it). Many tools run in autocommit mode, committing each statement automatically. Oracle and MySQL also commit implicitly before and after every DDL statement, whereas PostgreSQL and SQLite let DDL be rolled back.
Try the problem first, then reveal the working one step at a time.
Predict the output of: SELECT job, COUNT(*) AS n FROM emp WHERE salary >= 25000 GROUP BY job HAVING COUNT(*) > 1 ORDER BY n DESC, job;
On the sample emp table (Jose's dept_id is NULL) how many rows does each return? (a) WHERE dept_id = NULL; (b) WHERE dept_id IS NULL; (c) WHERE dept_id <> 20; (d) WHERE NOT (dept_id = 20); (e) WHERE dept_id <> 20 OR dept_id IS NULL.
Starting from the original data, run: BEGIN; UPDATE emp SET salary = salary + 1000 WHERE emp_id = 108; SAVEPOINT s1; DELETE FROM works_on WHERE emp_id = 108; ROLLBACK TO s1; COMMIT; — what are Hari's salary and his number of works_on rows afterwards?
Pick the right command: (a) remove last year's log rows only (WHERE log_date < '2025-01-01') and keep the option to roll back; (b) empty a 50-million-row staging table every night as fast as possible, keeping its structure; (c) retire a table the application no longer uses.
Predict the output of SELECT ename FROM emp WHERE salary BETWEEN 25000 AND 50000 ORDER BY salary DESC, ename;
A student writes: SELECT ename, salary * 12 AS annual FROM emp WHERE annual > 600000; Oracle and MySQL reject it. Why, and how do you fix it? What does it return once fixed?
Which names match each pattern on the sample data? (a) '%a' (b) 'A%' (c) '_a%' (d) '%i%' — and how would the answer to (d) change in Oracle?
Write a CREATE TABLE for allotment(allot_no, allottee_id, house_no, allot_date, amount, status) where allot_no is the key, a house number may appear in at most one allotment row, allottee_id must exist in allottee(allottee_id), amount is required and positive, and status is required, defaults to 'ACTIVE' and may only be 'ACTIVE' or 'CANCELLED'.
In standard SQL, user A owns emp and runs GRANT SELECT ON emp TO B WITH GRANT OPTION. B then runs GRANT SELECT ON emp TO C. Finally A runs REVOKE SELECT ON emp FROM B CASCADE. Who can still read emp? What would REVOKE … RESTRICT have done?
= NULL and <> NULL are never true — use IS NULL / IS NOT NULL. Rows whose condition is UNKNOWN are dropped by WHERE just like FALSE ones.12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.