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

Study methods

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

SQL Fundamentals

Speaker 1Speaker 2

SQL Fundamentals

20:00
0:00-20:00
  1. Corey

    Welcome to our SQL fundamentals episode. SQL stands for Structured Query Language, and it is the language developers use to communicate with most databases. Whether your application is written in JavaScript, Python, Go, or TypeScript, SQL will often be working alongside it.

  2. Simon

    That is because backend development is largely about moving data around. A video platform might receive a video, title, description, and thumbnail from a creator's device, store that information in a database, and later send it back to viewers. SQL provides the standard way to create, read, update, and delete that data.

  3. Corey

    A database is software that makes it easier to store large amounts of data in a computer's file system. You can think of it as a much more powerful version of Excel or Google Sheets, except that instead of manually dragging and clicking, you write queries that automate those operations. Popular SQL databases include PostgreSQL, MySQL, SQLite, Microsoft SQL Server, Oracle, and CockroachDB.

  4. Simon

    In this course, the practice database is Cashpal, a toy PayPal-like application. Its tables contain users and transactions, such as one user sending money to another. The best way to learn SQL is hands-on: write the queries yourself instead of binge-watching tutorials, because coding practice prevents tutorial hell.

  5. Corey

    Let's begin with SELECT, the statement used for read operations. A query such as SELECT ID FROM users; returns the ID column from the users table. SELECT ID, name FROM users; returns two columns, while SELECT * FROM users; uses the star, or wildcard, to return every column.

  6. Simon

    SQL keywords are generally case-insensitive, although uppercase keywords such as SELECT and FROM are the usual convention. Every SQL statement ends with a semicolon. The result of a query is normally a result set arranged as rows and columns, rather than console output like you might see in Python or Go.

  7. Corey

    SQL is a common language, but databases can have different SQL dialects. SQLite, PostgreSQL, and MySQL share the main ideas but may support different data types or features. Learning SQL transfers well between them, although production work still requires checking the details of the specific database engine.

  8. Simon

    SQL and NoSQL are not really two groups of equally similar technologies. SQL databases all support Structured Query Language, so they have a common interface and are often general-purpose. NoSQL databases simply do not use SQL, and they may have completely different query languages and designs.

  9. Corey

    NoSQL systems are often specialized. Redis is commonly used as an in-memory key-value store or cache, Elasticsearch is frequently used for search and aggregations, Firebase is useful for real-time and mobile applications, and DynamoDB is Amazon's database designed for data at scale. MongoDB is more general-purpose than some of those examples.

  10. Simon

    For many straightforward web applications, PostgreSQL is a strong starting point because it is general-purpose and can handle substantial scale. SQLite is different: it is embedded directly into an application and works well when resources are constrained, such as on mobile devices or at the edge. PostgreSQL acts as a database server and generally offers more features, stricter type checking, and better support for very large or complex applications.

  11. Corey

    SQLite has a relatively loose type system. If a column is declared as TEXT, SQLite may still allow an integer to be inserted into it. PostgreSQL would generally enforce the declared type more strictly. SQLite supports null, integer, real values, text, and blobs, and Boolean values are represented as 0 and 1 when returned, even though you can write FALSE and TRUE in a query.

  12. Simon

    Tables are made of columns and rows. A column describes an attribute, such as name or age, while each row is a record containing values for those columns. You create a table with syntax like CREATE TABLE employees, followed by column definitions such as ID INTEGER, name TEXT, age INTEGER, and is_manager BOOLEAN.

  13. Corey

    Cashpal's basic tables illustrate the same idea. A users table might contain ID, handle, name, age, balance, and an administrative flag. A transactions table might contain an ID, recipient ID, sender ID, a note, and an amount. The CREATE TABLE statement can be formatted over several lines to make the schema easier to read.

  14. Simon

    To change an existing table, use ALTER TABLE. You can rename a table with ALTER TABLE employees RENAME TO contractors, rename a column with RENAME COLUMN salary TO invoice, add a column with ADD COLUMN, or remove one with DROP COLUMN. Renaming tables and columns in a live application can be dangerous because existing code may still expect the old names.

  15. Corey

    That brings us to database migrations. A migration is an incremental change to a database schema, such as adding a table, adding a column, deleting a column, or changing a name. Adding is usually safer because old application code did not depend on the new resource. Deleting is more dangerous, so update the application code first to stop using the resource, then remove it from the database.

  16. Simon

    Changing a name is harder because old code expects the old name while new code expects the new one. Options include scheduled downtime, deploying the database and code at exactly the same time, copying the table and moving carefully to the copy, or using aliasing when the database supports it. Aliasing allows old and new code to reference two names temporarily, after which the old name can be removed.

  17. Corey

    Migrations are commonly described as up and down migrations. Up migrations move the schema forward through successive changes. Down migrations reverse their corresponding up migrations so the schema can be rolled back if something goes wrong. Reversing a schema change does not always restore data that was already deleted, so migrations must be treated carefully.

  18. Simon

    A database schema is the shape of the data: its tables, table names, columns, types, and relationships. There is no single perfect schema, but a useful rule is to keep it as simple as possible while accurately representing the application's relationships. Simplicity makes future changes easier.

  19. Corey

    Money deserves special attention. Financial applications often store amounts as integers representing the smallest unit, such as cents, rather than using floating-point numbers. Instead of storing 5.67 dollars, the system can store 567 cents. Integers avoid the rounding problems that can occur with floating-point arithmetic.

  20. Simon

    Null means the absence of a value. It is different from an empty string, zero, or FALSE. A blank username is a string with length zero; a null username means no value is present. SQL's null is similar to None in Python, null in JavaScript, or nil in Go, and it is often preferable when a value is genuinely absent.

  21. Corey

    Constraints enforce rules on the schema. NOT NULL requires a value, UNIQUE prevents duplicate values, and PRIMARY KEY identifies records uniquely. A primary key is unique, cannot be null, and a table normally has only one primary key. The conventional design is an integer ID column used as the primary key, rather than using a business value such as an email address.

  22. Simon

    Using a dedicated ID is safer because business rules can change. An application might eventually allow two users to share an email address, but changing an email that has been used as an identifier throughout the codebase would be painful. IDs are intended to remain stable even when other user information changes. Some systems use UUIDs instead: randomly generated identifiers with an extremely low chance of collision.

  23. Corey

    A foreign key connects tables. If a transactions table contains a user ID that refers to the ID in a users table, that user ID is a foreign key. Adding a FOREIGN KEY constraint ensures that the referenced record actually exists. For example, an employee's department ID can reference the ID of a real department, preventing an employee from being assigned to a nonexistent department.

  24. Simon

    Relational databases organize data into tables and use keys to connect related records. A non-relational database usually does not support those same complex relationships and often nests data, sometimes resembling large JSON objects. Nesting can be convenient, but it may duplicate information: if several users belong to the same course, each user record might contain its own copy of the course.

  25. Corey

    There are three important relationship types. In a one-to-one relationship, one record corresponds to one record, such as a class and its name. This can usually be represented as another column on the same table. In a one-to-many relationship, one record can relate to zero or many records, such as one user and many tweets. The foreign key normally belongs on the table representing the many side.

  26. Simon

    A many-to-many relationship needs a joining table. Users and groups are a good example: one user can join many groups, and one group can contain many users. The joining table might be called users_groups and contain only user ID and group ID. A unique constraint across both columns prevents the same relationship from being recorded twice.

  27. Corey

    Normalization is the practice of organizing data to reduce redundancy and improve integrity. First normal form requires every row to have a unique primary key and prohibits nested tables. Second normal form adds the idea that non-key columns must depend on the entire primary key, not merely part of a composite key. Third normal form says non-key columns should depend only on the primary key.

  28. Simon

    Boyce-Codd normal form adds another rule for unusual cases involving multiple possible candidate keys: a column that is part of a primary key cannot depend on a column outside the primary key. In everyday backend work, memorizing those academic definitions is less important than applying the practical goal: avoid duplicate data and keep each fact stored in the appropriate place.

  29. Corey

    For example, storing both a user's birthday and a precomputed age can create an integrity problem, because the age becomes incorrect as time passes. Store the raw birthday and calculate the age when needed. Likewise, if an address is copied into two tables, changing it in one place but forgetting the other can create conflicting data.

  30. Simon

    The basic database operations are summarized by CRUD: create, read, update, and delete. They map neatly to SQL and HTTP. SQL INSERT usually corresponds to an HTTP POST, SELECT to GET, UPDATE to PUT, and DELETE to DELETE. In a common web architecture, the front end communicates with the backend over HTTP, and the backend communicates with the database using SQL.

  31. Corey

    To insert rows, use INSERT INTO users, list the columns, and provide VALUES in that exact order. For example, INSERT INTO users, followed by name, age, country code, username, password, and is admin, can add a user. When the ID column is an auto-incrementing primary key, you can omit it and let the database generate the next identifier.

  32. Simon

    In production, these values are not usually typed into one-off SQL statements by hand. Backend code constructs queries dynamically from user actions, often through a database library or ORM. An ORM maps programming-language objects or structs to database rows and lets you call methods such as create, update, or delete instead of writing every statement manually.

  33. Corey

    ORMs make code less verbose, but they trade some control for convenience. They can generate inefficient queries or make low-level debugging harder, so a good ORM should still provide an escape hatch for raw SQL. Whether to use one depends on the project and team, but many production systems use an ORM for routine operations and raw SQL for specialized queries.

  34. Simon

    For reading data, WHERE filters rows. SELECT username FROM users WHERE is_admin = TRUE returns only usernames of administrators. You can combine conditions with AND and OR, use parentheses to control the order, and remember that SQL uses a single equals sign for equality. IS NULL and IS NOT NULL are the special forms for checking missing values.

  35. Corey

    The IN operator is shorthand for several OR conditions. A condition such as country_code IN, followed by the United States, Canada, and Mexico, finds users from any of those countries. LIKE supports partial matching: a percent sign represents zero or more characters, so LIKE 'Al%' finds names beginning with Al, while LIKE '%lunch%' finds the word lunch anywhere in the text.

  36. Simon

    An underscore in a LIKE pattern represents exactly one character. A pattern with two underscores followed by a fixed ending can require a specific total length. BETWEEN checks whether a value falls within two bounds, and NOT BETWEEN selects values outside them. DISTINCT removes duplicate values from the result, which is useful when you want each country code only once.

  37. Corey

    LIMIT prevents a query from returning more than a specified number of rows. That matters when a production table contains millions of records and selecting everything would strain the system. ORDER BY sorts the result, ascending by default or descending when explicitly requested. A common pattern is to sort first and then apply LIMIT, such as finding the five largest transactions.

  38. Simon

    The DELETE statement removes rows, and this is where caution is essential. DELETE FROM users WHERE ID = 2 removes one known user, but DELETE FROM users with no WHERE clause removes every user. A good safety habit is to run the intended WHERE condition as a SELECT first, inspect exactly what will be affected, and only then change SELECT to DELETE.

  39. Corey

    UPDATE changes existing rows. Its structure is UPDATE users SET is_admin = TRUE WHERE ID = 9. The WHERE clause is just as important here as it is for DELETE, because omitting it updates every row. Use a specific primary key whenever you intend to change one record.

  40. Simon

    Production data also needs backups. A common simple strategy is taking automated snapshots daily or hourly and storing them in inexpensive cold storage such as an object-storage bucket. Snapshots are easy to set up and may be sufficient for smaller applications, but restoring the latest snapshot can lose changes made after that snapshot.

  41. Corey

    A more robust strategy records every change in an append-only log. If a record is created and later deleted, the log still preserves both events, allowing the system to replay changes and recover more precisely. That approach costs more complexity and money, so it is generally reserved for systems that cannot afford to lose recent data.

  42. Simon

    Another option is a soft delete. Instead of physically removing a row, add something such as a deleted_at timestamp and have application queries ignore marked rows. Soft deletes make recovery easier, but they add filtering complexity, can make large tables slower, and may conflict with privacy requirements such as a user's right to have data truly removed.

  43. Corey

    SQL also supports functions. IIF can return one value when a condition is true and another when it is false, which is useful for computed columns. For example, an audit column can say 'no action required' when was_successful is true and 'perform an audit' otherwise. The AS keyword gives a column or expression a temporary alias, such as renaming note to birthday_message in the result.

  44. Simon

    Aggregations reduce many rows to a value. COUNT finds the number of rows, SUM adds values, MAX finds the largest, MIN finds the smallest, and AVG calculates an average while ignoring null values. GROUP BY lets you perform an aggregation separately for each group, such as calculating the total transaction amount for every user.

  45. Corey

    WHERE and HAVING are easy to confuse. WHERE filters individual rows before grouping and aggregation. HAVING filters the grouped results afterward. So if you want only a particular user ID, use WHERE; if you want groups whose calculated transaction total exceeds 20, use HAVING. ROUND can then format a numeric result to a desired precision, such as a whole-number average age.

  46. Simon

    A subquery is a query nested inside another query, surrounded by parentheses. It is useful when one query supplies values to another. For example, if customer support knows David's name but not his ID, the outer query can select transactions where user_id equals the result of an inner query that selects David's ID from users.

  47. Corey

    Subqueries can also perform calculations without a backing table. If ages are stored in days, a condition can compare age_in_days to 40 multiplied by 365. The key point is that a subquery is not automatically a temporary table or a performance optimization; it is simply a way to use the result of a nested query.

  48. Simon

    Joins combine data from multiple tables. An inner join returns rows with matching records in both tables. For example, users can be joined to countries where users.country_code equals countries.country_code. Qualifying column names with the table name and a dot prevents ambiguity when both tables contain columns such as ID or name.

  49. Corey

    A left join returns every row from the left table, even when there is no matching row on the right. That is useful when reporting every Cashpal user, including users with no transactions. A right join is usually unnecessary because you can swap the table order and use a left join instead. A full join returns every row from both tables, whether or not a match exists.

  50. Simon

    Joins can be chained across more than two tables, but larger joins may become expensive. When joining transactions to users and then aggregating, group by the user ID so multiple transaction rows become one result row per user. Without aggregation, a user with several related transactions can appear in several result rows.

  51. Corey

    Performance should usually come after correctness and a sensible schema. An index is an in-memory structure, often based on a binary tree, that makes lookups much faster. A primary key is commonly indexed automatically. If the application frequently runs a query such as SELECT FROM users WHERE email equals a value, an index on email can avoid scanning every row.

  52. Simon

    Indexes are not free. They consume memory, and inserts or updates must keep the index structure current, which can slow writes. Therefore, do not index every column automatically. Add indexes to columns used frequently in lookups when there is a real performance need. A multi-column index is useful for a common combination of conditions, and its column order matters: lookups on the first column benefit most.

  53. Corey

    Sometimes a normalized design becomes slow because it requires many joins or repeated aggregations. Denormalization deliberately introduces duplicate or precomputed data to speed up a hot query, such as storing a user's transaction count instead of calculating it every time. This can improve reads but creates integrity risks, because the duplicate value can fall out of sync.

  54. Simon

    So the practical rule is to begin with a normalized database and denormalize only when measurement shows that performance requires it. Correct, nonduplicated data is normally more valuable than premature speed optimizations. Caches and precomputed values can be useful, but cache invalidation and keeping copies synchronized add real complexity.

  55. Corey

    Finally, SQL injection is a major security risk. If user input is directly concatenated into a query, an attacker may insert SQL that changes the meaning of the statement, potentially turning an innocent insert into multiple statements and dropping an entire table. Never build dynamic SQL with ordinary string concatenation, template literals, f-strings, or similar raw interpolation.

  56. Simon

    Instead, use parameterized queries or a trustworthy database library that safely handles interpolation and sanitizes user-provided values. Nearly every serious database client provides this protection. The most important SQL lessons fit together: model relationships accurately, use constraints to protect integrity, query deliberately with filters and joins, treat migrations and deletion as dangerous, back up production data, and optimize with indexes only when needed.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent