Learn › Class 12 › Computer Science / Informatics Practices › Databases and SQL
Databases and SQL
You will learn to
- Use relational terms: relation, attribute, tuple, degree, cardinality and keys
- Write SQL to create tables and to insert, update and delete rows
- Write SELECT queries with WHERE, ORDER BY, aggregates, GROUP BY and joins
Helpful to know first: Tables and rows; Logical operators AND, OR, NOT.
A relational database stores data in tables, called relations. Columns are attributes and rows are tuples. Degree is the number of columns; cardinality is the number of rows.
Keys
A candidate key can identify each row uniquely. The chosen one is the primary key (unique, not NULL); the others are alternate keys. A foreign key refers to the primary key of another table.
DDL commands change structure: CREATE TABLE, ALTER TABLE and DROP TABLE. DML commands change data: INSERT, UPDATE and DELETE. SELECT reads data.
WHERE filters rows using =, <, >, BETWEEN (inclusive), IN, LIKE and IS NULL. In LIKE, % matches any number of characters and _ matches exactly one.
ORDER BY sorts results, ASC or DESC. Aggregates COUNT, SUM, AVG, MAX and MIN work on groups. GROUP BY forms the groups and HAVING filters them.
A Cartesian product pairs every row of one table with every row of another. An equi-join keeps pairs whose common columns match, as in WHERE A.id = B.id.
Common mix-ups
Not quite: WHERE and HAVING are interchangeable.
Instead: WHERE filters single rows before grouping. HAVING filters groups after GROUP BY, and can use aggregates.
Not quite: DELETE FROM STUDENT; removes the table.
Instead: DELETE removes the rows but keeps the empty table. DROP TABLE removes the table itself.