Showing posts with label Fixed. Show all posts
Showing posts with label Fixed. Show all posts

Saturday, July 25, 2026

Module 6: SQL Combining Conditions with AND & OR

Module 6

Combining Conditions with AND & OR

A step-by-step, hands-on SQL practice lesson — with a live query playground

SELECT * FROM employees WHERE department = 'Sales' AND status = 'Active';

So far every filter you've written has checked one thing at a time. Real questions are rarely that simple — "Sales employees who are also active," or "anyone in Sales or Marketing." This lesson covers AND and OR, the two keywords that let you combine multiple conditions into one precise query — plus the single most common mistake beginners make when mixing them.

Introduction

What You'll Learn — and Why It Matters

๐ŸŽฏ Objective

By the end of this lesson, you will be able to:

  • Use AND to require that every condition in a query is true.
  • Use OR to match rows where at least one condition is true.
  • Combine AND and OR correctly using parentheses.
  • Avoid the classic mistake of mixing them without grouping, which silently changes your results.

⚠️ What to Avoid

Common mistakes
  • Mixing AND and OR in one condition without parentheses — MySQL evaluates AND before OR, which can quietly return the wrong rows.
  • Assuming OR narrows results like AND does — OR actually widens them.
  • Writing WHERE department = 'Sales' AND 'HR' instead of repeating the column name on both sides.

๐Ÿ’ก Important to Know

Before you start

Think of AND as narrowing a search — every extra condition makes the result set smaller or the same size, never bigger. OR does the opposite — every extra condition can only make the result set bigger or the same size. When you mix both in one query, wrap the OR part in parentheses so it's evaluated as one unit.

Requirements

What You'll Need Before Starting

Operating SystemWindows, macOS, or Linux — this lesson works identically on all of them.
Database ServerMySQL installed and running. See How to Install MySQL if you haven't set it up yet.
Optional but recommendedXAMPP with phpMyAdmin, for a visual way to run queries. See How to Install XAMPP.
Prior knowledgeComfortable with SELECT, aliases, and basic WHERE filtering from Module 1.

No installation needed for the live playground further down this page — it runs entirely in your browser.

Practice

Step-by-Step Practice

Follow along in order — each step builds on the one before it.

1 Open MySQL (CLI or phpMyAdmin)

Open a terminal and connect with the MySQL command-line client, or open phpMyAdmin at http://localhost/phpmyadmin/.

mysql -u root -p

The basic syntax patterns for this lesson look like this:

SELECT columns FROM table WHERE condition1 AND condition2;
SELECT columns FROM table WHERE condition1 OR condition2;

2 Create a Database and Verify It

CREATE DATABASE module6_practice;
SHOW DATABASES;
USE module6_practice;

Now create a table and verify it was created:

CREATE TABLE employees (
  id INT PRIMARY KEY,
  name VARCHAR(50),
  department VARCHAR(50),
  salary INT,
  status VARCHAR(20)
);
SHOW TABLES;
DESCRIBE employees;

3 Insert Sample Data

INSERT INTO employees (id, name, department, salary, status) VALUES
(1, 'Sokha', 'Sales', 2800, 'Active'),
(2, 'Maria', 'Marketing', 3200, 'Active'),
(3, 'Wei', 'Sales', 3000, 'Inactive'),
(4, 'Aiden', 'IT', 3500, 'Active'),
(5, 'Nadia', 'HR', 2600, 'Active'),
(6, 'Liam', 'Marketing', 2100, 'Inactive');

4 Filter with AND

Both conditions must be true — Sales and active.

SELECT name, department, status FROM employees
WHERE department = 'Sales' AND status = 'Active';

5 Filter with OR

Either condition can be true — Sales or Marketing.

SELECT name, department FROM employees
WHERE department = 'Sales' OR department = 'Marketing';

6 AND with a Numeric Condition

Combine a text condition with a numeric one.

SELECT name, salary FROM employees
WHERE status = 'Active' AND salary > 2700;

7 Mixing AND and OR — the Right Way

Active employees who are in either Sales or Marketing. Without the parentheses, this query would return every active Sales employee, plus every Marketing employee regardless of status — not what we want.

