SQL Server
Common SQL Beginner Mistakes and How to Avoid Them
Recognize common SQL mistakes around filtering, NULL, joins, ordering, and data changes, then replace each with a safer habit.
On this page
SQL is readable enough that beginners can write a query before they understand all of its consequences. A statement may run successfully and still answer the wrong question, return an unexpected number of rows, or change more data than intended. The best defense is a set of repeatable habits: confirm context, state the intended columns and rows, inspect relationships, and check results.
This lesson is a diagnostic guide, not a replacement for the earlier lessons. Use it when a result surprises you or before a query becomes part of a script. Examples use the synthetic JaviBuildsLab database and the dbo.Customers and dbo.Orders tables. Start with your first SELECT query, then revisit filtering with WHERE, sorting with ORDER BY, NULL, JOINs, duplicate rows after joins, and safe UPDATE and DELETE practices where needed.
Mistake: running a query in the wrong database
An SSMS query window is connected to a server and has a current database context. It is possible to choose the wrong database in the toolbar, open a query window from another context, or assume that a database name in a tab is still selected. A query against a table with the same name in a different database may succeed and return plausible but unrelated rows. A query against a database without that table may fail with an object-not-found error.
Before exploring or changing data, check the session directly:
SELECT DB_NAME() AS CurrentDatabase;Compare the result with the database you intended to use. If it is not JaviBuildsLab, pause and select the correct database. A USE statement changes context for the current connection, but it does not create a database or prove that its contents are the expected ones. In a shared or production environment, follow the team’s approved connection process rather than switching context casually.
Better habit: confirm the server and database before a script that depends on either. Include a context check in a reusable script when running it against the wrong database would be costly.
Mistake: using SELECT * everywhere
SELECT * is convenient while learning a table, but it asks for every column. That can include fields a report does not need and make downstream results change when someone adds a column.
Prefer a deliberate list:
SELECT CustomerId, FirstName, LastName, City
FROM dbo.Customers;This makes the output easier to review. During exploration, SELECT TOP (10) * can help inspect unfamiliar data, but add an ORDER BY for repeatable sample rows. Review exploratory shorthand before carrying it into application code, exports, or reports.
Better habit: name the columns that answer the question. Give expressions useful aliases, and qualify a column with its table alias when more than one source has that column name.
Mistake: forgetting WHERE
An UPDATE or DELETE with no WHERE condition can affect every row in its target table. A SELECT with a missing filter may return far more data than expected. SQL Server follows the statement that was written; it cannot infer the subset you meant.
For a data change, begin with a preview:
SELECT CustomerId, FirstName, State
FROM dbo.Customers
WHERE CustomerId = 11;Make sure the preview returns exactly the intended row or rows. Reuse the same table and condition in the later change, verify the result, and count matches rather than judging a filter by appearance.
Better habit: write and run the SELECT first. For modifying statements, use the SELECT-first workflow and practice only in a known test database. Never remove a WHERE clause merely to make a query run.
Mistake: assuming rows have an order
Tables do not promise a display order. A query may appear to return rows in insertion order or primary-key order during one run, but that is not a contract. A different plan, index, server version, or data change can produce a different order.
When order matters, say so:
SELECT TOP (5) OrderId, OrderDate, Amount
FROM dbo.Orders
ORDER BY OrderDate DESC, OrderId DESC;The second sort column makes ties deterministic. TOP without ORDER BY limits the output but does not mean “the newest,” “the first,” or any other meaningful subset. See sorting data with ORDER BY for how to define the requested order.
Better habit: treat row order as unspecified unless the query includes a suitable ORDER BY. When you use TOP, define which rows should qualify before limiting them.
Mistake: comparing NULL with an equals sign
NULL represents missing or unknown information. It is not a regular value, so Email = NULL does not test for a missing email. The comparison evaluates to unknown, and it will not select the rows a beginner expects. Empty text is a value (''); NULL is different.
Use the NULL predicates:
SELECT CustomerId, Email
FROM dbo.Customers
WHERE Email IS NULL;Use IS NOT NULL to find rows with a value. Do not replace missing values with an empty string simply to make a comparison convenient; that changes the meaning of the data. Read Understanding NULL in SQL Server for how unknown values affect conditions and aggregates.
Better habit: use IS NULL or IS NOT NULL, and decide explicitly how an application should display missing data.
Mistake: confusing WHERE with HAVING
WHERE filters source rows before groups are formed. HAVING filters groups after aggregation. Using an aggregate such as COUNT(*) inside WHERE is invalid because the groups do not exist at that stage. Putting a row-level condition in HAVING can work in some circumstances, but it obscures the intended sequence and often performs unnecessary work.
For example, first choose complete orders, then keep customers whose qualifying orders total at least two:
SELECT CustomerId, COUNT(*) AS OrderCount
FROM dbo.Orders
WHERE Status = N'Complete'
GROUP BY CustomerId
HAVING COUNT(*) >= 2;The status test is about individual order rows; the count test is about each customer group. The WHERE versus HAVING lesson explains this distinction step by step.
Better habit: ask whether a condition describes one source row or an aggregate group. Put row conditions in WHERE and group conditions in HAVING.
Mistake: expecting a one-to-many join to keep one row per customer
A customer can have several orders. Joining Customers to Orders by CustomerId returns one row for each matching customer-order pair. A customer with three orders therefore appears on three result rows. Those rows are not necessarily duplicate records; they represent three relationships in the result.
Decide what one output row should represent before writing the join. Repeated customer details are expected for one row per order; for one row per customer, aggregate orders or choose another query shape. A LEFT JOIN also preserves customers without orders, with NULLs in the order columns. See the JOIN lesson and duplicate-row guide.
Better habit: state the grain in plain language: “one row per order” or “one row per customer.” Then make the join and any grouping match that promise.
Mistake: adding DISTINCT to hide an incorrect join
DISTINCT removes rows that are identical across the selected columns. It does not repair a missing join condition or prove that two tables are related correctly. If a join accidentally pairs every customer with every order, adding DISTINCT may hide some repeated output while leaving the underlying relationship wrong. It can also erase legitimate repeated values when the selected columns do not uniquely identify the business event.
Check the ON condition, compare row counts, and inspect joined keys. If you need one result per entity, use a grouping or existence test that expresses that goal.
Better habit: understand why rows repeat before using DISTINCT. Use it when uniqueness is genuinely part of the requested result, not as a cosmetic cleanup step.
Mistake: leaving shared column names unqualified
Both Customers and Orders can contain a CustomerId column. Once both tables appear in a query, writing CustomerId alone may be ambiguous. SQL Server will report an error rather than guess. Even when a name is currently unique, qualifying it makes the source clear and helps readers follow the relationship.
SELECT c.CustomerId, c.FirstName, o.OrderId, o.Amount
FROM dbo.Customers AS c
INNER JOIN dbo.Orders AS o
ON o.CustomerId = c.CustomerId;Here c and o are aliases within this statement; they do not rename database tables. See the alias lesson.
Better habit: qualify shared columns with a table alias and choose aliases that make a multi-table query easier to read.
Mistake: running UPDATE or DELETE before checking the target
A syntactically valid statement can still be operationally unsafe. A misspelled condition, an overly broad predicate, or the wrong database can change the wrong records. Beginners sometimes treat a successful “rows affected” message as proof of correctness; it only reports what happened, not whether it was intended.
Use the same filter in a preview and in the data change. Confirm and count the target rows, make the change in a safe environment, and verify the outcome. Practice in a transaction and roll it back unless you intend to keep the change. Follow organizational review and backup procedures in production.
Better habit: preview, count, change, verify, then decide. Follow safe UPDATE and DELETE practices before modifying data.
Mistake: treating NULL as an empty string
An empty string says that a text value is present and contains zero characters. NULL says that no value is known or recorded. They can have different meanings: a customer may have opted not to provide an email (NULL), while a source system may have imported an empty value. Comparisons, counts, and display rules can treat them differently.
COUNT(Email) skips NULL values, whereas COUNT(*) counts rows. Replacing NULL with '' changes the data; a presentation layer can show a friendly label without altering storage.
Better habit: ask what “missing” means in the domain. Keep storage semantics deliberate, and use COALESCE or application formatting only when the output needs a substitute.
Mistake: assuming an alias renames a schema object
SELECT Amount AS OrderTotal changes the column label in that query’s result. FROM dbo.Orders AS o gives the table a short name while the statement runs. Neither operation renames a column or table in the database. A later query still needs the stored object name, such as dbo.Orders.
Database object changes are a different administrative task and can affect applications, permissions, and dependencies. Do not use an alias as evidence that a schema change occurred.
Better habit: distinguish result labels and statement-local aliases from permanent database definitions. Use clear names in output, and handle schema changes through reviewed migrations.
Mistake: copying SQL without understanding its assumptions
An example from a forum, old script, or generated answer may use different table names, key values, SQL Server features, or data assumptions. It may omit a filter because the author ran it on a disposable dataset. It may also use a syntax form that is valid in another database product but not SQL Server.
Before adapting copied SQL, identify the engine, expected tables and columns, affected rows, and intended result. Run a read-only version where possible. Check each clause rather than pasting an unfamiliar statement into a production query window.
Better habit: explain each clause to yourself before running it. If you cannot predict the result, test the idea against a safe sample and consult the relevant lesson or official documentation.
A quick diagnostic routine
When a result looks wrong, pause and check the basics. Confirm the server and DB_NAME(), selected columns, table sources, filters, and NULL logic. Check whether a join returns several rows per entity and decide what one row represents. Add ORDER BY if order matters. Before changing data, preview and count the target rows, then compare the result with the question you meant to ask.
- Mistake spotted
- Check context and result grain
- State the safer habit
- Preview and verify
These checks become faster with practice. Keep the checklist nearby while learning, then turn the habits into a normal part of reviewing a query. The next lesson introduces a database object that can give a useful query a reusable name: views in SQL Server. You can also return to the SQL Server Foundations roadmap at any time.
Check what you learned
2 quick questions
SQL Server Foundations
Lesson 20 of 25
Was this helpful?
What could be better?
Thanks — that helps me improve Javi Builds.
Continue learning
- Cheat sheetCheck SQL Server Table SizesMeasure SQL Server table row counts and storage usage, separate data from index space, and identify which tables are driving database growth.Open cheat sheet
- RoadmapSQL Server FoundationsRecognize common SQL mistakes around filtering, NULL, joins, ordering, and data changes, then replace each with a safer habit.View roadmap
What should I build next?
I'm building Javi Builds around practical problems data engineers actually face. Tell me what you'd like to see next.
Stay in the loop
Get the Javi Builds updates you actually care about.
Check your inbox
I sent you a confirmation link. Your subscription will be active after you confirm it.