Core Concepts for Manipulating Databases with SQL, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 5.4 Free with a free account

Core Concepts for Manipulating Databases with SQL

Database Programming · Chapter 5: Querying, Filtering, and Sorting DataSection 5.4 · lesson 29 of 769 min · free with a free account

← Handling Missing Values with the ISNULL FunctionNext lesson: Ordering Results: Sorting Techniques in SQL →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Set-based updates, expressions, operator precedence, and logical clause order in SQL.

  • Describe a change as one set-based UPDATE instead of a row-by-row application loop
  • Apply arithmetic and logical operator precedence, using parentheses to make grouping explicit
  • Compare integer division and string concatenation behavior in SQLite, MySQL, and SQL Server
  • Trace the logical order of FROM, WHERE, GROUP BY, HAVING, SELECT, and ORDER BY

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,050 words). Read along, or search it.

Opening Question

One Statement Instead of Many Updates

Leo Park develops Lantern Books' application. To increase every book's stock, he proposes fetching products and sending a separate update for each one. Amina asks a different question: which rows qualify, and what should happen to them? Can one statement describe that whole request? SQL works naturally with collections of rows. Expressions define values, conditions choose rows, and logical clause order explains when each part of the request has meaning.

Set-Based Thinking

Result Sets, Bags, and Row Order

This disposable copy contains our canonical eight products, with the same illustrative category extension. We can safely change this copy without redefining later lessons' starting data. A result set is the rows returned by a query. Despite the name set, SQL commonly preserves duplicates; technically many results behave as bags. Set-based thinking describes the collection to process. The engine chooses an execution plan; the statement does not prescribe a loop through particular record positions. A statement can affect every qualifying row, or none. An empty result is valid, and an update with no matches need not indicate a failure. Row order is a separate concern. Use order by for presentation; insertion order is not a promise.

Worked Example

One UPDATE for Every Book

Update states the transformation: add two to stock. The where condition identifies every book, without naming each qualifying identifier. This is one logical operation, rather than a sequence of application round trips. It can reduce overhead and let the engine optimize access. That does not mean processors physically change every row at the same instant. Set-based describes our request, not a promise about internal machinery. Run the disposable update, then select its qualifying records. Each demonstration starts fresh. Every book gains two stock units. Products in other categories are outside the predicate, and their values remain unchanged in this copy.

Expressions

Calculating Inventory Value With an Alias

An expression reduces to a value. A column, a numeric literal, quoted text, a function call, or a calculation can all be expressions. Multiplying price by stock produces an inventory value for each product. The word as gives that calculated column a readable alias. A comparison tests the calculated value against a threshold. Ordinary comparisons can be true, false, or unknown; where retains only true records. Run the query. The result contains products whose individual stock value exceeds the threshold, sorted using the alias in order by. Database Basics and Statistics Workbook qualify. Calculate and filter directly, without storing another column that could become stale.

Operator Precedence

Arithmetic Grouping and Integer Division

Operator precedence decides how expressions are grouped. Multiplication, division, and remainder bind more tightly than addition and subtraction; parentheses override that default grouping. In the first expression, multiply five by three before adding twenty. In the second, parentheses force the addition before multiplication. Division has dialect-sensitive types. SQLite and SQL Server truncate integer division, while MySQL's slash division returns a decimal and its div operator supplies integer division. Run these expressions to see this SQLite build's values. Making one division operand noninteger preserves a fractional result here. The arithmetic results are thirty-five and seventy-five. The division results distinguish three from three point five, and the remainder is one.

Logical Operators

NOT, AND, OR, and Parentheses

Logical operators combine comparisons. NOT binds before AND, and AND binds before OR; explicit parentheses make a mixed condition easier to audit. Here a product must be a book or have sufficient stock, and must also satisfy the price ceiling. The parentheses keep that ceiling attached to both alternatives. Run the selection. Each row supplies values, while the engine locates qualifying records. World History, Notebook, and Pen Set qualify. The membership question is row-based, even though the request handles all qualifying records in one statement.

Text and NULL

Concatenation Differs Across Engines

