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: UPDATE or DELETE without a WHERE clause 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 600 includes 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 WHERE with an aggregate such as WHERE COUNT(*) > 2; use HAVING.
  • Writing = NULL. Use IS NULL.
  • Selecting a plain column that is not in GROUP BY and not aggregated.

Practice questions

  1. Differentiate DDL and DML with two commands each.
  2. Write a query for the total price of parts of each colour.
  3. Differentiate WHERE and HAVING.
  4. Differentiate DELETE, TRUNCATE and DROP.
  5. Write a query for suppliers whose name starts with V and ends with A.

Answers to the practice questions

  1. DDL: CREATE, ALTER. DML: INSERT, UPDATE.
  2. SELECT color, SUM(price) FROM part GROUP BY color;
  3. WHERE filters rows before grouping; HAVING filters groups after.
  4. DELETE removes chosen rows; TRUNCATE removes all rows but keeps the table; DROP removes the table itself.
  5. 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