SQL (Structured Query Language) is the standard language for relational databases. Its commands fall into groups: DDL defines structure, DML changes and reads data.
DDL: data definition
CREATE TABLE supplier (
sid INT PRIMARY KEY,
sname VARCHAR(30) NOT NULL,
branch VARCHAR(20),
city VARCHAR(20),
phone VARCHAR(15)
);
ALTER TABLE supplier ADD state VARCHAR(20);
ALTER TABLE supplier DROP COLUMN city;
ALTER TABLE supplier RENAME TO sup;
TRUNCATE TABLE supplies; -- removes all rows, keeps the table
DROP TABLE part; -- removes rows and the table
The exact syntax for changing a column's type or name differs between Oracle, MySQL and PostgreSQL, so check your system's manual.
DML: data manipulation
INSERT INTO supplier VALUES (1, 'Ravi', 'local', 'Delhi', '98100');
SELECT sname, city FROM supplier;
UPDATE supplier SET city = 'Goa' WHERE sname = 'Vandana';
DELETE FROM supplier WHERE sid = 204001;
Warning:
UPDATEorDELETEwithout aWHEREclause changes every row.
Aggregate functions
| Function | Result |
|---|---|
| COUNT() | Number of rows |
| SUM() | Total |
| AVG() | Average |
| MIN() | Smallest |
| MAX() | Largest |
SELECT MIN(price), MAX(price), AVG(price), SUM(price) FROM part;
SELECT COUNT(*) FROM part;
Aggregates ignore NULL values (except COUNT(*)).
Operators and predicates
- Logical: AND, OR, NOT.
- BETWEEN:
price BETWEEN 200 AND 600includes both ends. - LIKE:
%matches any text,_matches one character.'V%A'starts with V and ends with A;'_R%'has R in second position. - IN:
pname IN ('NUT','BOLT'). - DISTINCT: removes duplicates. Alias:
AS.
SELECT DISTINCT branch FROM supplier;
SELECT sname AS supplier_name FROM supplier WHERE sname LIKE 'V%A';
Clauses
SELECT color, SUM(price)
FROM part
GROUP BY color
HAVING SUM(price) > 1000
ORDER BY SUM(price) DESC
LIMIT 3; -- TOP 3 in SQL Server
WHERE filters rows before grouping; HAVING filters groups after grouping.
Common mistakes
- Using
WHEREwith an aggregate such asWHERE COUNT(*) > 2; useHAVING. - Writing
= NULL. UseIS NULL. - Selecting a plain column that is not in
GROUP BYand not aggregated.
Practice questions
- Differentiate DDL and DML with two commands each.
- Write a query for the total price of parts of each colour.
- Differentiate WHERE and HAVING.
- Differentiate DELETE, TRUNCATE and DROP.
- Write a query for suppliers whose name starts with V and ends with A.
Answers to the practice questions
- DDL: CREATE, ALTER. DML: INSERT, UPDATE.
SELECT color, SUM(price) FROM part GROUP BY color;- WHERE filters rows before grouping; HAVING filters groups after.
- DELETE removes chosen rows; TRUNCATE removes all rows but keeps the table; DROP removes the table itself.
SELECT * FROM supplier WHERE sname LIKE 'V%A';
Sources
- Official BCA syllabus Database Management Systems, course code CC202, Unit II
- Raghu Ramakrishnan and Johannes Gehrke, Database Management Systems, 3rd edition, McGraw-Hill