SELECT name, department, status FROM employees
WHERE status = 'Active' AND (department = 'Sales' OR department = 'Marketing');

8 Combine with Column Selection and an Alias

Bring in what you learned in Module 2.

SELECT name AS employee_name, salary AS monthly_pay
FROM employees
WHERE department = 'Sales' AND salary >= 2800;

9 Combine with Sorting

Filter first with AND/OR, then sort what's left.

SELECT name, department, salary FROM employees
WHERE status = 'Active' AND (department = 'Sales' OR department = 'IT')
ORDER BY salary DESC;

Troubleshooting

Common Problems and Solutions

Problem 1: Mixing AND and OR returns unexpected extra rows

You wrote WHERE status = 'Active' AND department = 'Sales' OR department = 'Marketing' and got inactive Marketing employees too.

SolutionMySQL evaluates AND before OR, so this reads as "(Active AND Sales) OR Marketing" — not what you meant. Add parentheses: WHERE status = 'Active' AND (department = 'Sales' OR department = 'Marketing').

Problem 2: Trying to match multiple values with one column and AND

You wrote WHERE department = 'Sales' AND department = 'HR' and got zero rows.

SolutionA single row's department can't equal two different values at once. Use OR instead — WHERE department = 'Sales' OR department = 'HR' — or the IN operator, covered in a future module.

Problem 3: An alias from SELECT doesn't work inside WHERE

You aliased salary AS monthly_pay and then tried WHERE monthly_pay > 3000 AND department = 'IT', and got an "unknown column" error.

SolutionSame rule as previous modules — WHERE can't see aliases created in the same SELECT. Use the real column name, salary, inside WHERE.

Problem 4: Too many AND conditions return zero rows

You stacked five AND conditions and nothing matched, even though you expected some results.

SolutionEvery AND you add narrows the result further — it's easy to over-filter by accident. Comment out conditions one at a time to find which one is excluding everything, or double-check for typos in column values.

Problem 5: A row you expected is silently missing

A row where department is NULL doesn't show up in either department = 'Sales' OR department = 'HR' or its opposite.

SolutionThis is expected — NULL never satisfies =, !=, AND, or OR comparisons directly. If you need to include those rows, add OR department IS NULL explicitly.

Conclusion

What You Should Take Away

You should now be comfortable combining multiple conditions in a single query using AND to narrow results and OR to widen them — and, most importantly, you know to reach for parentheses the moment you mix the two together.

In Module 7, we'll build on this with shortcuts like IN and BETWEEN that make long chains of OR and comparison conditions much easier to write and read.

Homework

Homework & Quiz

๐Ÿ“ Homework Task

Using the employees table from this lesson, write your own query that:

  • Selects name, department, and salary.
  • Finds employees who are Active AND earn 2600 or more.
  • Sorts the results by salary, highest first.

Try it yourself first — then check it against the live playground below.

๐Ÿงช Quiz: Test Your Understanding (10 Questions)

Pick one answer per question, then click Submit to see your score instantly.

1. With AND, how many conditions must be true for a row to match?

2. With OR, how many conditions must be true for a row to match?

3. Which operator does MySQL evaluate first when AND and OR appear together?

4. What fixes unexpected results when mixing AND and OR?

5. WHERE department = 'Sales' AND department = 'HR' returns:

6. Which is the correct way to match Sales or HR employees?

7. Adding more AND conditions to a query tends to:

8. Does a row with a NULL department match "department = 'Sales' OR department = 'HR'"?

9. Can WHERE reference an alias created in the same SELECT statement?

10. Which clause would you add to sort filtered results by salary, highest first?

0 / 10

Try It Live

๐Ÿงช Live SQL Playground

A real SQLite database running entirely in your browser (via WebAssembly) — nothing is sent to a server. Practice combining AND/OR on the employees table below, or pick an example query to get started.

employees id INTEGER PK
name TEXT
department TEXT
salary INTEGER
status TEXT
Loading SQL engine…
Run a query to see results here.

FAQ

Frequently Asked Questions

1. What's the core difference between AND and OR?

AND requires every listed condition to be true for a row to appear. OR only requires at least one of them to be true.

2. Why do AND and OR give different results when mixed without parentheses?

Because MySQL evaluates AND before OR by default, so an unparenthesized mix can group conditions differently than you intended. Parentheses make the grouping explicit and predictable.

3. Can I combine more than two conditions?

Yes — you can chain as many AND and OR conditions as you need, as long as you group them clearly with parentheses when mixing the two.

4. Is there a shortcut for many OR conditions on the same column?

Yes — the IN operator, for example WHERE department IN ('Sales', 'HR', 'IT'), replaces a long chain of OR conditions on the same column with something shorter and easier to read.

5. Does the order of AND/OR conditions affect the result?

No, as long as the grouping (parentheses) stays the same, reordering the individual conditions doesn't change which rows match.

6. Can I use AND/OR with numeric comparisons too?

Yes — you can freely mix equality, numeric comparisons like > and <, and text conditions within the same AND/OR expression.

7. What happens if none of my conditions match any rows?

MySQL simply returns an empty result set — no error, just zero rows. This is completely normal.

8. Does NULL work normally inside AND/OR conditions?

No — NULL represents an unknown value, so it can never satisfy a direct comparison inside AND or OR. You need an explicit IS NULL check to include those rows.

9. Can I use WHERE with a column that isn't in my SELECT list?

Yes. WHERE can reference any real column in the table, whether or not you're displaying it in your results.

10. Is there a NOT operator to reverse a condition?

Yes — NOT flips a condition's result, for example WHERE NOT department = 'Sales' matches every department except Sales. It combines with AND and OR the same way.

Wednesday, July 22, 2026

How to Fix XAMPP Port 80 & MySQL Port Conflict Errors

How to Fix XAMPP Port 80 & MySQL Port Conflict Errors

Step-by-step fixes for Windows and macOS — under 5 minutes, no data loss

[Apache] Port 80 in use by "Unable to open process" [MySQL] shutdown unexpectedly

Setting up a local development server with XAMPP is supposed to be quick and simple. But nothing kills your momentum faster than pressing Start and getting hit with a wall of red text: "Port 80 in use by..." or "MySQL shutdown unexpectedly."

If you're staring at a blocked Control Panel right now, you're not alone. This guide explains exactly why these port conflicts happen on Windows and macOS, and walks through the most effective fixes — without touching or corrupting your existing databases.

01

What Is the XAMPP Port 80 / MySQL Error?

When you run XAMPP, two core services need to listen on specific network ports to talk to your browser and your database:

  • Apache (Web Server): defaults to Port 80 (HTTP) and Port 443 (HTTPS).
  • MySQL (Database Engine): defaults to Port 3306.

The "port conflict" error happens when another program or background service on your computer is already using Port 80 or Port 3306. Since a network port can only be used by one application at a time, XAMPP fails to launch.

Note

While Port 80 belongs to Apache, MySQL errors often show up at the same time — because when Apache fails to start, phpMyAdmin can't connect to MySQL either, and the two failures get reported together.

02

Why Does This Error Occur?

Port conflicts are rarely a bug in XAMPP itself. Instead, they're caused by other programs or built-in system services claiming these ports first at startup:

  • World Wide Web Publishing Service (IIS): a built-in Windows web server that automatically locks Port 80.
  • Skype or Discord: older versions of Skype frequently used Ports 80 and 443 for incoming connections.
  • An existing standalone MySQL/MariaDB installation: if you previously installed MySQL manually, or via another stack like WampServer, it holds onto Port 3306.
  • Web deployment tools: VMware, Docker, or the Web Deployment Agent Service can also listen on Port 80.

03

What You'll Need to Fix It

Before applying any fix, make sure you have administrator privileges on your machine.

PlatformRequirementsRecommended Tools
WindowsWindows 10/11, Administrator accessCommand Prompt (cmd), Task Manager
macOSmacOS Catalina or newer, sudo accessTerminal, Activity Monitor
XAMPPXAMPP v8.x or higherXAMPP Control Panel

