The Relational Database Model

Learn how relational databases organize data before you write your first query. See why organizations keep shared data in a database rather than a spreadsheet, what a database management system does and where SQL fits in. Read tables, rows and columns, choose sensible data types, and handle missing values (NULL) without the usual traps. Use primary and foreign keys to identify rows and connect tables, recognize one-to-many and many-to-many relationships, and read a database schema and its diagram to find where each fact is stored.

BeginnerLesson 1 of 6 in SQL Basics Course

What you will learn

  1. Describe why organizations keep shared data in relational databases, what a database management system does, and how SQL is used to work with it.
    • Explain why organizations use databases
      Distinguish data, a database and a database management system, and explain what a relational database does better than a shared spreadsheet or loose files.
    • Recognize database systems and the role of SQL
      Name common relational database systems, describe how applications connect to them, and explain what SQL is and how its statements are grouped.
  2. Use the vocabulary of tables, rows and columns to read data correctly, and explain the rules that make a table relational.
    • Describe the parts of a table
      Identify tables, rows, columns and values in sample data, and match the everyday words with their formal relational names.
    • Explain the rules that make a table relational
      Apply the rules of the relational model about rows, columns and values, and recognize where SQL tables and spreadsheets behave differently.
  3. Match each column to a suitable data type, avoid the common type mistakes with money, codes and dates, and work correctly with NULL.
    • Recognize the main SQL data types
      Identify the common numeric, text, date and Boolean types, read their size and precision settings, and know where database systems differ.
    • Choose a data type for real-world data
      Pick suitable types for money, quantities, codes, dates and names by asking how the values will be used, and avoid the mistakes that wrong types cause.
    • Work correctly with NULL
      Explain what NULL means, distinguish it from zero and empty text, and predict how NULL behaves in comparisons, calculations and constraints.
  4. Use primary keys to identify every row, foreign keys to link tables, and recognize the one-to-many, one-to-one and many-to-many relationships they create.
    • Identify candidate keys and the primary key
      Decide which columns or column combinations identify each row uniquely, and explain the rules a primary key must follow.
    • Choose between natural and surrogate keys
      Compare real-world identifiers with system-generated ones, judge which make good primary keys, and protect natural identifiers with unique constraints.
    • Link tables with foreign keys
      Explain how a foreign key refers to a row in another table, what referential integrity protects, and what happens when referenced rows change or are deleted.
    • Recognize one-to-many, one-to-one and many-to-many relationships
      Determine how many rows on each side of a link can be related, and show how foreign keys and junction tables represent each kind of relationship.
  5. Read a schema written as table definitions or drawn as a diagram, and use it with sample data to find where facts are stored and how tables connect.
    • Read a schema and its table definitions
      Distinguish a schema from the data it describes, read schema notation and CREATE TABLE statements, and interpret the constraints they declare.
    • Read a schema diagram
      Interpret the boxes, key markers, connecting lines and crow's foot symbols of a schema diagram, and state each relationship it shows in words.
    • Answer questions using a schema and sample data
      Locate where each fact is stored, follow keys between tables by hand, and use the schema's constraints to decide what data are allowed.

Relational Database Model study guide

5 chapters

1

What a database does

A shop can begin with a spreadsheet, but shared data soon raise harder questions: which customer details are current, who may change them, and what happens when a payment stops halfway through? A database system gives these questions a common home. Separate the stored facts from the software that manages them, then see how applications use SQL to ask for data and make changes. The same ideas support a small phone app and a large company’s reporting system.

1.1 Shared facts and reliable changes

A customer name, an order date and a price are data: recorded facts. A database is an organized collection of related data. A database management system, or DBMS, is the software that stores and manages that collection. PostgreSQL is a DBMS; a shop's store database is one collection it manages.

Store each fact where it belongs

Suppose a spreadsheet repeats Maria Garcia's phone number on all 14 of her sales. A phone-number change requires 14 edits. One missed cell leaves conflicting records. In a relational database, customers holds Maria's details once, under customer_id 1. Each sale records that identifier. Updating her phone in one customer row gives later lookups one current number.

A relational database organizes facts in tables. “Relational” comes from relation, the mathematical name for a table. E. F. Codd introduced the model in 1970. Its central separation is useful: users describe the data they want through tables and values; the DBMS handles how to find those data on disk.

Rules and shared access

A table has named columns, data types and constraints. A constraint is a rule the DBMS checks, such as “an order must refer to an existing customer.” These checks protect shared data when several applications use the same database. Type enforcement varies: PostgreSQL rejects text such as 'twelve' in a numeric price column, while ordinary SQLite tables have flexible types.

A DBMS also manages simultaneous users, permissions, backups and recovery. Two staff members can work on shared data without exchanging separate copies of a spreadsheet. Permissions can let a reporting user read sales while limiting who may change them. A backup and recovery process helps restore data after a failure.

Keep a group of changes together

A transaction treats several changes as one unit: all are saved or none are. Moving $200 between accounts requires subtracting it from checking and adding it to savings. If a failure interrupts the transfer before completion, the DBMS can undo the unfinished transaction. Saving only the subtraction would leave an incorrect balance.

A spreadsheet remains useful for small calculations and flexible layouts. A database provides a defined structure for shared records and rules. An Excel worksheet has a fixed limit of 1,048,576 rows; databases routinely manage much larger collections, subject to storage, hardware and product limits.

Different data and different jobs

Structured data fit named columns shared by every row. Semi-structured data, such as JSON documents, can have different fields in different records. Unstructured data, such as audio or free-form email, lack that fixed tabular layout. Organizations often combine relational databases with document stores, key-value stores or file storage.

The workload matters too. A transactional system, also called OLTP, records everyday events through many small reads and writes: an order, a payment, an address change. An analytical system, or OLAP, reads many stored records to answer questions such as “How did monthly sales vary by region?” Both can use relational tables and keys.

Key Takeaways

  • A database holds related data; a DBMS manages it.
  • Relational data are organized in tables, with rules checked by the DBMS.
  • A transaction saves or undoes a group of changes together.
  • Shared customer details can be updated in one place and found through an identifier.
  • Transactional work records events; analytical work summarizes stored data.

1.2 SQL, database products and applications

SQL, short for Structured Query Language, is a language. PostgreSQL, MySQL, SQLite, Microsoft SQL Server and Oracle Database are products that use it. SQL Server is one DBMS, not another name for SQL itself.

How an application reaches the data

In a client-server system, a server program manages the database. A client, such as a website, reporting tool or query editor, sends requests to that server. PostgreSQL, MySQL, SQL Server and Oracle commonly work this way. Tools such as psql, pgAdmin, DBeaver and SQL Server Management Studio let people inspect databases and send requests.

An embedded engine runs inside an application. SQLite uses a library and an ordinary database file, such as store.db, without a separate database server. It is common in phones, browsers and desktop apps. A managed cloud service, such as Azure SQL Database, Amazon RDS or Google Cloud SQL, lets a provider run the database servers. “Managed” describes who operates the service; it does not replace tables and keys with a different model.

One DBMS installation can manage several databases, such as store and payroll. A connection selects the database to use, subject to permissions.

Say what result you want

SQL is declarative: it describes the required result while the DBMS chooses how to obtain it. Read this statement:

SELECT first_name, city
FROM customers
WHERE state = 'TX';

It asks for first names and cities from customer rows whose state is TX. It says nothing about which disk page to read first. Capitalized keywords make the statement easier to scan; select and SELECT mean the same thing. A semicolon normally ends a statement.

Recognize the statement's job
GroupPurposeExamples
Data definition, DDLDefine or change structureCREATE TABLE, ALTER TABLE, DROP TABLE
Data manipulation, DMLRead or change rowsSELECT, INSERT, UPDATE, DELETE
Data control, DCLManage permissionsGRANT, REVOKE
Transaction controlSave or undo a transactionCOMMIT, ROLLBACK

Some books put SELECT in a separate data query language group. The useful distinction is the statement's actual job: adding a column changes structure; adding a customer changes data.

SQL became an ANSI standard in 1986 and is standardized internationally as ISO/IEC 9075. Products add their own dialects. A ten-row limit appears as LIMIT 10 in SQLite, PostgreSQL and MySQL, TOP 10 in SQL Server, or FETCH FIRST 10 ROWS ONLY in standard SQL and Oracle.

Read text and other database objects

Text literals use single quotes: 'TX'. Standard SQL uses double quotes for identifiers, such as column names. An apostrophe inside text is doubled: 'O''Brien' represents O'Brien.

A view is a saved query used like a table; an ordinary view has no stored rows of its own. An index is a lookup structure that can help find rows quickly. Most systems automatically index primary keys. Stored procedures and functions are saved code that can be run by name.

Key Takeaways

  • SQL describes a wanted result; the DBMS chooses how to get it.
  • Client-server systems accept requests through a server; SQLite is embedded in an application.
  • DDL changes structure, while DML reads or changes rows.
  • Single quotes mark text; an apostrophe within text is doubled.
  • A view saves a query; an index supports faster lookups.
  • SQL dialects share the relational ideas but differ in some syntax.
2

Read a table correctly

A table gives each kind of record a clear shape: rows describe individual things, and columns describe their properties. Read the shape before interpreting a value. Then distinguish the table’s logical rules from a spreadsheet’s layout: position does not identify a record, a list of phone numbers is more than one value, and a total row has a different meaning from a sale. These distinctions make later work with keys and schemas much easier.

2.1 Rows, columns and values

A table stores facts about one kind of thing. Each row in customers describes one customer; each column holds one property. Their intersection holds a value.

Read across one record

Here are selected customer columns:

customer_idfirst_namelast_namecitystatezip_code
1MariaGarciaAustinTX78701
2JamesWilsonDenverCO80202
3AishaJohnsonBostonMA02108
4WeiChenSeattleWA98101

Find customer_id 4, then read city: Wei's city is Seattle. To find who lives in Denver, read the name in Denver's row: James Wilson. A neighboring row describes a different customer.

The full table has eight columns: customer_id, first_name, last_name, email, phone, city, state and zip_code. James's phone is NULL: the value is missing, but his row still has the phone column.

Match the vocabulary
Everyday wordFormal relational wordOther common word
TableRelation—
RowTupleRecord
ColumnAttributeField

A tuple is a whole row, not one cell. An attribute names a property shared by all rows. “Record 4” might mean an identifier or a display position; check which, because positions can change.

Count the shape

Degree counts columns; table cardinality counts rows. The full table has degree 8 and cardinality 4. The display above shows six columns without changing the table's degree.

Adding a customer raises cardinality to 5; degree stays 8. Adding birth_date raises degree to 9 and gives every row a place for that value, even when it is missing. A new customer adds a row, not a column.

Relationship cardinality, such as one-to-many, describes allowed links rather than a table's row count.

Read qualified names

Column names are unique within a table. orders.customer_id and customers.customer_id distinguish identically named columns in different tables: the dot separates table and column names.

snake_case uses lowercase words separated by underscores, as in zip_code. Names with spaces need quoting in SQL. Either singular or plural table names can work; use a consistent convention.

Key Takeaways

  • A row describes one item; a column describes one property.
  • Relation, tuple and attribute mean table, row and column.
  • Degree counts columns; table cardinality counts rows.
  • A table-qualified name identifies which table a column belongs to.

2.2 The rules behind the grid

A relational table has a logical structure beyond its rectangular appearance. In the formal model it is a set of rows. Sets contain no duplicate members and have no order. Columns are identified by name, so moving a column in a display does not change the fact it represents.

Identity does not come from position

A DBMS can return rows in a different order after updates, deletions or a change in how it reads storage. “The third row” is not a lasting way to identify a customer. customer_id 3 still identifies Aisha even when her row appears first. A query that needs a particular order asks for it with ORDER BY.

SQL tables differ from formal relations: without a primary key or another suitable uniqueness constraint, they can contain identical rows. Two copies of ('Coffee mug', 12.50) give no distinguishing value in those columns. A primary key gives each row a unique identifier and prevents complete duplicate rows.

One column, one domain

A domain is the set of values allowed in a column. A quantity has a whole-number type and may also need a rule that it must be positive. A state code is text, but not every text value is a valid state code. Data types and constraints describe the allowed values to the DBMS.

All rows share the same columns. One order cannot acquire an extra gift-note column just for itself. The table can have a gift_note column for every order, with NULL where no note was recorded. Optional facts still have a defined place.

Keep individual values separate

An atomic value is one value for the column's purpose. A phone cell containing “512-555-0147, 512-555-0199” holds a list of two numbers. Finding, checking or removing just one number becomes awkward. A customer_phones table can give each phone number its own row, with customer_id showing whose number it is.

Atomic does not mean that every text value must be split into its smallest pieces. A city name can contain several words and remain one city value. The question is whether the cell stores one fact of the kind the column represents, or a collection that should be handled separately.

Read a spreadsheet export critically

A sheet of sales may include a repeated header halfway down, a bottom row labeled “TOTAL,” and a price written as “12.50 (sale).” These are useful layout choices for a person, but they mix different kinds of content in the same columns.

To read it as a relational table:

  1. Treat the column names as the header, not as sale records.
  2. Keep each data row about one sale; calculate the total from those rows.
  3. Store the numeric price separately from a sale note.
  4. Give each sale a key so its row can be identified.

A total row mixed with sales could be counted as another sale or added to the total again. A note mixed into a numeric price prevents ordinary numeric operations.

Logical tables and physical storage

A table is the user's logical view. The DBMS may store its data in files, pages and indexes arranged for efficient access. Data independence means that changes to that physical arrangement need not change the table names, column meanings or requests used by applications.

Key Takeaways

  • A formal relation has distinct, unordered rows; SQL needs constraints to prevent duplicates.
  • Row order must be requested with ORDER BY.
  • A column’s domain describes its allowed values.
  • Each cell holds one value for its column’s purpose.
  • Every row has the same columns, including places for missing values.
3

Choose types and interpret missing data

A column’s type affects what can be stored, how values sort, and which calculations make sense. Digits may describe a count or a code; those uses call for different types. Money needs exact storage, while measurements can often use approximate values. Missing facts need their own treatment as NULL. Learn these choices alongside the important product differences, especially SQLite’s flexible storage and SQL’s handling of unknown comparisons.

3.1 The main SQL data types

A data type tells a DBMS what kind of value a column holds and how to work with it. Numeric addition, text comparison and date ordering are different operations. A familiar type name can also behave differently across database products.

Numbers: whole, exact and approximate
KindCommon typesSuitable use
Whole numbersINTEGER, SMALLINT, BIGINTCounts, quantities and integer identifiers
Exact decimalsDECIMAL(p, s), NUMERIC(p, s)Money and other exact decimal amounts
Approximate numbersREAL, FLOAT, DOUBLE PRECISIONMeasurements with acceptable rounding differences

In PostgreSQL, MySQL and SQL Server, INTEGER ranges from −2,147,483,648 to 2,147,483,647. BIGINT reaches 9,223,372,036,854,775,807; SQLite's integer storage can reach that range too.

For decimals, precision is the total number of digits and scale is the number after the decimal point. DECIMAL(8, 2) leaves six digits before the point: its maximum is 999999.99. The price 12.50 fits; 1234567.00 does not. PostgreSQL, MySQL, SQL Server and Oracle provide exact decimal storage. SQLite accepts this declaration but does not enforce its precision or scale, and can store fractions as binary floating point.

Floating point approximates many decimal fractions. In double precision, adding 0.1 and 0.2 gives 0.30000000000000004. SQLite treats these decimal literals as floating point. PostgreSQL treats bare decimal literals as exact numeric, so the same written calculation there can be exact; explicit double-precision values show the approximation.

Text, dates and flags

CHAR(n) is fixed-length text; PostgreSQL and SQL Server pad shorter values with spaces. VARCHAR(n) allows varying lengths up to a limit. SQLite ignores both length settings and does not pad. TEXT holds long text in SQLite, PostgreSQL and MySQL. SQL Server uses VARCHAR(MAX) or NVARCHAR(MAX) for this job; its older TEXT type is deprecated.

A DATE holds a calendar date, a TIME a time of day, and standard SQL TIMESTAMP a date and time. Write dates in year-month-day form, such as '2026-03-02', to avoid confusing March 2 with February 3. Typed dates have an internal storage format; the application chooses their display format. SQLite has no dedicated date type and commonly stores ISO date text. SQL Server uses DATETIME2 for date and time: its TIMESTAMP means ROWVERSION, a binary version counter.

A BOOLEAN represents TRUE or FALSE, or NULL when missing. PostgreSQL has a Boolean type; SQL Server uses BIT, MySQL treats BOOLEAN as a small integer, and SQLite stores the flags as 1 and 0. Binary types such as BLOB or PostgreSQL's BYTEA store bytes, including small images. Larger files are often stored separately with a path or URL in a table.

SQLite's type affinity

In ordinary SQLite tables, a declared type is a preference called type affinity. An INTEGER column converts '42' to the number 42, but can retain 'abc' as text. A SQLite STRICT table rejects text that cannot become a valid integer.

Key Takeaways

  • Integers hold whole numbers; exact decimals and floating point serve different needs.
  • Precision counts all digits; scale counts fractional digits.
  • ISO date text uses year-month-day order.
  • Text lengths, Boolean storage and date types have dialect differences.
  • SQLite affinity is flexible; STRICT tables enforce their supported types.
  • SQL Server’s TIMESTAMP is a row version, not a date and time.

3.2 Choose a type from the value’s job

Start with what a value means and how it will be used. A ZIP code contains digits, but nobody adds ZIP codes to get a meaningful total. A quantity also contains digits, and adding quantities is useful. Appearance alone is a poor guide to type.

Ask five questions
  1. What are typical values, and what extremes must fit?
  2. Will the values be used in arithmetic?
  3. Must they be exact, or is approximation acceptable?
  4. How must they sort and compare?
  5. What size fits realistic future values?
Money and measurements

Money needs exact values. In PostgreSQL, MySQL and SQL Server, a price can use DECIMAL(8, 2). Three items at $12.50 cost exactly $37.50. Binary floating-point storage can leave tiny errors after repeated additions, making exact comparisons unreliable. In SQLite, declaring DECIMAL does not supply exact decimal storage; use integer cents for exact amounts, so $12.50 is stored as 1250.

A measurement such as weight can use REAL when small rounding differences are acceptable. Choose the unit as part of the column's meaning: weight_lb makes pounds visible in its name. A numeric type alone does not record that unit.

Currency also needs a meaning. If a table mixes currencies, add currency_code, such as USD, EUR or JPY. Decimal places vary by currency, and unlike currencies must be converted before their amounts can be added.

Codes and names are text

Use text for ZIP codes, phone numbers, account numbers and stock codes. The Boston ZIP code '02108' loses its leading zero when converted to an integer. VARCHAR(10) can also hold ZIP+4, such as '02108-1234'. Phone numbers may contain a plus sign, spaces and hyphens. These characters are part of an identifier's representation, not arithmetic signs.

Allow room for real names and addresses. “Christopher Montgomery” has 22 characters, so VARCHAR(10) is too short. PostgreSQL and SQL Server reject it; MySQL rejects it in strict mode and may truncate otherwise. SQLite stores it because declared text lengths are ignored. A generous varying-length field avoids rejecting ordinary names without reserving its maximum length for every row.

Sorting reveals a wrong choice

Text sorting compares characters. Numbers stored as text can appear in the order '1', '10', '2', '25', '3'. A numeric column sorts those values numerically. Choosing text for every field shifts checking and conversion work onto later calculations.

Dates have a similar trap. US-style date text puts '12/01/2025' after '03/02/2026' in text order, although December 2025 is earlier. Use a date type, or consistently formatted ISO text in SQLite, so calendar order is preserved.

Read a product's types together

A product can use product_id INTEGER, sku VARCHAR(20), name VARCHAR(100), price DECIMAL(8, 2), weight_lb REAL, in_stock BOOLEAN and added_on DATE. Each type follows a job: identification, code storage, a name, exact money, measurement, a flag or a date. For SQLite, store the price as integer cents and the date as ISO text.

Key Takeaways

  • Choose types from meaning, arithmetic, exactness, ordering and realistic size.
  • Store codes as text to keep leading zeros and punctuation.
  • Use exact decimal money where supported, and integer cents in SQLite.
  • A numeric amount needs a currency and a measurement needs a unit.
  • Text storage gives text ordering, even when all the characters are digits.

3.3 NULL and unknown results

NULL marks a missing value. It is different from zero, empty text '' and the text 'NULL'. A known discount of 0 means no discount; a NULL discount means the amount is not recorded. A nullable column allows missing data, while NOT NULL requires a value.

Missing has more than one meaning

James Wilson has no recorded phone number. Order 102 has no shipping date because it has not shipped yet. A company customer may have no applicable last name. All can be represented by NULL, but NULL does not record which reason applies. A data dictionary should state each column's meaning.

Empty text is a present text value in PostgreSQL and SQLite. Oracle currently treats empty text as NULL. Query tools may display both as an empty-looking cell, so appearance alone does not tell them apart.

Comparisons can be unknown

SQL comparisons have three possible results: TRUE, FALSE and UNKNOWN. A comparison involving NULL, including NULL = NULL, is UNKNOWN. Two missing facts are not known to have the same value.

A WHERE clause keeps only TRUE results. Read these conditions:

  • phone IS NULL finds missing phone numbers.
  • phone IS NOT NULL finds recorded phone numbers.
  • phone = NULL yields UNKNOWN and finds no rows.

Negating a comparison does not recover a missing value. Add Daniel Brown, whose state is NULL, to the four store customers. The condition state <> 'TX' keeps CO, MA and WA: three rows. Daniel is excluded because his state comparison is UNKNOWN. To include missing states too, the condition is state <> 'TX' OR state IS NULL.

Combine conditions carefully

Think of UNKNOWN as “could be TRUE or FALSE.” A result is settled only if both possibilities give the same outcome.

ExpressionResultReason
TRUE AND UNKNOWNUNKNOWNThe second part decides whether both are true.
FALSE AND UNKNOWNFALSEOne false part already defeats AND.
TRUE OR UNKNOWNTRUEOne true part already satisfies OR.
FALSE OR UNKNOWNUNKNOWNThe second part decides OR.
NOT UNKNOWNUNKNOWNNegation cannot supply the missing fact.
Calculations and summaries

Ordinary arithmetic with NULL gives NULL: 5 + NULL is NULL. A line price multiplied by a missing quantity is missing too, not zero. Joining text with || and NULL gives NULL in PostgreSQL and SQLite; Oracle's concatenation treats NULL as empty text.

Summary functions usually skip NULL inputs. With five customers, including James and Daniel without phone numbers, COUNT(*) counts all five rows. COUNT(phone) counts the three recorded phones. The average of 4, NULL and 2 is 3, because the two known numbers are divided by two; treating NULL as zero would incorrectly give 2.

Use NOT NULL for facts that must be present, such as an order date. It does not force a positive number or nonempty text: those are separate rules. Primary keys require non-NULL identity; ordinary SQLite tables have a historical exception for some primary key declarations, so explicit NOT NULL matters there.

Key Takeaways

  • NULL marks missing information; 0 and empty text carry different meanings.
  • Test missing values with IS NULL or IS NOT NULL.
  • Comparisons involving NULL produce UNKNOWN; WHERE keeps only TRUE.
  • AND, OR and NOT must account for UNKNOWN.
  • Ordinary arithmetic with NULL produces NULL.
  • COUNT(*) counts rows; COUNT(column) counts non-NULL entries.
  • Document why NULL is allowed in each column.
4

Identify and connect records

Keys answer two different questions: “Which row is this?” and “Which related row does it refer to?” A primary key gives a table a main identifier, while a foreign key carries a reference. Test possible identifiers against future data, not just a small sample. Then read links in both directions, including whether a link is optional. Composite keys and junction tables extend the same ideas to records identified by combinations and to many-to-many relationships.

4.1 Candidate keys and primary keys

A key identifies a row through its values. Names can repeat; customer identifiers distinguish records so they can be read, changed or linked.

Test uniqueness and minimality

A superkey is a column or combination that uniquely identifies a row. A candidate key is a minimal superkey: removing any column loses that guarantee. Choose one candidate as the primary key; the others are alternate keys.

Suppose employee_id, ssn and email are each required and unique. Each is a candidate key. (employee_id, department) is a superkey but not a candidate: employee_id alone identifies the employee. A repeated last name fails the uniqueness test.

TermTest
SuperkeyDoes the combination identify a row?
Candidate keyIs it unique with no unnecessary column?
Primary keyWhich candidate is the main identifier?
Alternate keyWhich other candidate remains available?

Four customers with different last names do not establish a key: a fifth may share a name. Uniqueness must hold for all allowed future data. A repeat disproves a proposed key; a sample without repeats still needs a supporting business rule.

Read the declaration

A table has at most one primary key. Its values are unique and its columns must be non-NULL. Stable values avoid repeated changes to references. Look for PRIMARY KEY: neither a column's name nor its position declares it.

If customer 1 exists, another customer with key 1 is rejected. An omitted key needs a default or generated value. SQLite's INTEGER PRIMARY KEY generates an integer when omitted or given NULL. Some other primary key declarations in ordinary SQLite tables historically allow NULL; explicit NOT NULL, a STRICT table or the integer-primary-key form closes that gap.

Read a composite key

In enrollments(student_id, course_id, term, grade), a student can take several courses and retake one in another term. (student_id, course_id, term) identifies one enrollment: one composite primary key, not three separate primary keys.

Individual components may repeat; the complete combination cannot. Most DBMSs create a primary-key index for lookup, but the key does not guarantee query output order.

Key Takeaways

  • A candidate key is a minimal superkey.
  • One candidate is the primary key; the others are alternate keys.
  • A key’s uniqueness must hold for allowed future data.
  • A primary key is unique and non-NULL and may span several columns.
  • The declaration establishes the key, not its name or position.

4.2 Natural and generated identifiers

A natural key comes from real-world data, such as a vehicle's VIN, a book edition's ISBN or a state code. A surrogate key exists only to identify a row, often as a generated integer or UUID.

Choose an identifier that lasts

Prefer unique, present, stable, compact values that are safe to share. Names repeat; phones and emails change or are shared. Social Security numbers are sensitive and unavailable for some customers; using them in referring tables spreads that information.

A generated customer_id lets Maria keep identifier 1 when her contact details change. A natural state_code, such as TX, can work well because it is compact, standardized and useful in address records.

Protect business identifiers separately

The same person can register twice and receive two surrogate IDs. The IDs distinguish rows; they do not detect duplicate people.

If email must identify every account, use NOT NULL UNIQUE. UNIQUE alone permits several NULLs in PostgreSQL, SQLite and MySQL. SQL Server normally permits one NULL in a single-column unique constraint. Presence and uniqueness are separate rules.

The required, unique email is an alternate key. Changing it leaves the surrogate customer number in existing orders unchanged. Changing a referenced primary key requires its child references to remain consistent too.

Recognize generated-key syntax
SystemCommon generated integer form
Standard SQL, PostgreSQL, OracleGENERATED ALWAYS AS IDENTITY
MySQLAUTO_INCREMENT
SQL ServerIDENTITY(1,1)
SQLiteINTEGER PRIMARY KEY

PostgreSQL also has the older SERIAL form. Deletions, failed inserts and canceled work can leave gaps. IDs 1, 2 and 4 label three rows, not four. Renumbering to close gaps can break references.

Recognize UUIDs

A UUID is a 128-bit identifier, commonly written as 36 characters with hyphens: 7c9e6679-7425-40de-944b-e07fc1f90ae7. Computers can generate them independently with very low collision risk, useful when records from several places will be combined.

UUIDs take more space and are harder to read than small integers. Choose according to how records are created and referenced. Either kind of key is a label: its maximum value is not a row count, and its order need not show event times.

Key Takeaways

  • Natural keys come from real-world identifiers; surrogate keys exist for row identity.
  • Prefer primary keys that are stable, compact, present and safe to share.
  • A surrogate key does not prevent duplicate real-world records.
  • NOT NULL UNIQUE can protect a required alternate identifier.
  • Generated ID gaps are normal; IDs are labels, not counts.
  • UUIDs allow independent identifier generation with very low collision risk.

4.3 Foreign keys and valid references

A foreign key is a column or group of columns that refers to a primary key or another suitable unique key. The table carrying the reference is the child; the table it points to is the parent. A non-NULL foreign key must match an existing parent key when the constraint is enforced.

Follow a value across tables
order_idcustomer_idorder_dateshipped_date
10112026-03-022026-03-04
10222026-03-05NULL
10312026-03-092026-03-10

orders.customer_id refers to customers.customer_id. Order 102 points to customer 2, James Wilson. Orders 101 and 103 both point to customer 1, Maria Garcia. Repetition is allowed in the foreign key; the referenced parent key is unique.

This rule is referential integrity. An order for customer 99 is rejected if customer 99 does not exist. Otherwise it would be an orphan: a child with no matching parent. A name alone creates no constraint. A foreign key named placed_by can still refer to customer_id; the declared reference creates the link, with matching types for the key columns.

Optional or required

A nullable coupon_id can be NULL when an order has no coupon. A customer_id declared NOT NULL requires every order to have a customer reference, and the foreign key requires that customer to exist. These two constraints work together: one requires a value and the other checks the reference.

Foreign keys need not cross table boundaries. In employees(employee_id, name, manager_id), manager_id can refer to employee_id in the same table. The chief executive can have a NULL manager reference.

Parent changes need a rule
ActionEffect when a referenced parent is deleted
NO ACTION or RESTRICTRefuses the deletion while references remain, subject to constraint-check timing
CASCADEDeletes the referring child rows too
SET NULLKeeps children and clears their reference; the column must allow NULL

With the default action, customer 1 cannot be deleted while orders 101 and 103 still refer to her. Cascading from an order to its lines can make sense because those lines belong to that order. ON UPDATE specifies the corresponding behavior when a parent key changes. Cascading does not mean that deleting a child deletes its parent.

Composite references and enforcement

If an order line is identified by (order_id, product_id), a shipment referring to that line needs both columns. The combination must match an existing line. Matching an order and a product separately is insufficient: that product may never have appeared in that order. A required composite reference declares all its columns NOT NULL.

PostgreSQL, SQL Server, Oracle and MySQL's usual InnoDB engine enforce declared foreign keys. In SQLite, enable and check foreign-key enforcement for each connection with PRAGMA foreign_keys = ON; before relying on it. A declared but disabled constraint cannot protect the rows. Foreign keys also do not combine query results by themselves; a query must explicitly follow the link, usually through a join.

Key Takeaways

  • A foreign key’s non-NULL value must match an existing referenced key.
  • Foreign key values can repeat; parent key values are unique.
  • NOT NULL makes the link required.
  • Referential actions control child rows when a parent changes.
  • A composite reference must match the full parent-key combination.
  • SQLite foreign-key enforcement must be enabled for each connection.

4.4 Read relationship sizes in both directions

To identify a relationship, ask two questions: “For one row here, how many rows there can be linked?” and then the reverse. Include the minimum as well as the maximum. Today's sample shows what has happened; the constraints describe what is allowed.

One customer, many orders

A customer can place zero or more orders. Each store order belongs to exactly one customer because orders.customer_id is a non-NULL foreign key. This is one-to-many. The foreign key belongs in orders, the many side: each order stores one customer reference.

Maria has orders 101 and 103; James has order 102. Aisha and Wei have none. Their absence from orders is valid. A foreign key requires a parent for each child, but does not require every parent to have a child.

One-to-one needs uniqueness too

In user_profiles(user_id, bio, photo_url), let user_id be both the primary key and a foreign key to users. Every profile refers to one user, and a user can have at most one profile because the profile key cannot repeat. A user may have no profile yet.

A foreign key without uniqueness would allow several profiles for the same user, giving one-to-many. The uniqueness constraint changes the maximum. Such separate profile tables can keep optional or sensitive details apart from the main user record.

Many-to-many uses a table of pairs

An order can contain several products, and a product can appear in several orders. A junction table, also called a bridge, linking or associative table, records each pairing:

order_idproduct_idquantityunit_price
10111212.50
1011218.99
10213134.00
10311412.50

order_id refers to orders; product_id refers to products. The composite primary key (order_id, product_id) allows the same product in different orders but prevents the same pair appearing twice. Two one-to-many links implement the many-to-many relationship.

quantity and unit_price belong to the pairing. They describe how much of that product was sold in that order and the price charged then. A current product price may change later; it must not rewrite the historical charge.

For order 101, the two line amounts are two mugs at $12.50, giving $25.00, and one charger at $8.99. Together they cost $33.99. The quantity says how many mugs were bought; storing two duplicate mug lines would conflict with this table's chosen key.

Avoid lists and fixed slots

A product_ids cell containing “11,12” hides several references inside one text value. Columns such as product1, product2 and product3 impose a fixed limit and leave unused slots. A junction table adds a row for each additional pairing and lets the DBMS check each reference separately.

A self-referencing relationship uses the same pattern inside one table: many employees can refer to the same manager through manager_id. The manager is also an employee row. Read each link as a role, so employee identity and manager reference stay distinct.

Key Takeaways

  • Read the allowed minimum and maximum in each direction.
  • One-to-many stores the foreign key on the many side.
  • A unique foreign key limits a relationship to at most one child per parent.
  • A junction table represents many-to-many links through rows of pairs.
  • Facts such as quantity and sale price can belong to a pairing.
  • A self-reference links roles within one table.
5

Read a schema and follow its links

A schema records the structure that gives tables their meaning: column types, identifiers, references and constraints. A diagram makes those links visible, while a table definition states the rules precisely. Use both forms to find the path from a question to its answer, then use actual rows to supply the values. Keep structure and current data separate: knowing that orders refer to customers does not tell you which customers have placed orders today.

5.1 Structure, current data and constraints

A schema describes tables, columns, data types and constraints. An instance is the data stored at a particular moment. Adding an order changes the instance; adding a new column changes the schema. The schema tells what can be stored, while the rows tell what is stored now.

Read a short description

customers(customer_id, first_name, last_name, email, phone, city, state, zip_code) lists a table and its columns. Notes may underline primary keys or mark them PK, and mark references FK. For example, orders(order_id PK, customer_id FK → customers, order_date, shipped_date) identifies the main key and the customer link.

Read a full table definition
CREATE TABLE orders (
  order_id INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
  order_date DATE NOT NULL,
  shipped_date DATE
);

Read one column at a time. order_id is the integer primary key. customer_id is required and must refer to a customer. order_date is required. shipped_date may be NULL. This definition gives the allowed structure, not a list of existing orders.

Constraints answer different questions:

ConstraintWhat it checks
PRIMARY KEYA unique row identifier, possibly composite
NOT NULLA value is present
UNIQUERepeated non-NULL values are forbidden; NULL handling varies
REFERENCESA reference matches a parent key
CHECKA condition must not be FALSE
DEFAULTSupplies a value when one is omitted

A default is not a replacement for a supplied invalid value. If status has DEFAULT 'pending', omitting status supplies 'pending'; a supplied value still has to meet the column's other rules.

Combine rules for an order line
CREATE TABLE order_items (
  order_id INTEGER NOT NULL REFERENCES orders (order_id),
  product_id INTEGER NOT NULL REFERENCES products (product_id),
  quantity INTEGER NOT NULL CHECK (quantity > 0),
  unit_price DECIMAL(8, 2) NOT NULL,
  PRIMARY KEY (order_id, product_id)
);

The primary key at the bottom uses two columns. A second line for the same order and product fails. Quantity 0 fails the check. A missing quantity fails NOT NULL: the check alone would allow NULL because NULL > 0 is UNKNOWN, not FALSE. Explicit NOT NULL on both key parts also avoids SQLite's historical nullable-composite-key exception. In SQLite, use integer cents for an exact unit_price; the decimal declaration alone does not provide exact storage.

Find the schema and its meanings

In the SQLite shell, .schema orders displays the definition; in PostgreSQL's psql, \d orders describes it. INFORMATION_SCHEMA views list structural metadata in PostgreSQL, MySQL and SQL Server. SQLite lists objects in sqlite_schema, and graphical tools show tables and columns in a tree.

“Schema” also names a namespace inside systems such as PostgreSQL and SQL Server. sales.orders means the orders table in the sales schema. A data dictionary supplies meanings the structure cannot express, such as the price currency or whether a missing shipping date means “not shipped.” To see rows, a query such as SELECT * FROM orders; reads the current instance.

Key Takeaways

  • A schema is structure; an instance is the data at one moment.
  • Read a column’s type and all its constraints together.
  • A required positive number needs both NOT NULL and a positive-value check.
  • A composite primary key is declared over the whole combination.
  • A data dictionary records meanings and units beyond the schema.

5.2 Read the ends of a schema line

A schema diagram draws each table as a box. The title names the table; the contents list columns and often types. PK marks primary keys, and FK marks foreign keys. Relationship lines show which foreign key refers to which parent key.

First identify the kind of line

Some diagrams use an arrow from a foreign key to its referenced key. An arrow from orders.customer_id to customers.customer_id describes the reference's direction. Other tools use end symbols to describe how many rows can be linked. Check the diagram's legend: an arrow direction and a relationship's size are different information.

Read crow's foot symbols

In crow's foot notation, a bar means one, a circle means zero, and a three-pronged foot means many. Each line end states a minimum and maximum. The symbol nearest the table gives the maximum; the other gives the minimum.

End symbolsAllowed number of rows at that end
Bar and barExactly one
Circle and barZero or one
Bar and crow's footOne or more
Circle and crow's footZero or more

When reading from one table, look at the symbols beside the other table. Those symbols describe how many rows there can match your one starting row.

Work through customers and orders

The store line has exactly-one symbols beside customers and zero-or-more symbols beside orders.

  1. Start with one customer. Look at the orders end: the customer can have zero or more orders.
  2. Start with one order. Look at the customers end: the order belongs to exactly one customer.
  3. Check the definition: the non-NULL foreign key is in orders, so it is the many side, and each order needs a valid customer.

The crow's foot is next to the table holding the repeating foreign key. Reading the near end while starting from that same table reverses the meaning. A nullable customer reference would change the customers end to zero-or-one; it would not limit each customer to one order.

Recognize a junction table

The store has one-to-many links from orders to order_items and from products to order_items. Both many ends meet at order_items. Its two foreign keys form the primary key. This structure lets an order contain several products and a product appear in several orders.

The diagram describes allowed connections, not today's counts. It permits Maria to have several orders and Aisha to have none. To learn how many each actually has, read the rows. A parent-to-child minimum of one may express an additional business rule; a foreign key by itself does not require a parent to have children.

Recognize related diagram styles

An entity-relationship diagram made during design may show business entities before tables exist. Chen-style diagrams use ovals for attributes and diamonds for relationships. A schema diagram shows the actual tables and their declared keys. Both help communicate structure, but their symbols need to be read according to their own legend.

Key Takeaways

  • A schema diagram shows tables and declared key links.
  • At each line end, read the minimum and maximum using the legend.
  • The far end describes the rows linked to one starting row.
  • The many end of a one-to-many link holds the repeating foreign key.
  • Two many ends meeting at a table can reveal a junction table.
  • A diagram gives allowed connections; rows give actual counts.

5.3 Find facts by following keys

Locate each requested fact and follow the keys connecting it to the starting record. Names can repeat or change; match key values instead.

Find an order's customer

“Where does the customer who placed order 102 live?” follows this path:

  1. Find order 102 by orders.order_id.
  2. Read its customer_id: 2.
  3. Find customer 2 by customers.customer_id.
  4. Read customers.city: Denver.

Order number 102 is not the customer identifier. SQL joins automate these key matches; display positions do not connect the records.

Find products and a historical total

Order 101 has these order_items rows. Follow each product_id to products for its name:

product_idquantityunit_priceProduct name
11212.50Coffee mug
1218.99Phone charger

Use the recorded line price for the amount charged:

  • Two mugs at $12.50 cost $25.00.
  • One charger at $8.99 costs $8.99.
  • Total: $33.99.

Today's product price could misstate an old order's cost. Order 102 has one lamp at $34.00; order 103 has four mugs at $12.50, totaling $50.00.

Interpret missing values and rules

Order 102's shipping date is NULL, documented here as “not shipped.” Test it with IS NULL, not equality to NULL.

Read every relevant constraint when judging a change:

  • A line for order 104 fails if that order does not exist.
  • Another line with key (101, 11) fails because the pair exists.
  • Quantity 0 fails the positive-quantity check.
  • Default foreign-key behavior blocks deleting product 11 while lines reference it.

An unused key does not make a row valid when its reference is missing.

Identify the new rows

A returning customer buying two different existing products adds one orders row and two order_items rows. The customer and products already exist. Offering a new product adds one products row, without requiring an order.

Key Takeaways

  • Locate each requested fact before following the key path.
  • Match foreign key values to referenced keys, not names or row positions.
  • Use the sale-line price for historical order totals.
  • Check every applicable constraint when judging a proposed change.
  • A new event adds rows to the tables whose facts it creates.

Relational Database Model examples

5 Walkthroughs

1

From shared records to database requests

12 steps
See how a DBMS keeps related records usable, then follow a request from an application to the database.
  1. 1
    IntroductionWho looks after shared facts?

    A shop's sales, support and management teams use the same customer records. A database holds such shared facts, and software called a DBMS manages them.

    Follow how a database system shares these facts, keeps changes consistent (the job of a transaction) and answers application requests.

  2. 2
    ExplanationSeparate collection from software

    Data are recorded facts. A database is an organized collection of related data; a DBMS is the software managing it.

    The shop's customers and orders are data. PostgreSQL stores them, checks rules and answers requests.

  3. 3
    ExampleUpdate one phone number

    Maria's phone appears on 14 spreadsheet sales. A missed edit leaves conflicting copies.

    Store her phone once under customer_id 1 and let sales reference her. A phone change then needs one update; each sale keeps its own facts.

  4. 4
    AnalogyKeep two changes together

    A transfer subtracts from checking and adds to savings. Saving only the subtraction would leave incorrect balances.

    A transaction saves both changes together or undoes both, even across rows or tables.

  5. 5
    ChallengeChoose the protection

    A reservation reduces the available seat count, but saving its payment record fails. The two changes belong to one transaction. What should remain after that transaction is undone?

    ---reveal---

    Neither change should remain. Undoing the seat reduction restores the earlier availability, and no payment record from that failed transaction is saved. Keeping only the seat change would leave a partial reservation.

  6. 6
    ConnectionRecognize the workload

    Placing an order is transactional work: a few prompt reads and writes. Comparing monthly regional sales is analytical work: summarizing many historical records.

    A sales database can serve both activities.

  7. 7
    ExplanationFollow the application’s request

    Clients send requests to a database server, as with PostgreSQL or SQL Server. SQLite runs as a library inside the application, without a separate server.

    A managed cloud provider operates servers for its users; tables and requests still apply.

  8. 8
    ExampleRead a declarative request

    SELECT first_name, city FROM customers WHERE state = 'TX'; requests two columns from customers in TX.

    SQL is declarative: it states the result, leaving retrieval steps to the DBMS. SQL is the language; PostgreSQL is one product interpreting it.

  9. 9
    TipRead the statement’s job

    ALTER TABLE changes structure; INSERT adds a row; GRANT manages permission; COMMIT saves a transaction.

    Text uses single quotes: 'TX'. Double an internal apostrophe: 'O''Brien'. A semicolon normally ends a statement.

  10. 10
    ChallengeChoose structure or data

    A shop adds a delivery_note column, then fills it for one order. Are both changes to rows?

    ---reveal---

    Adding the column changes structure: data definition. Filling it changes stored data: data manipulation.

  11. 11
    ChallengeBring the parts together

    A website sends SQL to a PostgreSQL server to record a purchase. A manager reads an ordinary sales view later. Does the view contain another stored copy of all those purchase rows?

    ---reveal---

    No. An ordinary view saves a query that reads the underlying data; it stores no separate result rows of its own. PostgreSQL remains the DBMS managing the purchase records, while the website and reporting tool are clients.

  12. 12
    RecapA shared collection with clear responsibilities

    A database holds facts; a DBMS manages storage, rules, access and recovery. Transactions keep changes together.

    SQL requests concern structure, rows, permissions or transaction control. Identify the job before reading the details.

2

Read the meaning behind a table

10 steps
Locate a fact, count the table’s shape, and distinguish relational rules from display layout.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionStart with what a row represents
  2. 2
    ExampleFind a customer’s city
  3. 3
    ExplanationUse the formal names
  4. 4
    ChallengePredict two kinds of additions
  5. 5
    Key InsightIdentify records without positions
  6. 6
    AnalogyKeep one value for each property
  7. 7
    ExplanationMatch a type to its domain
  8. 8
    ChallengeInterpret a spreadsheet export
  9. 9
    ChallengeCheck a new record and its values
  10. 10
    RecapRead structure before values
3

Choose storage and reason with NULL

15 steps
Apply type choices to business data and predict what missing values do to comparisons and calculations.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTwo choices for every column
  2. 2
    ExplanationSeparate numeric families
  3. 3
    TipNotice product differences
  4. 4
    ChallengeCheck a decimal range
  5. 5
    ConnectionRecognize dates and flags
  6. 6
    ExplanationChoose from the value’s purpose
  7. 7
    ExampleStore money exactly
  8. 8
    ChallengeFix a code and a quantity
  9. 9
    ExplanationRead what is missing
  10. 10
    ExampleFollow an unknown comparison
  11. 11
    Key InsightUse the missing-value test
  12. 12
    ChallengeCombine known and unknown
  13. 13
    ExampleCount what is present
  14. 14
    ChallengeCheck a report’s interpretation
  15. 15
    RecapLet meaning guide storage
4

Build reliable links from keys

18 steps
Test identifiers, trace foreign keys and read one-to-many, one-to-one and many-to-many relationships.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionIdentity comes before a link
  2. 2
    ExplanationTest uniqueness and minimality
  3. 3
    ChallengeTest a future enrollment
  4. 4
    TipDeclare one primary key
  5. 5
    ExplanationChoose a stable label
  6. 6
    Key InsightKeep a separate business rule
  7. 7
    ChallengeRead a gap without renumbering
  8. 8
    ExampleFollow an order’s reference
  9. 9
    ExplanationRequired and optional references
  10. 10
    ChallengeRead a deletion rule
  11. 11
    ConnectionCheck the whole reference
  12. 12
    ExplanationRead one-to-many both ways
  13. 13
    ExampleLimit a link to one
  14. 14
    ExampleRepresent each product pairing
  15. 15
    Key InsightStore a fact about the pair
  16. 16
    ChallengeChoose a link for a new situation
  17. 17
    ChallengeCombine identity and references
  18. 18
    RecapKeys do different jobs together
5

Read a schema to answer a question

14 steps
Read definitions and diagram ends, then trace records and judge whether proposed changes are valid.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSeparate the map from the records
  2. 2
    ExampleRead an order definition
  3. 3
    Key InsightCombine a check with a required value
  4. 4
    ChallengeClassify two changes
  5. 5
    TipFind the full rules
  6. 6
    ExplanationRead a diagram’s legend
  7. 7
    ExampleStart with one row and look across
  8. 8
    ChallengePredict an optional link
  9. 9
    ConnectionSpot a table of pairs
  10. 10
    ExampleFollow order 102 to its city
  11. 11
    ExampleCalculate from the sale lines
  12. 12
    ChallengeJudge a proposed line
  13. 13
    ChallengeConnect data, rules and meaning
  14. 14
    RecapUse each source for its own information

Relational Database Model practice questions

50 Practice Questions in 5 sets

Set 1: Apply rules across a small database10 Practice Questions

Question 1 of 10

An app uses an ordinary view named open_jobs and an index on jobs.job_id. What is the role of each?
  1. The view holds copied rows; the index changes the schema.
  2. The view saves a query; the index helps locate rows.
  3. The view grants access; the index supplies missing values.
  4. The view stores the table; the index saves a query.
Show answerHide answer
Answer: B
A view saves a query; an index helps locate rows. An ordinary view does not keep copied result rows: the current job records remain in the underlying table.

Question 2 of 10

A company reads several years of invoice rows to compare annual revenue by region. What kind of workload is this?
  1. Transactional workload
  2. Embedded workload
  3. Analytical workload
  4. Data-definition workload
Show answerHide answer
Answer: C
This is analytical work: summarizing many stored invoices. Transactional work records individual events, such as issuing an invoice. Classify the activity, even when both use the same data.

Question 3 of 10

A report shows item 8 before item 3. A later run shows item 3 first, with every value unchanged. What explains the change?
  1. Output order is unspecified unless requested.
  2. The first item has become the primary key.
  3. Column positions now identify different items.
  4. The table must have lost a uniqueness rule.
Show answerHide answer
Answer: A
Output order is unspecified unless requested. Moving a row on screen changes neither its identity nor its values. A primary key identifies the row; it does not force the smallest key to appear first.

Question 4 of 10

Each library reader can borrow many books, and each book can be borrowed by many readers over time. Which structure represents a borrowing event?
  1. A row containing reader and book references, plus the borrowing date
  2. A reader row containing a comma-separated list of all borrowed books
  3. A book row containing a comma-separated list of all previous readers
  4. A reader row with fixed book_1, book_2 and book_3 reference columns
Show answerHide answer
Answer: A
A borrowing row links one reader and one book and can hold the event’s date. Such linking rows represent the many-to-many connection without embedding lists. Fixed book slots would cap how many references a reader could have; they also make repeated borrowing events awkward to record.

Question 5 of 10

A table currently contains generated IDs 2, 5 and 8. How many rows does it contain?
  1. 8 rows
  2. 3 rows
  3. 5 rows
  4. 6 rows
Show answerHide answer
Answer: B
There are 3 rows, one for each listed identifier. Generated IDs are labels and may have gaps after deletions or failed work. Taking the largest identifier, 8, as the row count assumes a consecutive sequence that generated keys do not guarantee.

Question 6 of 10

A diagram has exactly-one symbols beside Departments and zero-or-more symbols beside Employees. Read from one department: how many employees may be linked?
  1. Exactly one employee
  2. One or more employees
  3. Zero or one employee
  4. Zero or more employees
Show answerHide answer
Answer: D
Read the symbols at the Employees end to describe employees linked to one department: zero or more. The exactly-one symbols at Departments answer the reverse question, about the department for one employee. Reading the starting end would swap the two directions.

Question 7 of 10

Five inspection readings are 6, NULL, 12, NULL and 9. What are COUNT(*) and AVG(reading)?
  1. 5 and 5.4
  2. 3 and 9
  3. 5 and 9
  4. 3 and 5.4
Show answerHide answer
Answer: C
COUNT(*) counts all 5 rows. AVG skips the two missing readings and divides the known total, 27, by three, giving 9. Dividing by five treats missing entries as zero, even though NULL provides no evidence that either missing measurement was zero.

Question 8 of 10

An ordinary SQLite table declares label VARCHAR(4). A row supplies the text "Winter". What does SQLite do?
  1. Stores only the first four letters.
  2. Pads the word with two spaces.
  3. Rejects the row for excess length.
  4. Stores the complete six-letter word.
Show answerHide answer
Answer: D
SQLite ignores the length argument in VARCHAR(4), so it stores the complete text. The declaration gives text affinity, not a four-character limit. Expecting rejection applies the behavior of systems such as PostgreSQL to SQLite, where declared character lengths do not provide that protection.

Question 9 of 10

Orders has order 620 with account_id 14. Accounts has account 14 in Phoenix and account 620 in Tulsa. The order’s account_id references Accounts.account_id. Where is order 620’s account?
  1. Tulsa, by matching the two 620 identifiers
  2. Phoenix, by following account_id 14
  3. Either city, because both IDs exist
  4. Neither city, because the key names differ
Show answerHide answer
Answer: B
Order 620 points through its account_id value 14, so its account is in Phoenix. Matching order_id 620 directly to account_id 620 ignores the declared link. Identifiers from different tables can share a number without representing the same record or relationship.

Question 10 of 10

A workshop permits one registration per member, session and date. Members can attend different sessions on one date and repeat a session on a later date. A session can have many members. Which combination identifies a registration?
  1. member_id and session_id
  2. member_id and date
  3. member_id, session_id and date
  4. session_id and date
Show answerHide answer
Answer: C
The full member, session and date combination is required. Removing date confuses repeat visits to the same session; removing session confuses two sessions attended on one date. Removing member would merge different people at the same session, so each of the three components is needed.
Set 2: Read records, types and simple links10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Tickets has an enforced, non-NULL event_id foreign key to Events. Events 12 and 19 exist. Two tickets already refer to event 12. What happens to a third ticket referring to event 12?
  1. It is allowed because the parent exists.
  2. It is rejected because event_id repeats.
  3. It creates another row for event 12.
  4. It changes an existing ticket for event 12.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A developer describes the rows a report needs and lets PostgreSQL choose how to find them. What property of SQL does this illustrate?
  1. It is declarative.
  2. It is an engine.
  3. It is a file format.
  4. It is a database.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Read quantity INTEGER CHECK (quantity > 0) and status TEXT DEFAULT 'new'. Neither column has NOT NULL. A new row supplies quantity NULL and omits status. What is stored?
  1. The row is rejected by the quantity check.
  2. Quantity becomes 0; status becomes 'new'.
  3. Quantity stays NULL; status stays NULL.
  4. Quantity stays NULL; status becomes 'new'.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

An equipment table stores asset 46 with the phone entry "212-555-0108, 212-555-0116". Staff must check each number separately. How should the phone data be organized?
  1. Keep one text cell and increase its length.
  2. Use related phone rows, one per number.
  3. Add a second asset row with the same key.
  4. Use a larger numeric type for both numbers.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Company rules require badge_number to be present and unique. Departments repeat. Why is (badge_number, department) a superkey but not a candidate key?
  1. A department value can appear in several rows.
  2. A primary key must always contain two columns.
  3. The badge values might stop being unique later.
  4. Removing department still leaves a unique key.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A warehouse code can be "0047" or "47-A". It is matched to labels and never used in arithmetic. What type best preserves these values?
  1. A varying-length text type
  2. A whole-number integer type
  3. An exact decimal numeric type
  4. An approximate floating-point type
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Four rows have region values 'NE', 'SW', NULL and 'NW'. How many rows pass WHERE region <> 'NE'?
  1. 3
  2. 2
  3. 4
  4. 1
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

In PostgreSQL, how many digits can appear before the decimal point in a DECIMAL(7, 2) value?
  1. 2
  2. 7
  3. 5
  4. 9
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A booking saves a seat assignment and a matching payment record. What database feature ensures that either both changes are saved or both are undone?
  1. A unique constraint
  2. A table definition
  3. A transaction
  4. A saved view
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A table has 6 named columns and 18 rows. After two more rows are added, what are its degree and cardinality?
  1. Degree 20, cardinality 6
  2. Degree 6, cardinality 18
  3. Degree 8, cardinality 20
  4. Degree 6, cardinality 20
Show answerHide answer

Save this lesson to see this answer.

Set 3: Choose types and trace linked records10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

In PostgreSQL, a shipment has NULL delay_days and status 'urgent'. What is the result of (delay_days > 2) OR (status = 'urgent'), and does WHERE keep the row?
  1. UNKNOWN; the row is omitted
  2. TRUE; the row is kept
  3. FALSE; the row is omitted
  4. UNKNOWN; the row is kept
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A table adds tracking_note as a new column for every delivery. Which property changes directly?
  1. Its degree
  2. Its row count
  3. Its index
  4. Its primary key
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A membership table uses generated member_id as primary key. Email must be present and identify at most one account. Which additional declaration enforces both email rules in PostgreSQL?
  1. email TEXT PRIMARY KEY
  2. email TEXT NOT NULL
  3. email TEXT UNIQUE
  4. email TEXT NOT NULL UNIQUE
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

At the parent end of a diagram, a circle and bar show zero-or-one. The child end shows zero-or-more. Which child reference matches these symbols?
  1. A required foreign key with no uniqueness rule
  2. A required foreign key that is also unique
  3. A nullable foreign key that is also unique
  4. A nullable foreign key with no uniqueness rule
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A SQLite app must store exact dollar-and-cent charges of 7.35 and 2.80. What storage choice keeps the amounts exact?
  1. REAL values 7.35 and 2.80
  2. DECIMAL values 7.35 and 2.80
  3. INTEGER cents 735 and 280
  4. TEXT amounts used directly in arithmetic
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Invoice 75 has two lines: item 6, quantity 3, charged unit price 4.20; item 8, quantity 2, charged unit price 6.50. Their current catalog prices are 4.80 and 6.00. What was the invoice’s charged total?
  1. 25.60
  2. 26.40
  3. 27.40
  4. 24.60
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A service repeats each supplier’s current phone on every shipment row. Staff miss some copies during updates. What change addresses the inconsistency?
  1. Give each shipment a larger identifier.
  2. Sort shipments by the supplier’s phone.
  3. Store phones as numbers instead of text.
  4. Store supplier details once and refer to them.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Profiles.user_id is both its primary key and a foreign key to Users.user_id. No rule requires a user to have a profile. What does this allow?
  1. Many profiles per user; one user per profile
  2. One or more profiles per user; one user per profile
  3. Zero or one profile per user; one user per profile
  4. One profile per user; many users per profile
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A new invoice row is added without changing any columns or constraints. What has changed?
  1. The schema, but not the instance
  2. The instance, but not the schema
  3. Both the schema and the instance
  4. Neither the schema nor the instance
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

StockRows has primary key (warehouse_id, item_id) with rows (4, 7) and (5, 9). Reservations has a required, enforced composite foreign key to StockRows. Is a reservation for (4, 9) allowed?
  1. No; the complete referenced pair is absent.
  2. Yes; warehouse 4 and item 9 both appear.
  3. Yes; each key component is individually unique.
  4. No; all existing pairs would need warehouse 4.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Read constraints and explain consequences10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A sales table contains sale rows plus a bottom row labeled "TOTAL" holding their summed amount. Why is that row a problem when the amount column is summed again?
  1. It makes each sale’s amount a text value.
  2. It forces all sale rows to have the same key.
  3. It changes the number of columns in each sale.
  4. It adds a summary as if it were another sale.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Two prices are 30 USD and 30 EUR. Why can they not be added directly as one meaningful money total?
  1. They need distinct primary keys.
  2. Their text lengths are equal.
  3. Their currency units differ.
  4. Their values have no scale.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A course roster permits each learner to attend many courses, including the same course in different terms. Each course has many learners. Which linking row and key fit these rules?
  1. Learner and course references; key learner_id
  2. Learner and course references; key (learner_id, course_id)
  3. Learner, course and term; key (learner_id, course_id, term)
  4. Learner, course and term; key (course_id, term)
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A table has 9 columns and 24 rows. Three rows are deleted, then two columns are added. What are its degree and cardinality?
  1. Degree 11, cardinality 21
  2. Degree 6, cardinality 26
  3. Degree 9, cardinality 23
  4. Degree 21, cardinality 11
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A diagram shows Orders and Products each linked one-to-many to Lines. Lines has primary key (order_id, product_id), and both parts are foreign keys. What does this show between orders and products?
  1. One-to-one, because each pair is unique
  2. Many-to-many, through the Lines table
  3. One-to-many, with Products as the parent
  4. Many-to-one, with Orders as the child
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Passes permits one active pass per person and per locker. Both person_id and locker_id are required and individually unique. The primary key is person_id. How should locker_id be classified?
  1. A foreign key only
  2. A nonminimal superkey
  3. A second primary key
  4. An alternate candidate key
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A schema declares price DECIMAL(8, 2). What additional information is needed to interpret a stored price of 45.00 as a real-world amount?
  1. The physical disk-page address
  2. The number of indexes on the table
  3. The row’s displayed position
  4. The currency used by the column
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A website and a reporting tool both connect to a PostgreSQL server managing shop and payroll databases. Which description correctly separates these components?
  1. PostgreSQL is a client; shop and payroll are SQL dialects.
  2. The website is SQL; PostgreSQL and payroll are databases.
  3. PostgreSQL is the DBMS; shop and payroll are databases.
  4. The reporting tool is the DBMS; PostgreSQL is its stored data.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Two ordinary SQLite tables declare amount DECIMAL(6, 2) and label VARCHAR(3). Rows supply amount 1234567.89 and label "Summer". What do those declarations alone enforce?
  1. Both the amount precision and label length
  2. Neither the amount precision nor label length
  3. The amount precision but not the label length
  4. The label length but not the amount precision
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A customer ID is referenced by many old invoices. Customers often change their email, and the business requires emails to remain unique and present. Which arrangement best supports these rules?
  1. Stable surrogate ID; email declared NOT NULL UNIQUE
  2. Email as primary key; generated ID without a unique rule
  3. Phone as primary key; email stored without constraints
  4. Email as primary key; a new customer row after each change
Show answerHide answer

Save this lesson to see this answer.

Set 5: Resolve missing data and connected constraints10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A DBMS rebuilds an index and rearranges stored pages. Applications still use the same table and column names to request unchanged data. What principle does this demonstrate?
  1. Data independence
  2. Join cardinality
  3. Atomic transactions
  4. Composite row keys
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Scans uses primary key (batch_id, page_no). The pair (18, 4) exists. Batch and page numbers may repeat separately. Which proposed row is rejected specifically for duplicating this key?
  1. batch 18, page 5, new image
  2. batch 19, page 4, new image
  3. batch 18, page 4, different image
  4. batch 19, page 5, different image
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A loan service must prevent a payment from referring to a nonexistent loan, even when several apps write data. Where should this shared rule be enforced?
  1. In each report’s column headings
  2. In an enforced database reference constraint
  3. In the text of the loan’s display label
  4. In the order used to show payment rows
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What does a circle followed by a bar at a crow’s foot diagram end mean?
  1. Zero or one row
  2. Exactly one row
  3. Zero or more rows
  4. One or more rows
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Sale 810 belongs to existing client 26. A new purchase by that same client includes three different existing products, one line per product. How many new rows belong in Clients, Sales and SaleLines?
  1. 1 client, 1 sale, 3 lines
  2. 0 clients, 3 sales, 3 lines
  3. 0 clients, 1 sale, 1 line
  4. 0 clients, 1 sale, 3 lines
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Initially, Orders.customer_id is a non-NULL foreign key to Customers with no uniqueness rule. Customers may have no orders. Adding UNIQUE to Orders.customer_id leaves the other rules unchanged. How does the relationship change?
  1. Customers go from many orders to exactly one; each order keeps one customer.
  2. Customers go from zero-or-many orders to zero-or-one; each order keeps one customer.
  3. Customers keep zero-or-many orders; each order gains zero-or-one customer.
  4. Customers go from zero-or-many orders to zero-or-one; each order gains zero-or-one customer.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An SQLite connection has foreign-key enforcement off. A declared reference is present, but an orphan row is accepted. What needs to change before future writes can rely on that constraint?
  1. Make the parent ID a text column.
  2. Sort child rows by their foreign key.
  3. Enable foreign keys only in the reporting query.
  4. Enable foreign keys for the connection before writes.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Six accounts have city values 'Miami', NULL, 'Dallas', 'Miami', NULL and 'Boise'. How many pass WHERE NOT (city = 'Miami') OR city IS NULL?
  1. 2
  2. 3
  3. 6
  4. 4
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A SQLite table defines a INTEGER NOT NULL, b INTEGER NOT NULL, PRIMARY KEY (a, b) and q INTEGER NOT NULL CHECK (q > 0). No rows exist. Which proposed row satisfies all these constraints?
  1. a = 2, b = NULL, q = 3
  2. a = 2, b = 5, q = 0
  3. a = 2, b = 5, q = 3
  4. a = 2, b = 5, q = NULL
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Project 31 has tasks 7 and 9 through a nullable project_id foreign key with ON DELETE SET NULL. Note 4 refers to task 7 through an enforced foreign key with ON DELETE CASCADE. After deleting project 31, task 7 is deleted. What remains of task 9 and note 4?
  1. Task 9 remains with project_id NULL; note 4 is deleted.
  2. Task 9 remains with project_id 31; note 4 is deleted.
  3. Task 9 is deleted; note 4 remains linked to task 7.
  4. Task 9 remains with project_id NULL; note 4 remains.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

76 Key Terms, each with its definition

A

Alternate key
An alternate key is a candidate key not chosen as the primary key, commonly enforced by combining required values with uniqueness.
An account’s required unique email can remain an alternate key alongside a generated account_id.
Analytical workload (OLAP)
An analytical workload summarizes many stored records to compare totals or patterns.
A monthly report compares sales across regions by reading the stored records of many purchases.
Atomic value
An atomic value is one value for a column’s purpose, rather than a list of separate values that must be processed independently.
A phone field containing two comma-separated numbers holds a list where one phone value is expected.

B

Boolean type
A Boolean type represents true-or-false facts, with NULL available for missing information unless a constraint forbids it.
An in_stock flag records whether an item is available; its exact storage form varies by DBMS.

C

Candidate key
A candidate key is a minimal superkey: its values uniquely identify a row and removing any component would lose that guarantee.
A required, unique employee email can be a candidate even when employee_id becomes the primary key.
Cascade
A cascade carries a parent deletion or key change to referring child rows according to the declared foreign key action.
Deleting an order can cascade to its order lines because those child rows belong to that order.
Character type
A character type stores text such as names or codes; its length and comparison behavior depend on its declaration and database system.
A product code such as MUG-11-BLU belongs in text storage because it is a label, not a quantity.
CHECK constraint
A CHECK constraint rejects a row if its condition is FALSE, but a result of UNKNOWN from NULL does not itself reject the row.
A required positive quantity uses NOT NULL along with CHECK (quantity > 0) to cover both rules.
Client-server system
In a client-server system, clients send requests to a server that manages and returns data.
A website and a reporting tool can both connect to the same PostgreSQL server over a network.
Column (attribute or field)
A column (attribute or field) is a named, typed property shared by every row.
The city column holds a city value, or NULL when allowed, for each customer record.
Composite key
A composite key identifies rows through a combination of columns, whose complete values must be unique even if individual parts repeat.
Student, course and term together identify an enrollment when a student may retake a course later.
Constraint
A constraint is a declared rule that limits allowed data, such as uniqueness, required values or valid references between tables.
A positive-quantity constraint rejects an order line with zero units even though zero is an integer.
Crow’s foot notation
Crow’s foot notation marks relationship ends with circles, bars and three-pronged feet to show minimum and maximum linked-row counts.
A circle and foot beside orders allow one customer to have zero or more related order rows.
Currency code
A currency code is a standardized three-letter label that identifies an amount’s currency, such as USD, EUR or JPY.
Two rows both containing 20 may represent different amounts if one is labeled USD and the other EUR.

D

Data
Data are recorded facts, such as names, dates or amounts.
A delivery service records a package’s weight, destination and dispatch date as data.
Data definition language (DDL)
DDL statements create, alter or remove database structures, such as tables.
Adding a new delivery-date column changes structure, so it belongs to data definition.
Data dictionary
A data dictionary documents column meanings, units and business rules that a table’s types and constraints do not fully express.
Documentation explains whether a NULL shipped_date means not shipped or a date that was lost.
Data independence
Data independence separates the logical table structure used by applications from the DBMS’s physical arrangement of stored data.
The DBMS can reorganize disk pages while applications continue to refer to the same named columns.
Data manipulation language (DML)
DML statements read or change stored rows, including inserts, updates and deletions.
Recording a new order adds data; it does not create another column or change the table’s shape.
Database
A database is an organized collection of related data that can be searched, updated and shared.
A store database keeps customer, product and order records together for several applications.
Database instance
A database instance, in the schema-versus-data sense, is the collection of values stored at one particular moment.
Adding a new order changes the current instance while leaving its table definition unchanged.
Database management system (DBMS)
A DBMS is software that manages databases, enforces rules and controls access.
When PostgreSQL manages a store database, the software is distinct from the customer records stored there.
Database schema
A database schema describes the structure of tables, columns, data types, keys and constraints that determine what records are allowed.
Adding a new delivery instruction column changes the schema, even before any instruction is stored.
Default value
A default value is supplied when a new row omits a column’s value, while other constraints still govern the value that is stored.
A status column with DEFAULT 'pending' records pending when the new row leaves status unspecified.
Degree
A table's degree is its number of columns, a property of its structure.
Adding a customer’s birth date as a new column increases the degree of the customers table.
Domain
A domain is the set of values allowed for a column, described through its data type and any additional restrictions.
A quantity domain can require whole numbers greater than zero, excluding negative stock amounts.

E

Embedded database engine
An embedded database engine runs inside an application as a library, without a separate server.
A desktop app can use SQLite to read and write a local database file containing its records.
Entity-relationship diagram
An entity-relationship diagram represents business entities and relationships during design, which may later be translated into tables.
Chen-style diagrams may draw attributes as ovals and relationships as diamonds instead of table boxes.
Exact decimal type
An exact decimal type stores base-ten amounts without binary approximation in systems that support it, such as PostgreSQL.
A PostgreSQL price declared DECIMAL(8, 2) stores exact dollar-and-cent amounts within its range.

F

Floating-point type
A floating-point type stores approximate binary numbers, allowing a broad numeric range while introducing small decimal rounding differences.
A measured temperature can use a floating-point type when tiny representation errors are acceptable.
Foreign key
A foreign key is a column or combination whose non-NULL references must match an existing parent primary key or suitable unique key.
Several order rows can hold customer_id 1, each referring to the same unique customer record.

G

Generated identifier
A generated identifier is a key value supplied automatically by the database, with syntax that varies across database products.
SQLite’s INTEGER PRIMARY KEY supplies an integer when a new row leaves the identifier out.

I

Index
An index is a lookup structure that helps a DBMS find matching rows.
A primary-key index helps the system locate one customer record in a table containing millions.
Integer cents
Integer cents represent an amount as a whole number of the currency’s smallest cent unit, giving exact storage for cent-based money.
An SQLite price of $12.50 can be stored as 1250 cents and formatted as dollars when displayed.
Integer type
An integer type stores whole numbers within a supported range, making it suitable for counts, quantities and many generated identifiers.
The quantity of lamps in an order is a whole-number count, unlike their measured weight.
IS NULL
IS NULL is the SQL test that returns true when an entry is missing, allowing such rows to be found without an equality comparison.
The condition phone IS NULL identifies customers whose phone numbers have not been recorded.
ISO date format
The ISO date format writes a calendar date as year-month-day, giving an unambiguous representation such as 2026-03-02.
Consistent ISO date text in SQLite sorts in calendar order, unlike month-first US display text.

J

Join
A join combines related data by matching values across tables, automating the key-following process used for a manual lookup.
A customer lookup matches orders.customer_id to customers.customer_id to reach the right city.
Junction table
A junction table records pairings through foreign keys to two tables, often using their combination as its primary key.
Each order_items row links an order with a product and records the quantity and charged unit price.

K

Key path
A key path is a sequence of declared references followed between tables to connect a starting record with the facts needed for an answer.
To find an order’s city, follow its customer_id to a customer row and read that row’s city.

L

Line amount
A line amount is the cost of the units on one order line, calculated from its quantity and the unit price recorded for that sale.
Two mugs at $12.50 contribute $25.00 to the order total before the remaining lines are added.

M

Many-to-many relationship
A many-to-many relationship lets rows on both sides link to several rows on the other, represented through a table of pairings.
One order contains several products, and one product can appear in many different orders.

N

Natural key
A natural key uses an identifier from the real-world subject being recorded, such as a vehicle identification number or state code.
A states table can use a two-letter state_code as a readable primary key in address records.
NOT NULL
NOT NULL is a constraint that requires a column entry to be present, rejecting NULL without itself checking positivity or nonempty text.
An order date can be required while a shipping date remains nullable until dispatch occurs.
NULL
NULL is the marker for a missing database value, which may be unknown, not yet available or not applicable to that record.
An order’s shipping date can be NULL because it has not shipped, while its order date is recorded.
Numeric code
A numeric code is an identifier written using digits whose purpose is labeling, so leading zeros and other formatting can carry meaning.
The ZIP code 02108 needs text storage to keep the initial zero when the value is read back.

O

One-to-many relationship
A one-to-many relationship allows one parent to be linked to several children, each carrying a foreign key to its parent.
An employee’s manager reference can repeat because several employees may share one manager.
One-to-one relationship
A one-to-one relationship allows at most one matching row on each side, commonly enforced through a foreign key that is also unique.
A profile can use user_id as both primary key and foreign key, preventing a second profile for one user.
Optional relationship
An optional relationship allows a link to be absent, often represented by a nullable foreign key and a zero minimum at the parent end.
An order without a coupon can keep coupon_id NULL while other orders refer to existing coupons.
Order line
An order line is a record of one product within one order, holding pairing facts such as quantity and the unit price charged.
Two mugs in one order can be represented by one line with quantity 2 and the recorded price per mug.
Orphan row
An orphan row is a child record whose non-NULL reference has no matching parent, leaving its supposed relationship unresolved.
An order referring to a deleted customer would be an orphan if no enforced constraint prevented it.

P

Parent and child tables
A parent table supplies a referenced key; a child table stores the foreign key that points to that parent, possibly many times.
Customers is the parent and orders the child when each order stores its customer’s identifier.
Precision
The precision of DECIMAL(p, s) is p, the total number of digits available across the integer and fractional parts of a value.
In DECIMAL(8, 2), eight total digits leave room for six before the point and two after it.
Primary key
A primary key is the candidate key chosen as a table’s main row identifier, with unique, non-NULL values and possibly several columns.
The customer table uses customer_id as its primary key so orders can refer to one precise customer.

R

Referential action
A referential action specifies how a foreign key handles a referenced parent’s deletion or key change, such as blocking or cascading it.
ON DELETE SET NULL keeps child rows but removes their parent reference, so that reference must allow NULL.
Referential integrity
Referential integrity is the rule that enforced non-NULL foreign key references match existing parent rows, keeping links valid.
An enforced order-to-customer constraint rejects an order for customer 99 when that customer is absent.
Relational database
A relational database uses tables: columns describe properties and rows describe records.
A store keeps orders in one table and uses customer identifiers to refer to a separate customer table.
Relationship cardinality
Relationship cardinality describes how many rows on either side of a link may relate to one row on the other side.
A customer may have many orders, while each store order must refer to exactly one customer.
Row (tuple or record)
A row (tuple or record) contains one item's entries for all the table's columns.
In a customers table, the row for a customer named Wei Chen contains his identifier, name, city and the other customer properties.

S

Scale
The scale of DECIMAL(p, s) is s, the number of digits after the decimal point, which determines its fractional precision.
A scale of two provides two decimal places, as needed for prices expressed in dollars and cents.
Schema diagram
A schema diagram displays existing tables, their columns and key links in boxes and lines, often showing allowed relationship counts.
A line joins orders.customer_id to the customer key, making the reference from orders to customers visible.
Self-referencing relationship
A self-referencing relationship links roles within one table by having a foreign key refer to a key in that same table.
An employee’s manager_id points to another employee row, with NULL for a person who has no manager.
SQL
SQL is the standard declarative language for relational databases, with product-specific dialects.
A reporting tool sends an SQL request to PostgreSQL to retrieve the customer records it needs.
SQL dialect
An SQL dialect is a product's supported SQL syntax, types and added features.
SQLite uses LIMIT 10 for a result limit, while SQL Server commonly uses TOP 10.
Structured data
Structured data share defined, named fields, even when some values are missing.
Every order row has the same columns, including a shipping date that can be NULL before shipment.
Superkey
A superkey is a column or set of columns whose combined values uniquely identify each row, even when it includes unnecessary columns.
If employee_id is unique, pairing it with department still identifies the employee but adds an extra column.
Surrogate key
A surrogate key is an identifier introduced only to distinguish database rows, such as a generated integer with no business meaning.
A customer_id stays fixed when the customer changes an email address, phone number or last name.

T

Table (relation)
A table (relation) holds facts about one kind of thing in named columns and individual rows.
The products table records each item the store offers using columns such as name and price.
Table cardinality
A table’s cardinality is the number of rows it currently contains, which changes as records are added or removed.
A store customer table that currently holds four records has a table cardinality of four.
Three-valued logic
Three-valued logic combines TRUE, FALSE and UNKNOWN results, accounting for conditions that involve missing database values.
TRUE OR UNKNOWN is TRUE because the true condition already makes the combined OR condition succeed.
Transaction
A transaction groups changes so all are saved together or all are undone.
A transfer subtracts money from one account and adds it to another within the same transaction.
Transactional workload (OLTP)
A transactional workload records everyday events through small reads and writes.
A ticket system records each booking and payment as customers buy seats throughout the day.
Type affinity
SQLite’s type affinity is a preference for a column’s storage type, with conversions attempted while allowing flexible stored values.
An ordinary SQLite integer column can retain abc as text when integer conversion fails.

U

UNKNOWN
UNKNOWN is SQL’s third truth result, produced when a comparison depends on missing information and cannot be settled as true or false.
state <> 'TX' is UNKNOWN for a customer whose state is NULL, so WHERE omits that row.
UUID
A UUID is a 128-bit identifier commonly written in 36 characters, supporting independent generation with very low collision risk.
Separate devices can generate UUIDs before their new records are combined in one database.

V

View
A view is a saved query used like a table; an ordinary view has no stored result rows of its own.
A sales view can present selected order columns while the underlying records remain in their tables.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started