- Learn
- Computer Science & IT
- Programming
- SQL Basics
- Relational Database Model
The Relational Database Model
BeginnerLesson 1 of 6 in SQL Basics Course
What you will learn
- 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 databasesDistinguish 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 SQLName common relational database systems, describe how applications connect to them, and explain what SQL is and how its statements are grouped.
- Explain why organizations use databases
- 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 tableIdentify 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 relationalApply the rules of the relational model about rows, columns and values, and recognize where SQL tables and spreadsheets behave differently.
- Describe the parts of a table
- 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 typesIdentify 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 dataPick 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 NULLExplain what NULL means, distinguish it from zero and empty text, and predict how NULL behaves in comparisons, calculations and constraints.
- Recognize the main SQL data types
- 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 keyDecide which columns or column combinations identify each row uniquely, and explain the rules a primary key must follow.
- Choose between natural and surrogate keysCompare real-world identifiers with system-generated ones, judge which make good primary keys, and protect natural identifiers with unique constraints.
- Link tables with foreign keysExplain 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 relationshipsDetermine 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.
- Identify candidate keys and the primary key
- 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 definitionsDistinguish a schema from the data it describes, read schema notation and CREATE TABLE statements, and interpret the constraints they declare.
- Read a schema diagramInterpret 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 dataLocate where each fact is stored, follow keys between tables by hand, and use the schema's constraints to decide what data are allowed.
- Read a schema and its table definitions
Relational Database Model study guide
1What 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
| Group | Purpose | Examples |
|---|---|---|
| Data definition, DDL | Define or change structure | CREATE TABLE, ALTER TABLE, DROP TABLE |
| Data manipulation, DML | Read or change rows | SELECT, INSERT, UPDATE, DELETE |
| Data control, DCL | Manage permissions | GRANT, REVOKE |
| Transaction control | Save or undo a transaction | COMMIT, 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.
2Read 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_id | first_name | last_name | city | state | zip_code |
|---|---|---|---|---|---|
| 1 | Maria | Garcia | Austin | TX | 78701 |
| 2 | James | Wilson | Denver | CO | 80202 |
| 3 | Aisha | Johnson | Boston | MA | 02108 |
| 4 | Wei | Chen | Seattle | WA | 98101 |
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 word | Formal relational word | Other common word |
|---|---|---|
| Table | Relation | — |
| Row | Tuple | Record |
| Column | Attribute | Field |
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:
- Treat the column names as the header, not as sale records.
- Keep each data row about one sale; calculate the total from those rows.
- Store the numeric price separately from a sale note.
- 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.
3Choose 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
| Kind | Common types | Suitable use |
|---|---|---|
| Whole numbers | INTEGER, SMALLINT, BIGINT | Counts, quantities and integer identifiers |
| Exact decimals | DECIMAL(p, s), NUMERIC(p, s) | Money and other exact decimal amounts |
| Approximate numbers | REAL, FLOAT, DOUBLE PRECISION | Measurements 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;
STRICTtables enforce their supported types. - SQL Server’s
TIMESTAMPis 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
- What are typical values, and what extremes must fit?
- Will the values be used in arithmetic?
- Must they be exact, or is approximation acceptable?
- How must they sort and compare?
- 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 NULLfinds missing phone numbers.phone IS NOT NULLfinds recorded phone numbers.phone = NULLyields 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.
| Expression | Result | Reason |
|---|---|---|
| TRUE AND UNKNOWN | UNKNOWN | The second part decides whether both are true. |
| FALSE AND UNKNOWN | FALSE | One false part already defeats AND. |
| TRUE OR UNKNOWN | TRUE | One true part already satisfies OR. |
| FALSE OR UNKNOWN | UNKNOWN | The second part decides OR. |
| NOT UNKNOWN | UNKNOWN | Negation 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 NULLorIS NOT NULL. - Comparisons involving NULL produce UNKNOWN;
WHEREkeeps 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.
4Identify 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.
| Term | Test |
|---|---|
| Superkey | Does the combination identify a row? |
| Candidate key | Is it unique with no unnecessary column? |
| Primary key | Which candidate is the main identifier? |
| Alternate key | Which 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
| System | Common generated integer form |
|---|---|
| Standard SQL, PostgreSQL, Oracle | GENERATED ALWAYS AS IDENTITY |
| MySQL | AUTO_INCREMENT |
| SQL Server | IDENTITY(1,1) |
| SQLite | INTEGER 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 UNIQUEcan 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_id | customer_id | order_date | shipped_date |
|---|---|---|---|
| 101 | 1 | 2026-03-02 | 2026-03-04 |
| 102 | 2 | 2026-03-05 | NULL |
| 103 | 1 | 2026-03-09 | 2026-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
| Action | Effect when a referenced parent is deleted |
|---|---|
NO ACTION or RESTRICT | Refuses the deletion while references remain, subject to constraint-check timing |
CASCADE | Deletes the referring child rows too |
SET NULL | Keeps 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 NULLmakes 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_id | product_id | quantity | unit_price |
|---|---|---|---|
| 101 | 11 | 2 | 12.50 |
| 101 | 12 | 1 | 8.99 |
| 102 | 13 | 1 | 34.00 |
| 103 | 11 | 4 | 12.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.
5Read 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:
| Constraint | What it checks |
|---|---|
PRIMARY KEY | A unique row identifier, possibly composite |
NOT NULL | A value is present |
UNIQUE | Repeated non-NULL values are forbidden; NULL handling varies |
REFERENCES | A reference matches a parent key |
CHECK | A condition must not be FALSE |
DEFAULT | Supplies 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 NULLand 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 symbols | Allowed number of rows at that end |
|---|---|
| Bar and bar | Exactly one |
| Circle and bar | Zero or one |
| Bar and crow's foot | One or more |
| Circle and crow's foot | Zero 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.
- Start with one customer. Look at the orders end: the customer can have zero or more orders.
- Start with one order. Look at the customers end: the order belongs to exactly one customer.
- 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:
- Find order 102 by
orders.order_id. - Read its
customer_id: 2. - Find customer 2 by
customers.customer_id. - 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_id | quantity | unit_price | Product name |
|---|---|---|---|
| 11 | 2 | 12.50 | Coffee mug |
| 12 | 1 | 8.99 | Phone 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
1From shared records to database requests
12 steps
- 1IntroductionWho 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.
- 2ExplanationSeparate 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.
- 3ExampleUpdate one phone number
Maria's phone appears on 14 spreadsheet sales. A missed edit leaves conflicting copies.
Store her phone once under
customer_id1 and let sales reference her. A phone change then needs one update; each sale keeps its own facts. - 4AnalogyKeep 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.
- 5ChallengeChoose 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.
- 6ConnectionRecognize 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.
- 7ExplanationFollow 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.
- 8ExampleRead 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.
- 9TipRead the statement’s job
ALTER TABLEchanges structure;INSERTadds a row;GRANTmanages permission;COMMITsaves a transaction.Text uses single quotes:
'TX'. Double an internal apostrophe:'O''Brien'. A semicolon normally ends a statement. - 10ChallengeChoose structure or data
A shop adds a
delivery_notecolumn, 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.
- 11ChallengeBring 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.
- 12RecapA 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.
2Read the meaning behind a table
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionStart with what a row represents
- 2ExampleFind a customer’s city
- 3ExplanationUse the formal names
- 4ChallengePredict two kinds of additions
- 5Key InsightIdentify records without positions
- 6AnalogyKeep one value for each property
- 7ExplanationMatch a type to its domain
- 8ChallengeInterpret a spreadsheet export
- 9ChallengeCheck a new record and its values
- 10RecapRead structure before values
3Choose storage and reason with NULL
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTwo choices for every column
- 2ExplanationSeparate numeric families
- 3TipNotice product differences
- 4ChallengeCheck a decimal range
- 5ConnectionRecognize dates and flags
- 6ExplanationChoose from the value’s purpose
- 7ExampleStore money exactly
- 8ChallengeFix a code and a quantity
- 9ExplanationRead what is missing
- 10ExampleFollow an unknown comparison
- 11Key InsightUse the missing-value test
- 12ChallengeCombine known and unknown
- 13ExampleCount what is present
- 14ChallengeCheck a report’s interpretation
- 15RecapLet meaning guide storage
4Build reliable links from keys
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionIdentity comes before a link
- 2ExplanationTest uniqueness and minimality
- 3ChallengeTest a future enrollment
- 4TipDeclare one primary key
- 5ExplanationChoose a stable label
- 6Key InsightKeep a separate business rule
- 7ChallengeRead a gap without renumbering
- 8ExampleFollow an order’s reference
- 9ExplanationRequired and optional references
- 10ChallengeRead a deletion rule
- 11ConnectionCheck the whole reference
- 12ExplanationRead one-to-many both ways
- 13ExampleLimit a link to one
- 14ExampleRepresent each product pairing
- 15Key InsightStore a fact about the pair
- 16ChallengeChoose a link for a new situation
- 17ChallengeCombine identity and references
- 18RecapKeys do different jobs together
5Read a schema to answer a question
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSeparate the map from the records
- 2ExampleRead an order definition
- 3Key InsightCombine a check with a required value
- 4ChallengeClassify two changes
- 5TipFind the full rules
- 6ExplanationRead a diagram’s legend
- 7ExampleStart with one row and look across
- 8ChallengePredict an optional link
- 9ConnectionSpot a table of pairs
- 10ExampleFollow order 102 to its city
- 11ExampleCalculate from the sale lines
- 12ChallengeJudge a proposed line
- 13ChallengeConnect data, rules and meaning
- 14RecapUse each source for its own information
Relational Database Model practice questions
Set 1: Apply rules across a small database10 Practice Questions
Question 1 of 10
open_jobs and an index on jobs.job_id. What is the role of each?Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
VARCHAR(4). A row supplies the text "Winter". What does SQLite do?Show answerHide answer
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
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?Show answerHide answer
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
Show answerHide answer
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
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?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
badge_number to be present and unique. Departments repeat. Why is (badge_number, department) a superkey but not a candidate key?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
WHERE region <> 'NE'?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
DECIMAL(7, 2) value?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
delay_days and status 'urgent'. What is the result of (delay_days > 2) OR (status = 'urgent'), and does WHERE keep the row?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
tracking_note as a new column for every delivery. Which property changes directly?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
member_id as primary key. Email must be present and identify at most one account. Which additional declaration enforces both email rules in PostgreSQL?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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?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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
order_id, product_id), and both parts are foreign keys. What does this show between orders and products?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
person_id and locker_id are required and individually unique. The primary key is person_id. How should locker_id be classified?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
DECIMAL(8, 2). What additional information is needed to interpret a stored price of 45.00 as a real-world amount?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
DECIMAL(6, 2) and label VARCHAR(3). Rows supply amount 1234567.89 and label "Summer". What do those declarations alone enforce?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
WHERE NOT (city = 'Miami') OR city IS NULL?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Alternate key
account_id.Analytical workload (OLAP)
Atomic value
B
Boolean type
in_stock flag records whether an item is available; its exact storage form varies by DBMS.C
Candidate key
employee_id becomes the primary key.Cascade
Character type
MUG-11-BLU belongs in text storage because it is a label, not a quantity.CHECK constraint
NOT NULL along with CHECK (quantity > 0) to cover both rules.Client-server system
Column (attribute or field)
city column holds a city value, or NULL when allowed, for each customer record.Composite key
Constraint
Crow’s foot notation
Currency code
D
Data
Data definition language (DDL)
Data dictionary
shipped_date means not shipped or a date that was lost.Data independence
Data manipulation language (DML)
Database
Database instance
Database management system (DBMS)
Database schema
Default value
DEFAULT 'pending' records pending when the new row leaves status unspecified.Degree
Domain
E
Embedded database engine
Entity-relationship diagram
Exact decimal type
DECIMAL(8, 2) stores exact dollar-and-cent amounts within its range.F
Floating-point type
Foreign key
customer_id 1, each referring to the same unique customer record.G
Generated identifier
INTEGER PRIMARY KEY supplies an integer when a new row leaves the identifier out.I
Index
Integer cents
Integer type
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.phone IS NULL identifies customers whose phone numbers have not been recorded.ISO date format
2026-03-02.J
Join
orders.customer_id to customers.customer_id to reach the right city.Junction table
order_items row links an order with a product and records the quantity and charged unit price.K
Key path
customer_id to a customer row and read that row’s city.L
Line amount
M
Many-to-many relationship
N
Natural key
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.NULL
Numeric code
02108 needs text storage to keep the initial zero when the value is read back.O
One-to-many relationship
One-to-one relationship
user_id as both primary key and foreign key, preventing a second profile for one user.Optional relationship
coupon_id NULL while other orders refer to existing coupons.Order line
Orphan row
P
Parent and child tables
Precision
DECIMAL(p, s) is p, the total number of digits available across the integer and fractional parts of a value.DECIMAL(8, 2), eight total digits leave room for six before the point and two after it.Primary key
customer_id as its primary key so orders can refer to one precise customer.R
Referential action
ON DELETE SET NULL keeps child rows but removes their parent reference, so that reference must allow NULL.Referential integrity
Relational database
Relationship cardinality
Row (tuple or record)
S
Scale
DECIMAL(p, s) is s, the number of digits after the decimal point, which determines its fractional precision.Schema diagram
orders.customer_id to the customer key, making the reference from orders to customers visible.Self-referencing relationship
manager_id points to another employee row, with NULL for a person who has no manager.SQL
SQL dialect
LIMIT 10 for a result limit, while SQL Server commonly uses TOP 10.Structured data
Superkey
employee_id is unique, pairing it with department still identifies the employee but adds an extra column.Surrogate key
customer_id stays fixed when the customer changes an email address, phone number or last name.T
Table (relation)
Table cardinality
Three-valued logic
Transaction
Transactional workload (OLTP)
Type affinity
abc as text when integer conversion fails.U
UNKNOWN
state <> 'TX' is UNKNOWN for a customer whose state is NULL, so WHERE omits that row.UUID
V
View
- 1Relational Database Model
- 2SQL SELECT
- 3SQL CASE and Functions
- 4SQL GROUP BY
- 5SQL Joins
- 6SQL CREATE TABLE
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.