04

Two Ways to Fix the Error

Way 1 — Stop the conflicting service (recommended)

Free up Port 80 or Port 3306 so XAMPP can use its normal default ports.

Way 2 — Change XAMPP's default ports

Reconfigure XAMPP to run on alternate ports instead — e.g., 8080 for Apache, 3307 for MySQL.

05

Step-by-Step Fix

Way 1: Free Up Port 80 / 3306

  1. Open Services. Press Windows Key + R, type services.msc, and hit Enter.
  2. Find the culprit. Scroll down to World Wide Web Publishing Service.
  3. Stop it. Right-click it and select Stop.
  4. Prevent it from returning. Right-click again, choose Properties, set Startup type to Manual or Disabled, then click Apply.

Or, stop IIS directly from an admin Command Prompt:

net stop w3svc
  1. Open Terminal.
  2. Find what's using Port 80:
    sudo lsof -i :80
  3. Identify the process ID (PID) from the output, then stop it:
    sudo kill -9 <PID>

Way 2: Change Ports in XAMPP's Configuration

If you can't stop whatever's occupying Port 80 or 3306, tell XAMPP to use different ports instead.

Step 1 — Change Apache's port (80 → 8080):

  1. Open the XAMPP Control Panel.
  2. Next to Apache, click Config → Apache (httpd.conf).
  3. Find the line Listen 80 and change it to Listen 8080.
  4. Find ServerName localhost:80 and change it to ServerName localhost:8080.
  5. Save and close the file.


Step 2 — Change MySQL's port (3306 → 3307):

my.ini


  1. Next to MySQL, click Config → my.ini.
  2. Find port=3306 under both [client] and [mysqld], and change both to port=3307.
  3. Save and close the file.


06

Checking and Verifying Your Fix

  1. Open the XAMPP Control Panel.
  2. Click Start next to Apache and MySQL.
  3. Confirm both rows turn green and show their active process IDs and ports (8080, 3307).
[Apache]  Status change detected: running (Ports: 8080, 443)
[MySQL]   Status change detected: running (Ports: 3307)

Then open your browser and go to http://localhost:8080/dashboard or http://localhost:8080/phpmyadmin to confirm everything's working.

07

Common Problems During the Fix

Problem 1: phpMyAdmin can't connect after changing the MySQL port

Fix Open xampp/phpMyAdmin/config.inc.php, find this line:
$cfg['Servers'][$i]['host'] = 'localhost';
and change it to:
$cfg['Servers'][$i]['host'] = '127.0.0.1:3307';

Problem 2: Port 443 (SSL) conflict error

Fix Open Apache's httpd-ssl.conf file via XAMPP Config, and change Listen 443 to Listen 4433.

08

Tips for Learning SQL

Once your local environment is running again, keep these in mind to speed up your database learning:

  • Start with the CLI first. Before relying entirely on phpMyAdmin, get comfortable with basic terminal commands — SELECT, INSERT, UPDATE, JOIN.
  • Use real sample databases. Practice on realistic datasets like Sakila or Employees rather than tiny test tables.
  • Master normalization. Understanding 1NF, 2NF, and 3NF helps you design efficient schemas from day one.

09

Related Articles on CodeMend

10

Conclusion

Port 80 and Port 3306 conflicts in XAMPP are a common rite of passage for every developer. Whether you disable a conflicting service like IIS, or reconfigure XAMPP to listen on alternate ports like 8080 and 3307, fixing this takes just a few clicks once you understand how network ports work.

11

Frequently Asked Questions

Is it better to stop IIS or change XAMPP's port?

Stopping IIS is generally the better choice if you don't need .NET development — it lets you keep using the standard http://localhost address instead of typing a custom port number every time.

Will changing the MySQL port delete my existing databases?

No. Changing the port configuration only changes how applications connect to MySQL — it doesn't touch or delete your stored data files.

Why does Skype block Port 80?

Older versions of Skype used Ports 80 and 443 as a fallback for HTTP/HTTPS traffic, to get around strict firewalls. This behavior can be turned off in Skype's Advanced Network Settings.