Concatenation joins text pieces into one value. MySQL's concat takes arguments, while SQL Server also offers concat and its plus operator. A missing part has different effects: MySQL concat propagates null, but SQL Server concat treats null as empty text. Concat with separator skips missing arguments. Coalesce can supply an empty middle-name replacement, though spacing still needs thought. Matching names does not guarantee matching missing-value behavior. SQLite here uses double pipes for concatenation. SQL Server twenty twenty-five also supports pipes; older SQL Server releases differ, and MySQL's default pipes mean logical or. Arithmetic has similar caveats. Null arithmetic remains null; division by zero can warn, return null, or error depending on engine, context, and session settings.

Clause Order

Tracing the Logical Clause Pipeline

Trace the clauses: from chooses products, where keeps positive-stock rows, and group by collects equal categories. That is their logical order. Having filters the resulting groups. Count star counts their rows; sum adds each group's inventory values; select builds the reported columns and their aliases. Order by arranges the output, and a row limit would choose a final window. Distinct, when requested, removes duplicate output rows after projection. Run the grouped report. The count condition keeps categories with at least two qualifying products, before ordering their total values. Book totals eight hundred six, and Stationery totals three hundred. Equipment has only one product, so it fails the group condition despite having positive stock.

Portability Rule

Repeat Expressions Instead of Aliases in WHERE

Logical order explains a portable habit: repeat an expression in where, because a select alias is conceptually created later. MySQL and SQL Server enforce this restriction. SQLite accepts some aliases in where as a nonstandard extension. Local success does not establish portability. Aggregate conditions belong in having, after grouping. Logical order explains meaning; the optimizer can physically rearrange work when it preserves that meaning.

Quick Check

A Packing Charge Without Parentheses

A new packing expression adds a fixed charge to six items at four units each. The written expression has no parentheses. Which amount does it return? Pause, and decide.

Answer

Multiplication Before Addition Gives 41

The answer is forty-one. Multiplication combines six and four first, producing twenty-four; adding seventeen gives the returned amount. Ninety-two would require parentheses around the addition. Sixty-eight does not follow either grouping of this expression, so it cannot describe the displayed calculation. A syntactically valid expression can still encode the wrong business intent. Parentheses are inexpensive documentation when the intended grouping might be misunderstood.

Key Takeaways

Collections, Expressions, and Logical Clause Order

Leo can describe the stock adjustment as one qualified update. He can also explain why a computed column's alias belongs in sorting, while a group test belongs in having. Think in collections, construct values with expressions, and make operator grouping explicit. Check types and null behavior before assuming the same spelling means the same thing. Trace logical clause order to debug meaning. Then inspect the actual execution plan when performance is the question, because logical stages are not a physical timetable.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Core Concepts for Manipulating Databases with SQL

What is the logical order of SQL clauses in a SELECT query?
A SELECT query is logically processed in the order FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, and finally LIMIT or TOP. This explains why MySQL and SQL Server reject a SELECT alias in WHERE, since WHERE runs before SELECT creates it, while ORDER BY can use the alias. The optimizer may physically execute steps in another order, but the results must match this logical order.
Why does 7 / 2 return 3 in some databases?
When both operands are integers, SQLite and SQL Server perform integer division and discard the fraction, so 7 / 2 returns 3. MySQL's / operator returns a decimal result, 3.5000, and its DIV operator performs integer division instead. Writing one operand as a decimal, such as 7.0 / 2, produces a fractional result of 3.5 in all three systems. The remainder operator is separate: 7 % 2 returns 1.
Why does CONCAT return NULL in MySQL?
MySQL's CONCAT returns NULL whenever any argument is NULL, so one missing middle name blanks the whole label. SQL Server's CONCAT treats NULL arguments as empty strings instead. CONCAT_WS skips NULL arguments in both systems, or you can wrap the nullable column, as in COALESCE(middle_name, ''). MySQL also treats || as logical OR by default rather than concatenation, unlike SQLite and standard SQL.
What does set-based thinking mean in SQL?
Set-based thinking means describing which rows qualify and how they change in one statement, instead of looping through rows one at a time in application code. For example, UPDATE products SET stock = stock + 2 WHERE category = 'Book' changes every book in a single statement, while rows outside the condition stay unchanged. If no rows match, the statement succeeds with zero rows affected rather than raising an error.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →