1. Home
  2. Explore
  3. Computer Science
  4. SQL and Database Fundamentals

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

SQL and Database Fundamentals

Speaker 1Speaker 2

SQL and Database Fundamentals

18:20
0:00-18:20
  1. Maria

    Every time you log in to a streaming service, check your bank balance, swipe a student ID, or track a package, something is happening behind the scenes: an application is asking a database to look up or change information. That steady exchange of data is part of what makes our digital world work.

  2. Corey

    And SQL is one of the key ways we communicate with databases. It’s not only for programmers. A business can use SQL to answer questions like which products sell best, who its most valuable customers are, or when sales tend to rise. It turns questions about a business into instructions a database can process.

  3. Maria

    Let’s use a fictional retailer, Redcat Shoes, to make the ideas concrete. The starting point for retrieving information is the SELECT statement, which tells the database which columns you want, and the FROM clause, which names the table to get them from.

  4. Corey

    For example, `SELECT product_name, price FROM sales;` asks for two columns from the sales table. You’ll sometimes see `SELECT *`, where the asterisk means all columns. That’s handy for a quick look, but it’s usually a poor choice in production code or on a large table.

  5. Maria

    Because `SELECT *` makes the database fetch every column, even when you need only a couple. On a very large table, that can increase reading and memory demands and slow a query. Naming only the columns you need is more efficient and makes the query easier for another person to understand.

  6. Corey

    Once we’ve picked the columns, `WHERE` lets us filter rows. If Redcat wants sneaker records, for instance, it could use `WHERE category = 'sneakers'`. The database returns rows where the condition is true, rather than making us sift through every result ourselves.

  7. Maria

    Conditions can use comparison operators for exact matches, inequality, and less-than or greater-than comparisons. They work with values such as numbers and dates, as well as text. For example, `WHERE price > 100` finds products priced above 100.

  8. Corey

    For patterns in text, SQL also has `LIKE`. A percent sign is a wildcard that can match any sequence of characters, including no characters. So `WHERE product_name LIKE 'Men%'` finds names that begin with “Men.” With dates, comparisons let you select a date or a range of dates.

  9. Maria

    To combine conditions, use the logical operators `AND`, `OR`, and `NOT`. `AND` requires every connected condition to be true, so `WHERE category = 'sneakers' AND color = 'black'` finds black sneakers. `OR` requires at least one condition to be true, so it can broaden the results.

  10. Corey

    There’s a subtle but important rule when `AND` and `OR` appear together: `AND` has higher precedence, much like multiplication before addition in arithmetic. If you mean “sneakers or boots, but only when made by Nike,” group the alternatives: `WHERE (category = 'sneakers' OR category = 'boots') AND manufacturer = 'Nike'`.

  11. Maria

    Parentheses make that intention unmistakable and help prevent surprising results. `NOT` reverses a condition, too, and parentheses are just as useful when you combine it with other logical operators.

  12. Corey

    What if Redcat wants the manufacturers it carries, without seeing the same manufacturer repeated for every sale? `SELECT DISTINCT manufacturer_name FROM sales;` removes duplicate results. DISTINCT applies to the full set of selected columns, so selecting manufacturer and color returns unique manufacturer-color pairs.

  13. Maria

    After retrieving data, we can make it easier to read with `ORDER BY`. By default, results are sorted in ascending order: text from A to Z, numbers from small to large, and dates from early to late. `DESC` requests descending order; `ASC` can state ascending order explicitly.

  14. Corey

    You can sort on multiple columns, too. `ORDER BY color ASC, price DESC` sorts by color first, then puts the most expensive products first within each color. Sorting changes the order of the results, not which rows the query returns.

  15. Maria

    For business summaries, `GROUP BY` brings rows with the same value together so SQL can calculate something for each group. Aggregate functions include `COUNT` for counting rows, `SUM` for adding numeric values, `AVG` for an average, and `MIN` and `MAX` for the smallest and largest values.

  16. Corey

    Suppose Redcat wants revenue by category. It could group sales by category and sum price times quantity: `SELECT category, SUM(price * quantity) AS total_revenue FROM sales GROUP BY category;`. The alias `total_revenue` gives the calculated result a clear label.

  17. Maria

    And if Redcat wants only categories whose revenue exceeds a threshold, that’s where `HAVING` comes in. `WHERE` filters individual rows before grouping; `HAVING` filters the groups after aggregation. So a revenue condition based on `SUM(price * quantity)` belongs in `HAVING`, not `WHERE`.

  18. Corey

    That distinction matters because SQL handles rows and groups at different stages. In general, filter individual sales with `WHERE` before grouping, and use `HAVING` to keep or exclude the resulting category summaries.

  19. Maria

    So far, our sales table has been a teaching shortcut. A real database usually shouldn’t repeat everything—customer names and addresses, product descriptions, manufacturer details, and sale information—in one giant table. Repeating a customer’s address with every purchase wastes space and makes corrections risky.

  20. Corey

    If that customer moves, for example, the address might need to be changed in many rows. Miss one, and the database can end up with conflicting information. Normalization is the practice of organizing data into related tables to reduce this kind of unnecessary repetition and improve consistency.

  21. Maria

    Redcat might have separate customer, product, manufacturer, and sale tables. Each table has a primary key: a value, often an ID, that uniquely identifies each row. A foreign key is a column in one table whose values refer to a primary key in another.

  22. Corey

    So a sale can store a customer ID and a product ID instead of copying the customer’s address and the product’s full description into every transaction. The IDs point to the related records. That reduces repetition while preserving the relationships among the data.

  23. Maria

    When information is split across tables, SQL joins let us bring related data together in a query. An inner join returns rows where the join condition finds a match in both tables. If a product has never been sold, for instance, it won’t appear in an inner join between products and sales.

  24. Corey

    A join needs an explicit condition that tells the database how the tables connect. If sales and products share a product ID, the condition could be `ON sales.product_id = product.product_id`. We can then filter for sneaker products and retrieve information from both tables.

  25. Maria

    It’s best to name the columns we need instead of selecting every column from both joined tables. Explicit columns reduce unnecessary data, clarify where each value comes from, and avoid ambiguity if two tables contain columns with the same name.

  26. Corey

    And we can chain joins to follow several relationships. A sale can link to a product by product ID, and the product can link to a manufacturer by manufacturer ID. If we also need customer information, we can join the customer table through the sale’s customer ID.

  27. Maria

    Aliases are short, temporary names for tables within a query. For example, we might write `FROM sale AS s JOIN product AS p ON s.product_id = p.product_id`. Then `s.sale_date` and `p.product_name` are shorter and clearer than repeating full table names throughout a complex query.

  28. Corey

    A request like “show products made by Texas manufacturers that were sold to customers in California” could require joins from sales to products, manufacturers, and customers. The join conditions follow the foreign-key relationships, and filters on the customer and manufacturer states narrow the results.

  29. Maria

    Inner joins aren’t the only option. A left join keeps every row from the table on the left and adds matching information from the right when it exists. If there’s no match, the right-hand columns are NULL. That’s useful if Redcat wants every product listed, including products that have never sold.

  30. Corey

    A right join does the reverse, keeping all rows from the right-hand table. A full outer join keeps rows from both sides, matched or not, and uses NULL where information on the other side is missing. A Venn diagram is a helpful image: inner join is the overlap, while outer joins include unmatched parts of one or both circles.

  31. Maria

    Be meticulous about join conditions. If you omit the condition or match the wrong columns, you can create a Cartesian product: every row from one table combined with every row from the other. A thousand rows in each table can produce a million combinations, which can consume significant database resources.

  32. Corey

    You may also encounter `NATURAL JOIN`, which tries to infer join columns from matching column names. Because that guess can be affected by changes in names or table structure, explicit joins are generally clearer and less likely to surprise you.

  33. Maria

    SQL also changes data, not just retrieves it. The data manipulation language includes `INSERT`, `UPDATE`, and `DELETE`. `INSERT` adds rows, and it’s good practice to list the columns explicitly so it’s clear which value goes where and the statement is less vulnerable to table changes.

  34. Corey

    For example, an insert might specify customer ID, first name, last name, state, and email, followed by the corresponding values. Columns you leave out receive their default values if defined; otherwise, they typically receive NULL. NULL means a value is unknown, missing, or not applicable—it is not the same as zero or an empty string.

  35. Maria

    You can also insert rows selected from another table, such as copying qualifying old sales into an archive table. But constraints help protect data integrity: the database should reject a sale that refers to a customer ID that doesn’t exist, or an attempt to reuse a primary key that must be unique.

  36. Corey

    `UPDATE` changes existing rows. Its general shape is `UPDATE table_name SET column_name = value WHERE condition;`. That `WHERE` clause is crucial: without it, the update applies to every row. An update meant to discount one category could accidentally change every product’s price.

  37. Maria

    A safe habit is to run a `SELECT` with the same `WHERE` condition before running an update. Check which rows and values it returns. Only when you’re confident the selection is right should you run the update. The details of updates involving multiple tables can vary among database systems, so check the system you’re using.

  38. Corey

    `DELETE` removes rows, and it has the same essential warning: without a `WHERE` clause, it deletes all rows in the table. Preview the target rows with a `SELECT` first. Once deleted, data is generally gone unless a backup or an open transaction gives you a way to restore it.

  39. Maria

    Foreign-key relationships also affect deletion. A database may restrict deleting a parent record while related child records exist; cascade the deletion to those child records; or set the child foreign key to NULL or a default. You need to understand the schema and the configured behavior before deleting related data.

  40. Corey

    Some organizations use a soft delete instead of removing a record physically. They update a status such as `is_active` or add a deletion timestamp, then have ordinary application views filter the record out. That leaves the information available for reporting or auditing.

  41. Maria

    There’s an important distinction between deleting rows and dropping a table. `DELETE` removes records but leaves the table structure. `DROP TABLE` removes the table itself—its data and structure, including its columns and indexes. It’s a much more drastic structural change.

  42. Corey

    Before dropping a table, have a reliable backup, check what other tables or database objects depend on it, and test the change in a non-production environment. `DROP TABLE IF EXISTS` can keep a script from failing if the table isn’t there, but it doesn’t replace those safety checks.

  43. Maria

    Dependencies also affect the order of operations. If table B has a foreign key pointing to table A, B is the referencing, or child, table. You generally need to drop B before A, because A is still referenced by B.

  44. Corey

    When writing SQL, prioritize correctness first: a fast query that returns the wrong answer is useless and can be harmful. Next comes readability, so people can review, debug, and safely change the query. Optimize after that when there’s a real performance need.

  45. Maria

    Readable SQL is easier to maintain as a team. Comments can explain why complex logic is there; consistent aliases make joins easier to follow; and explicit `JOIN ... ON` conditions separate table relationships from filtering conditions. Consistent line breaks, indentation, and capitalization also make a query’s structure easier to see.

  46. Corey

    It helps to understand the usual logical flow of a query: `FROM` and joins identify the data source; `WHERE` filters rows; `GROUP BY` forms groups; `HAVING` filters those groups; `SELECT` chooses output columns; `UNION`, if present, combines results; and `ORDER BY` sorts the output. A database optimizer may change how it executes a query, but the logical sequence is a useful mental model.

  47. Maria

    For performance, try to eliminate unwanted data early. A `WHERE` condition filters rows before grouping, so fewer rows need to go through later work such as aggregation or sorting. This is one reason to apply appropriate filters as early as you can.

  48. Corey

    Indexes are another major tool for speeding up searches. Think of the index at the back of a textbook: instead of reading every page to find a topic, you use the index to locate it. A database index stores values in a searchable structure with pointers to their rows, helping the database avoid a full table scan.

  49. Maria

    But more indexes aren’t automatically better. They can speed up reads, such as `SELECT` queries, while slowing writes. When data in an indexed column changes, the database must maintain the associated indexes too. Index columns often used in filters, joins, or sometimes sorting, but consider the cost before indexing every column.

  50. Corey

    A query is called sargable when its search condition is written so the database can use an index effectively. For example, putting a function around a date column—like asking for `YEAR(order_date) = 2023`—can make it harder to use an index on that column.

  51. Maria

    A date range can express the same idea in a more index-friendly way: `order_date >= '2023-01-01' AND order_date < '2024-01-01'`. The column is left unwrapped, so an index on the date may help the database locate the range.

  52. Corey

    Other conditions can affect index use, too. A pattern such as `LIKE '%smith%'`, with a wildcard at the beginning, generally prevents using an index for that pattern; `LIKE 'smith%'` can often use one. Prefer exact matches over `LIKE` when that meets the need, and consider whether `EXISTS` or `IN` is more suitable for a subquery, especially when it returns many rows.

  53. Maria

    For efficient joins, include only tables you need, and filter data before joining when possible so the join has fewer rows to process. An inner join can be faster than an outer join when unmatched rows aren’t needed, because an outer join also has to preserve those nonmatching rows.

  54. Corey

    A single join can also be more efficient than a correlated subquery that is evaluated in relation to each outer row. In application code, the related problem is the N-plus-one pattern: fetch a list, then issue another query for each item. One query with joins can often retrieve the related data in one go.

  55. Maria

    Set operations can combine results from multiple `SELECT` statements. `UNION` removes duplicate rows, which takes extra work. `UNION ALL` keeps duplicates and is generally faster, so use it when duplicates are acceptable or you know there won’t be any.

  56. Corey

    When a query is slow and the cause isn’t obvious, look at its execution plan. Tools such as `EXPLAIN` or `EXPLAIN ANALYZE` show how the database plans to run—or did run—the query. Depending on the system, you can inspect table access, index use, joins, row counts, and estimated or actual costs and times.

  57. Maria

    A common table expression, or CTE, is another tool for complex queries. Defined with `WITH`, it names a temporary result set for one query. You can split a long sequence of steps into named pieces instead of burying the logic in deeply nested subqueries, making it more readable and maintainable.

  58. Corey

    Normalization supports consistency, but some read-heavy applications deliberately use controlled denormalization: they add some redundancy to avoid expensive joins and speed up reads. That trade-off can make writes less efficient and requires care to keep repeated values consistent.

  59. Maria

    For very large tables, partitioning can split data into smaller sections according to a criterion such as date range. A query limited to one period may then need to scan only the relevant partition rather than the entire table. It’s one way databases manage tables with extremely large numbers of rows.

  60. Corey

    All of these powerful commands need a safe testing process. Never test against the production database. Use a separate development, staging, or test environment. For repeatable tests, create the required schema, load specific test data, run the SQL, verify the results, and clean up so the next test starts from a known state.

  61. Maria

    Transactions are especially useful when manually checking a risky change. Start a transaction, run the update or delete, and inspect the results. If everything is right, `COMMIT` makes the changes permanent; if not, `ROLLBACK` undoes the work since the transaction began.

  62. Corey

    That gives you a temporary safety net, but it doesn’t replace a separate test environment. Development workflows can also use isolated database instances, such as containers, or in-memory databases for fast tests. The central principle is to keep experimentation controlled and separate from production.

  63. Maria

    There’s an ethical side to data changes, too. Correcting a factual error, such as a misspelled customer name, can support accuracy. Changing historical records to make sales look better or deleting complaints to hide them is different: that manipulates the record and can undermine trust.

  64. Corey

    Responsible organizations make direct production changes rare, require approval and a strong reason, and keep audit trails. Those logs can record who made a change, what table or value changed—including old and new values—when it happened, and why, such as a linked support ticket or bug report.

  65. Maria

    The point of an audit trail is accountability, not hiding corrections. If someone asks why a figure changed, there’s a verifiable history. Even a legitimate correction can be transparent: the record shows what changed, who changed it, when, and why.

  66. Corey

    So the big picture is that SQL helps retrieve, connect, summarize, and modify the information behind everyday services and business decisions. Start with correct queries, make them readable, optimize when there’s a real need, and take special care with changes that affect valuable data.

  67. Maria

    And keep the relationships in mind: normalization organizes data into related tables, keys connect those tables, and joins bring the information together when we need the full picture. Behind a login, a purchase, or a package update, that careful work with data is part of what makes the interaction possible.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent