SQL and Database Fundamentals
SQL, Relational Databases, and Database Practice
Databases and the role of SQL
Many everyday digital services depend on databases: streaming platforms retrieve viewing information, banks manage account balances, schools track student records, and retailers record sales and inventory. Each interaction may cause data to be looked up, added, changed, or analyzed.
A database is an organized collection of data. A database management system (DBMS) stores and manages that data and provides ways for applications and users to work with it. SQL (Structured Query Language) is the widely used language for querying and managing relational databases.
SQL is useful not only to programmers but also to analysts and business decision-makers. It translates questions—such as which products sell best, who the most valuable customers are, or when sales peak—into instructions that a database can process. The results can support reporting, inventory planning, trend analysis, and fraud detection.
The relational model organizes data into tables. Each table contains rows, which represent records, and columns, which represent attributes of those records. Related tables can be connected through key columns.
Retrieving data with SELECT and FROM
A basic SQL query uses two clauses:
SELECTidentifies the columns to return.FROMidentifies the table or tables from which to retrieve them.
For example, a retailer that needs only product names and prices can request those columns from a sales-related table. Requesting only necessary columns is generally better than requesting every column.
The asterisk (*) means “all columns.” It can be convenient for exploring a small table, but it is usually a poor choice for production queries or large tables. Retrieving unnecessary columns increases the amount of data the database must read and return, consumes more memory and processing resources, and can make queries slower. On large datasets, the difference may be substantial.
A good default is to select only the columns needed for the task. This improves efficiency and makes a query’s purpose clearer.
Filtering rows with WHERE
The WHERE clause filters individual rows. A row is returned only if it satisfies the condition or conditions specified.
Common comparison operators include:
Equals: finds an exact match.
Not equal: excludes a particular value.
Less than and greater than: compare numeric values and dates.
Less than or equal to and greater than or equal to: include the boundary value as well.
These comparisons can be applied to numbers, dates, and—depending on the database and comparison rules—text. A filter can identify, for example, products above a price threshold or sales after a particular date.
Pattern matching with LIKE
The LIKE operator searches text for a pattern. The percent sign (%) is a wildcard representing any sequence of characters, including no characters. For example, a pattern such as Men% can match names beginning with “Men.”
The placement of the wildcard matters. A pattern with a wildcard only at the end can often use an index, while a pattern beginning with a wildcard often cannot. This distinction is important when performance matters.
Conditions should be written precisely, especially when filtering dates. The exact date literal format varies between database systems, so queries should use the format supported by the DBMS in use.
Combining conditions with AND, OR, and NOT
Logical operators let a query combine or reverse conditions:
ANDrequires every connected condition to be true. For example, a row might have to represent a sneaker and have the color black.ORrequires at least one connected condition to be true. A query for sneakers or products made by a particular manufacturer returns both sets, including any manufacturer products that are not sneakers.NOTreverses a condition, selecting rows that do not satisfy it.
When AND and OR appear together, parentheses should be used to make the intended logic explicit. SQL evaluates AND before OR unless parentheses specify a different grouping. For example, the condition “sneakers or boots, but only when made by Nike” should group the two categories together before applying the manufacturer condition. Without parentheses, the database may evaluate the expression differently from what was intended.
Removing duplicates with DISTINCT
DISTINCT removes duplicate rows from the query’s result. It is useful when a report needs unique values, such as a list of manufacturers represented in sales, rather than every transaction.
DISTINCT applies to the complete combination of selected columns. If a query selects both manufacturer and color, then each unique manufacturer–color pair is returned. Thus, one manufacturer can appear more than once if it has products in different colors.
Ordering results with ORDER BY
The ORDER BY clause sorts returned rows. It changes the order of the results, not which rows qualify.
Ascending order is the default in many SQL systems. It typically sorts text from A to Z, numbers from low to high, and dates from earlier to later.
Descending order reverses that sequence: Z to A, high to low, or later to earlier.
Results can be sorted by multiple columns. The database sorts by the first specified column, then uses the next column to order rows that tie on the first. For instance, products could be sorted by color in ascending order and then by price in descending order within each color.
Summarizing data with aggregates and GROUP BY
SQL can summarize many rows rather than returning each record individually. Aggregate functions calculate a value from a set of rows:
COUNTcounts rows or values.SUMadds numeric values.AVGcalculates an average.MINfinds the smallest value.MAXfinds the largest value.
The GROUP BY clause divides rows into groups that share one or more column values. Aggregate functions can then calculate a summary for each group. For example, sales can be grouped by product category to calculate revenue per category. Revenue from individual sales is commonly calculated by multiplying unit price by quantity, then summing those values within each category.
A calculated result can be given a readable output name using an alias, such as labeling a sum as “total revenue.” Clear output names make reports easier to interpret.
Filtering groups with HAVING
The HAVING clause filters groups after GROUP BY and aggregation have taken place. It is used for conditions on aggregate results—for example, retaining only categories whose total revenue exceeds a threshold.
WHERE and HAVING operate at different stages:
WHEREfilters individual rows before grouping.HAVINGfilters the resulting groups after aggregation.
Because WHERE acts earlier, ordinary row-level conditions should generally be placed there. Aggregate conditions belong in HAVING.
Relational design: normalization and keys
A real database usually should not store every kind of information in one enormous table. Repeating customer names, addresses, product details, and manufacturer information on every sales record creates redundancy. If a customer’s address changes, many rows may need updating; a missed update can leave conflicting information. Repetition also wastes storage and makes errors more likely.
Normalization is the practice of organizing data into smaller related tables to reduce unnecessary repetition and support consistency. A retailer might maintain separate tables for customers, products, manufacturers, and sales. Each table focuses on a particular entity or type of record.
Primary keys
A primary key (PK) uniquely identifies each row in a table. It is often an ID column, such as a customer ID or product ID. Each primary-key value must identify one specific record.
Foreign keys
A foreign key (FK) is a column in one table whose values refer to a key in another table. For example, a sales record can store a customer ID rather than repeating the customer’s name and address. That ID connects the sale to the customer’s record. A sale can similarly refer to a product, and a product can refer to its manufacturer.
Primary and foreign keys allow related information to be stored once and connected when needed. They also support referential integrity: the database can enforce rules that prevent references to nonexistent records.
Combining related data with joins
A normalized database stores information across related tables, so queries often need to bring that information together. A join combines rows from tables using a relationship between their columns, commonly a foreign key in one table and the corresponding primary key in another.
INNER JOIN
An inner join returns rows for which the join condition finds a match in both tables. If a product has never appeared in a sale, it will not appear in an inner join between products and sales.
A join condition, written with ON, tells the database which columns establish the relationship. For example, matching the product ID in a sales table to the product ID in a product table connects each sale to its product details. A query can then filter on a product attribute such as category.
When joining tables, selecting every column from every table is usually unhelpful. It may retrieve unnecessary data and can create ambiguity when different tables contain columns with the same name. Specifying the required columns makes the query more efficient and understandable.
Chaining joins and using aliases
A query can join more than two tables by following the relationships among them. To retrieve sales, product details, and manufacturer names, a query can connect sales to products and products to manufacturers. A more complex request—such as finding products made by Texas manufacturers and sold to customers in California—may require joining sales, products, manufacturers, and customers, then filtering on the relevant state columns.
Table aliases are short temporary names for tables within a query. Aliases make multi-table queries less cluttered and help indicate which table supplies each column. Consistent aliases are especially helpful when several tables contain columns with similar names.
Outer joins
Outer joins preserve some rows even when the other table has no matching row. Unmatched columns are filled with NULL, which represents missing or unknown information.
A left join keeps every row from the left table and includes matching rows from the right table. When no right-side match exists, right-side columns are
NULL.A right join keeps every row from the right table and includes matching rows from the left table. Unmatched left-side columns are
NULL.A full outer join keeps rows from both tables, whether or not they have a match. Missing values from either side appear as
NULL.
For example, a left join from products to sales can list every product, including those never sold. Products with sales can show their sale information; products without sales remain in the results with NULL sale fields.
An inner join can be understood as retaining only the overlap between the two tables’ matching records. A left join preserves the left table’s records in addition to that overlap; a right join preserves the right table’s records; a full join preserves records from both sides.
Avoiding accidental Cartesian products
The ON condition must specify the correct relationship between joined tables. If the join condition is missing or incorrect, the query may create a Cartesian product, also called a cross join: every row in one table is paired with every row in the other.
If each table has one thousand rows, such a result can contain one million row combinations. For large tables, this can consume substantial memory and processing capacity. Join conditions should therefore be checked carefully.
A natural join attempts to infer join columns from matching column names. Because that inference can change or behave unexpectedly when schemas change, explicit join conditions are generally clearer and safer.
Changing data with DML
Data manipulation language (DML) commands add, modify, and remove rows. The key operations are INSERT, UPDATE, and DELETE.
Adding rows with INSERT
An INSERT statement adds new records to a table. Best practice is to list explicitly the columns receiving values. Doing so clarifies which value corresponds to each column and makes the statement more resilient if the table later gains additional columns.
Columns not included in an insert receive their defined default values, if any. Otherwise, they commonly receive NULL, subject to the table’s constraints. NULL does not mean zero or an empty string; it represents a value that is unknown, missing, or not applicable.
An insert can also take rows from a query, such as copying qualifying older sales into an archive table. The selected data must be compatible with the destination table’s columns.
The database checks constraints when rows are inserted. For example:
A foreign-key value must refer to a valid related record.
A primary-key value must not duplicate an existing primary-key value.
These rules protect the consistency of the data.
Modifying rows with UPDATE
An UPDATE statement changes values in existing rows. The SET clause specifies the columns and new values; the WHERE clause identifies which rows should change.
For example, a retailer could reduce prices for a particular category by multiplying the existing prices by a discount factor. The condition must restrict that change to the intended category.
An update without a WHERE clause affects every row in the table. This can cause severe data corruption—for example, setting every product’s price to the same amount by mistake.
A reliable safety procedure is to run a SELECT query using the exact condition intended for the update before executing the update. The preview makes it possible to verify the targeted rows, their current values, and the number of affected records.
Syntax for updates involving multiple tables can vary across DBMS products. Database-specific behavior should be checked before relying on such statements.
Removing rows with DELETE
A DELETE statement removes rows from a table. Like UPDATE, it normally uses a WHERE clause to identify the target rows.
A delete without a WHERE clause removes every row in the table, although the table structure remains. Before deleting, a SELECT query with the same condition can preview the records that would be affected. Deleted data may be difficult or impossible to recover unless a backup exists or the operation is within a transaction that can be rolled back.
Deletion, referential integrity, and soft deletes
Deleting a record referenced by other records can affect the database’s relationships. For example, a manufacturer may still be referenced by products. How the database handles such a deletion depends on the foreign-key constraint:
Restrict prevents the parent record from being deleted while dependent child records exist. This is a protective default in many designs.
Cascade automatically deletes dependent child records when the parent is deleted. This can be useful but may remove a large amount of related data.
Set null changes the child record’s foreign-key value to
NULLwhen the parent is deleted, if the column permits it.Set default changes the foreign-key value to a predefined default, if the schema defines one.
The consequences of a deletion depend on the schema and its constraints, so those relationships must be understood before a record is removed.
A soft delete avoids physically removing the record. Instead, an application updates a status field—for example, marking a record inactive—or records a deletion timestamp. The data remains available for auditing and historical reporting, while ordinary application views can filter it out. This approach can be safer when historical records need to be retained.
Changing database structure with DDL
Data definition language (DDL) commands change database structures rather than simply changing values in rows. DROP TABLE removes an entire table, including its data, columns, and associated structure such as indexes.
Dropping a table is more destructive than deleting its rows. Safe practice includes:
Creating or verifying a reliable, recent backup.
Checking which tables, views, procedures, or other database objects depend on the table.
Testing the operation in a development or staging environment before using it in production.
Using an “if exists” option where supported to prevent a script from failing when the table is absent.
Dependencies affect the order in which tables can be dropped. If one table contains a foreign key that references another, the referencing child table generally must be dropped before the referenced parent table. Understanding this dependency structure is essential before structural changes.
Priorities for writing professional SQL
Good SQL should be developed in this order:
Correctness: The query must return accurate results or make the intended change. A fast query that gives the wrong answer is not useful and may cause harm.
Readability: Other people—and the original author later—should be able to understand, debug, and safely modify the query.
Optimization: Performance should be improved when a correct and readable query is too slow or is used frequently on substantial data.
Premature optimization can make code needlessly complex before the real performance problem is understood.
Readability can be improved by:
Adding comments that explain the reasoning behind complex logic.
Using table aliases consistently in multi-table queries.
Using explicit
JOIN ... ONconditions rather than older styles that mix join conditions intoWHERE.Placing selected columns and separate conditions on distinct lines.
Applying consistent indentation, capitalization, and comma placement.
Logical query processing and early filtering
Although a DBMS optimizer may rearrange operations to improve efficiency, a useful conceptual order for a query is:
FROMand joins identify the source rows.WHEREfilters individual rows.GROUP BYforms groups from the remaining rows.HAVINGfilters those groups.SELECTdetermines the output columns and expressions.UNION, if used, combines query results.ORDER BYsorts the final result.
This order explains why aggregate conditions belong in HAVING rather than WHERE: grouping and aggregation have not yet happened when WHERE is processed.
A central optimization principle is to eliminate unnecessary rows as early as possible. Filtering individual rows with WHERE before grouping or sorting reduces the amount of data carried into later operations, which can be more expensive.
Indexes and their trade-offs
An index is a separate data structure maintained by the DBMS to help locate rows efficiently. Like the index at the back of a book, it can direct the system to relevant records without reading every row.
Without a useful index, the database may perform a full table scan, examining each row to find matches. An index stores values in an organized form along with references to their corresponding rows, allowing the database to find matching records more quickly.
Indexes are especially useful on columns frequently used in:
WHEREfilters.Join conditions in
ONclauses.Some
ORDER BYoperations.
However, indexes have costs. They can speed up reads, particularly SELECT queries, but they make writes more expensive. When indexed data is inserted, updated, or deleted, the DBMS must also maintain affected indexes. Too many indexes can therefore slow data modification and use additional storage.
Strategic indexing balances faster searches against the costs of index maintenance. Indexes are most valuable when columns are frequently searched or joined and the read benefit outweighs the write cost. Database systems provide different kinds of indexes, including primary and secondary, clustered and non-clustered, and composite or partial indexes. The central purpose is to provide efficient lookup paths for common queries.
Sargable filters
A condition is sargable—short for “search argument able”—when it is written in a form that allows the database to use an index effectively.
Applying a function directly to an indexed column can make a condition non-sargable. For example, filtering by the year extracted from a date may require the database to calculate that year for every row before comparing it, preventing efficient use of an index on the original date column.
A more index-friendly approach is often to compare the unmodified date column with the start and end of the desired date range. This allows the DBMS to search the index for dates within that range.
Other common considerations include:
A text pattern with a leading wildcard often prevents efficient index use; a pattern with a wildcard only at the end can often use an index.
Exact-match comparisons should generally be preferred over
LIKEwhen an exact match is what the task requires.In some cases,
EXISTSwith a subquery can be more efficient thanIN, particularly when the subquery returns many rows.EXISTSchecks whether a match is present and may stop once it finds one. Actual performance depends on the DBMS and query, so it should be evaluated rather than assumed.
Optimizing joins and set operations
Join performance can often be improved by:
Joining only the tables needed for selected columns or filtering conditions.
Filtering rows before joining when possible, reducing the data the join must process.
Using an inner join when nonmatching rows are not needed. Outer joins may require extra work to preserve unmatched records and generate
NULLvalues.
Joins can also be preferable to correlated subqueries, which refer back to the outer query and may require repeated work. A single join can retrieve related data in one operation. This can also avoid the N+1 query problem in application code: the application first fetches a list of records and then issues a separate query for each record to retrieve related information. A join can often retrieve the needed information in one database request, reducing database round trips and workload.
UNION and UNION ALL
Set operations combine results from multiple SELECT statements.
UNIONremoves duplicate rows from the combined result.UNION ALLretains duplicates.
Removing duplicates requires additional work, such as comparing or sorting rows. If duplicates are acceptable or cannot occur, UNION ALL is generally more efficient. UNION is appropriate when the result specifically needs to contain unique rows.
Diagnosing performance with execution plans
When a query is slow, database systems commonly provide tools such as EXPLAIN, EXPLAIN ANALYZE, or graphical execution-plan views.
An execution plan shows how the database intends to execute—or, in some tools, actually executed—the query. It can reveal:
Which tables are accessed and in what order.
Whether indexes are used or table scans are performed.
Which join algorithms are selected.
How many rows are estimated or actually processed at each stage.
The estimated or measured cost and time of operations.
Execution plans help locate bottlenecks. They can show whether an index is being ignored, whether a join creates a large expansion of rows, or whether sorting consumes substantial time. Interpreting them is a core skill in serious query tuning.
Common table expressions and large-scale design strategies
A common table expression (CTE) is a named temporary result set defined for one query. A CTE can divide a complicated query into logical steps, making it easier to understand and maintain than a deeply nested query. Each step can be named and then referenced by a later part of the query.
Denormalization
Normalization reduces redundancy and supports data integrity, but it can require joins to assemble information for reports. For read-heavy systems where query speed is especially important, designers may use denormalization: deliberately adding some controlled redundancy to reduce the need for expensive joins.
For example, a frequently used reporting table might store a customer’s state alongside an order even though that state is also stored in the customer table. This can speed reads but creates extra responsibility to keep repeated values consistent and can make writes more complex.
Partitioning
For very large tables, partitioning divides data into smaller physical or logical sections according to a rule, such as date ranges. A table might be partitioned by month. A query that needs only recent records can then access the relevant partition rather than scanning the entire table, improving manageability and potentially query speed.
Safe testing of SQL
Data-changing SQL should never be tested against a production database. A dedicated non-production environment—such as a development database, staging server, or test database—provides a safer place to evaluate changes.
A repeatable automated test often follows these steps:
Create the required schema and tables.
Insert a small, specific set of test records.
Run the SQL being tested.
Run verification queries to confirm the resulting database state.
Clean up by truncating or dropping test tables so the next test begins in a known state.
Transactions as a safety mechanism
A transaction groups database operations so they can be committed together or undone. A test or manual debugging session can begin a transaction, run an update or delete, and inspect the results with SELECT queries.
Commit makes the changes permanent.
Rollback undoes the changes made since the transaction began.
Transactions act as a temporary safety net, provided the DBMS and the operations involved support rollback. Isolated database instances, including containerized databases or in-memory databases used for testing, can also provide controlled environments separate from production.
Ethical updates and audit trails
The ability to modify data raises ethical responsibilities as well as technical risks. Correcting a clear factual error, such as a misspelled customer name, can improve accuracy. Altering historical records to make past performance appear better or deleting unfavorable complaints changes the record rather than correcting it, undermining trust.
Responsible organizations generally treat direct production-data changes as unusual events requiring justification and, often, approval. They use audit trails or change logs to record significant modifications.
An audit trail commonly records:
Who made the change, such as a user account or automated process.
What changed, including the table, column, record identifier, and old and new values.
When the change occurred, using a timestamp.
Why the change was made, often by linking it to a support request, bug report, or stated reason.
Audit trails make changes accountable and traceable. They let an organization investigate why data differs from an earlier record and confirm that corrections were made transparently. Maintaining such records supports data integrity, organizational trust, and ethical practice.
Core principles to remember
SQL is a standard way to query and manage relational data, supporting both everyday applications and strategic analysis.
Use
SELECTto retrieve only the columns required, and useWHEREto filter individual rows.Use parentheses when combining
ANDandORso the intended logic is unambiguous.Use
GROUP BYand aggregate functions to summarize records; useHAVINGto filter those summaries.Normalize data to reduce repetition, and use primary and foreign keys to connect related tables.
Choose the join type according to whether unmatched rows should be retained, and verify every join condition.
Before an
UPDATEorDELETE, preview the target rows with aSELECTusing the same condition.Treat
DROP TABLEas a highly destructive structural operation; check backups and dependencies first.Prioritize SQL correctness, then readability, then optimization.
Use indexes strategically, filter early, and inspect execution plans when performance problems remain.
Test changes outside production, use transactions when appropriate, and record production changes transparently.

Ask anything
We've read this whole study set, so questions about it get the best answers.