Prepstellar

SQL Fundamentals · SQL Foundations

20 cards

Relational Model and SQL

Swipe, scroll or use ← →
  1. Tables, rows, and typed columns

    Before writing a single query it helps to know what the query is aimed at. PostgreSQL is a relational database management system, which means it is a system for managing data stored in relations, and relation is essentially a mathematical term for table. The two words name the same structure, so a sentence about relations is a sentence about tables.

    The relational arrangement is a deliberate choice rather than the only possibility. Files and directories on a Unix-like operating system form a hierarchical database, and the object-oriented database is a more modern development. A relational system commits to one shape and builds everything else on top of it.

    Arrangement Shape of the stored data
    Hierarchical A tree, as files and directories form on a Unix-like system
    Object-oriented Objects, a more modern development
    Relational Named tables of rows and columns
    1 / 20
  2. Tables, rows, and typed columns

    Each table is a named collection of rows, and each row of a given table has the same set of named columns. Each column is of a specific data type, so every stored value carries a declared kind instead of being loose text.

    The shape of a row therefore belongs to the table, not to the row. A row cannot bring an extra column of its own, leave out one it does not need, or choose a different type for a column than its neighbours use.

    For example, a products table declares id, name, and price. Every row in that table has exactly those three columns, price holds a numeric value in all of them, and no row is free to store a word there instead.

    2 / 20
  3. Quick check

    Someone says a database keeps its data in relations, with a fixed set of typed columns. What is being described?

    1. AA declared link joining two tables together

      A link between tables is a foreign-key reference, which is a separate idea built on top of tables.

    2. BA table, with the same named columns in every row

      Right. Relation is the mathematical term for a table, and every row of a table carries the same named columns, each of one specific data type.

    3. CA grouping of databases managed by one server instance

      A collection of databases managed by one server instance is a database cluster, not a single stored structure.

    3 / 20

  4. Tables, rows, and typed columns

    Two orderings are easy to confuse, and only one of them is promised. Columns have a fixed order in each row, but SQL does not guarantee the order of the rows within a table in any way, although rows can be explicitly sorted for display.

    Ordering Promised by SQL?
    The columns inside a row Yes, fixed by the table definition
    The rows within a table No, not guaranteed in any way
    The rows in a result Only when the statement asks for a sort

    The practical consequence is worth remembering: running the same unsorted query twice can present the same rows in a different sequence, and nothing is broken when it does. Presentation order has to be requested.

    Tables themselves are grouped into databases, and a collection of databases managed by a single PostgreSQL server instance constitutes a database cluster.

    4 / 20
  5. Quick check

    Users report that two runs of the same unsorted listing showed the stored records in a different sequence, and no data changed in between. What is happening?

    1. AThe column order drifted between runs, so columns must be named

      Column order is fixed in each row by the table definition, so it cannot drift between two runs.

    2. BThe session replayed a cached copy of the earlier result

      Nothing replays an earlier result, and no cache decides the sequence in which rows come back.

    3. CRow order is not guaranteed, so the query must sort

      Right. SQL promises nothing about the order of the rows within a table, and only an explicit sort makes the presentation order dependable.

    5 / 20

  6. Identifying rows and relating tables

    Rows are unordered and interchangeable in shape, so the model needs a way to say this row. That is the job of constraints.

    A unique constraint ensures that the data contained in a column, or a group of columns, is unique among all the rows in the table. A primary key constraint indicates that a column, or group of columns, can be used as a unique identifier for rows in the table, and it requires that the values be both unique and not null.

    A table can carry any number of unique constraints, so more than one column may qualify as an identifier, but a table can have at most one primary key, and that single choice is the one the system treats as the identity of a row. Adding a primary key also forces the listed columns to be marked not null.

    Constraint How many per table What it promises
    Unique Any number The values are unique among all rows
    Primary key At most one The values are unique and not null, and identify the row
    6 / 20
  7. Quick check

    A table already carries three separate unique constraints. How many primary keys may it also declare?

    1. AAt most one, whatever the number of unique constraints

      Right. Unique constraints can be repeated freely, but only one candidate can be promoted to primary key, and that promotion also forces its columns to be not null.

    2. BOne for every unique constraint whose columns are not null

      Unique constraints do not each earn a primary key; the limit of one applies to the table as a whole.

    3. CNone, because those unique constraints already identify a row

      Existing unique constraints never block a primary key, and the primary key is still the declared identity of a row.

    7 / 20

  8. Keep your progress in the app

    That’s 3 of 9 quick checks. In the app they stay answered, and every lesson remembers where you left off.

  9. Identifying rows and relating tables

    References between tables are built on that identity. A foreign key constraint specifies that the values in a column, or a group of columns, must match the values appearing in some row of another table, which is how referential integrity between two related tables is maintained.

    The two sides have names worth keeping straight. The table that carries the constraint is the referencing table, and the table it points at is the referenced table.

    When no column list follows the referenced table name, the primary key of the referenced table is used as the referenced column. This is why the primary key defines the default target for foreign keys aimed at its table: write the reference without a column list and it resolves to that one declared identity.

    8 / 20
  10. Identifying rows and relating tables

    Not every column can be pointed at. A foreign key must reference columns that either are a primary key or form a unique constraint, or are columns from a non-partial unique index, so the referenced columns always have an index that resolves a reference to at most one row.

    Target on the referenced side Valid? Why
    Primary key Yes Unique and not null
    Unique constraint Yes Unique among all rows
    Non-partial unique index Yes Unique across the whole table
    An ordinary non-unique index No Duplicate target rows stay possible
    A not-null column with no uniqueness No Rejecting nulls does not prevent duplicates

    The rule is about resolution, not speed. A reference is only meaningful when it lands on at most one row.

    9 / 20
  11. Quick check

    Which columns of the referenced table can a foreign key legitimately point at?

    1. AAny columns carrying an index that makes the lookup faster in practice

      An ordinary index makes lookups faster but still allows duplicate target rows, so the reference would not resolve to one row.

    2. BAny columns declared not null in the referenced table

      Rejecting nulls does not prevent duplicate values, so a not-null column is not by itself a valid target.

    3. CA primary key, a unique constraint, or a non-partial unique index

      Right. Only those three guarantee uniqueness on the referenced side, so a reference resolves to at most one row.

    10 / 20

  12. Identifying rows and relating tables

    Put the two rules together on a real design. Suppose a staff table has two columns that are each unique and never null: employee_no and email. Other tables must be able to reference staff without naming a column list, and tooling must be able to identify a row from one declared identity.

    The workable design declares one of the two columns the primary key and leaves the other as a unique constraint. The primary key becomes the default target that a bare reference resolves to; the other column stays a perfectly good identifier and can still be referenced explicitly by naming it.

    Two tempting alternatives fail:

    • Declaring both as primary keys is impossible, because a table can have at most one primary key.
    • Declaring both as plain unique constraints leaves no primary key, so a reference written without a column list has no default target to resolve to.
    11 / 20
  13. Quick check

    A table has two columns that are each unique and never null. Other tables must reference it without naming a column list, and one declared identity must identify a row. Which design works?

    1. ADeclare both columns as unique constraints and name the wanted column in every reference

      With no primary key at all, a reference that omits the column list has no default target to resolve to.

    2. BDeclare one column the primary key and leave the other as a unique constraint

      Right. A bare reference resolves to the primary key, so exactly one column has to hold that role while the other stays useful as a unique constraint.

    3. CDeclare the two columns together as a single primary key covering both

      A two-column primary key identifies rows only by the pair, so a reference would have to supply both columns instead of one identity.

    12 / 20

  14. Statements, clauses, expressions, and result sets

    A statement is one complete command handed to the server. The process of retrieving data, or the command that retrieves it, is called a query, and in SQL the SELECT command is used to specify queries.

    A statement is assembled from clauses, the labelled parts that each answer one question about the work.

    Clause The question it answers
    Select list Which values should the output contain?
    FROM table expression Where do the rows come from?
    Sort specification In what order are the rows presented?

    Splitting the work this way is what makes a query readable: each decision has one home, and changing the order of presentation never changes which values are produced.

    13 / 20
  15. Quick check

    Which part of a query states which values the output should contain?

    1. AThe select list

      Right. The select list is the clause that decides which columns or computed values the statement produces.

    2. BThe sort specification, which arranges the finished output

      A sort specification decides presentation order only, and never changes which values are produced.

    3. CThe table expression, which supplies the rows the query works from

      The table expression says where the rows come from, whether that is one table or a construct of joins and subqueries.

    14 / 20

  16. Statements, clauses, expressions, and result sets

    Two of those clauses stretch further than they first appear.

    FROM followed by one table name is a simple kind of table expression, while in general a table expression can be a complex construct of base tables, joins, and subqueries. So the same clause covers reading one table and combining several.

    A select list can select a subset of the available columns or make calculations using the columns, so one entry can add two numeric columns together instead of naming a single column. The calculation becomes an output column, and the set of rows returned is untouched.

    That division of labour decides where a computed value belongs: putting it in the table expression would risk changing the rows, and a sort specification only arranges them.

    15 / 20
  17. Quick check

    A report must show a value computed from two numeric columns, must not change which rows come back, and must expose that value as an output column. Where does the calculation belong?

    1. AIn the sort specification, so the value appears while ordering

      A sort specification only arranges rows; it adds no output column to the result.

    2. BIn the table expression, as a source combined with the base table

      The table expression decides where rows come from, so adding a source there risks changing which rows return.

    3. CIn the select list, as a computed entry beside the column references

      Right. The select list can hold calculations as well as plain column references, so it adds the output column without touching the rows.

    16 / 20

  18. Statements, clauses, expressions, and result sets

    Expressions are the smaller pieces inside those clauses that compute a single value, and they do not need a table underneath them. The table expression can be omitted entirely, which lets SELECT work as a calculator over constants and function results.

    A select list written as an asterisk means all columns that the table expression happens to provide, so such a query returns every row and every user-defined column of the named table.

    Written as What comes back
    A select list with no table expression The evaluated expressions alone, with no table read
    An asterisk over a table Every row and every user-defined column of it
    A named subset of columns Only the values that subset asks for

    What the statement hands back is the result set. How that result is presented depends on the client application: an interactive terminal draws a text table on the screen, while client libraries offer functions that extract individual values from the query result.

    17 / 20
  19. Quick check

    What does a SELECT statement written without any table expression do?

    1. AIt evaluates the expressions in its select list and returns them

      Right. Omitting the table expression turns the statement into a calculator over constants and function results.

    2. BIt fails with a syntax error until a source table is supplied

      The table expression is optional, so leaving it out is valid rather than an error.

    3. CIt reads every table that the current database contains

      No table is read at all when the table expression is absent, so nothing is scanned.

    18 / 20

  20. Key takeaways

    • A table is a named collection of rows, every row carries the same named columns, and each column is of a specific data type.
    • Column order inside a row is fixed, while the order of the rows in a table is not guaranteed and has to be requested with a sort.
    • A primary key is unique and not null, a table can have at most one of them, and a reference without a column list resolves to it.
    • A foreign key may reference only a primary key, a unique constraint, or a non-partial unique index.
    • Clauses divide a statement into labelled parts — select list, table expression, sort specification — and expressions compute the individual values inside them.
    • The result set is what the statement returns, and a query with no table expression simply evaluates its expressions.
    19 / 20
  21. Quick check

    Which summary keeps the roles straight?

    1. AA sort specification chooses the output values, and a unique index alone can be referenced

      A sort specification only orders rows, and a referenced index has to be unique and non-partial rather than any index at all.

    2. BThe select list chooses the values, the table expression supplies the rows, and one primary key per table is the default reference target

      Right. Each clause owns one decision, and the single primary key is what a reference written without a column list resolves to.

    3. CAn asterisk selects one column, and a table promises the order of its rows

      An asterisk means all the columns the table expression provides, and row order within a table is never guaranteed.

    20 / 20

  22. 9 quick checks · then the test

    In the app, finishing the quick checks opens this lesson’s 10-question test, and the ones you miss come back exactly when you’re about to forget them.

The whole course, on your phone

Lessons you can read, audio you can listen to on the way to work, and practice that remembers what you got wrong.