Web Analytics Made Easy - Statcounter
Home » SQL Server » SQL Server & DBA Error Codes Cheat Sheet – 100+ Common Errors, Causes & Solutions

SQL Server & DBA Error Codes Cheat Sheet – 100+ Common Errors, Causes & Solutions

Sql Server Dba Error Codes Cheat Sheet 100 Common Errors Causes Solutions
SQL Server & DBA Error Codes Cheat Sheet – 100+ Common Errors, Causes & Solutions

Introduction

If you work with SQL Server as a DBA, SQL Developer, Database Developer, Data Engineer, Database Architect, or database professional, you will eventually encounter an error message that stops your query, application, deployment, backup, restore, or production workload.

And when that happens, the first reaction is often:

“Let me Google this error.”

Or today:

“Let me ask AI what this error means.”

Those tools are useful, but you shouldn’t have to start from zero every time.

This SQL Server & DBA Error Codes Cheat Sheet is designed as a practical reference that you can bookmark and keep available while working with SQL Server.

It covers 100+ commonly encountered SQL Server, DBA, performance, security, storage, backup/restore, connectivity, and Azure SQL errors.

For each error, the goal is to answer five questions:

  1. What does the error mean?
  2. Why does it happen?
  3. What should I check first?
  4. What should I do next?
  5. How serious is it?

Please Note: An error number alone is not always enough to diagnose a problem. Always capture the complete error message, state, severity, database, procedure, line number, and surrounding context. Microsoft documents these attributes as important parts of SQL Server error information.

SQL Server Error Severity

Before looking at individual errors, understand the basic severity levels.

SeverityGeneral Meaning
0–10Informational messages
11–16User/programming or correctable errors
17–19Resource/software errors that may require DBA attention
20–24Serious errors that may affect the connection or database
25Fatal/system-level condition

Severity alone doesn’t determine how serious an incident is. The error number, state, frequency, impact, and environment also matter.

100+ SQL Server & DBA Error Codes Cheat Sheet

1. SQL Syntax, Object & Query Errors

ErrorMeaningWhy It HappensFirst CheckSolution / Next Step
102Incorrect syntax near…T-SQL syntax is invalidStatement around the reported locationCorrect syntax
105Unclosed quotation markString quotation is not closedSQL textClose the quotation or fix dynamic SQL
109INSERT column/value mismatchNumber of values doesn’t match columnsINSERT statementMatch columns and values
110Too many valuesMore values supplied than expectedINSERT statementCorrect column/value list
111CREATE PROCEDURE must be first statement in batchProcedure definition isn’t first in batchBatch structureSeparate with GO or use separate batch
113Comment not terminated/* ... */ isn’t closedSQL scriptClose the comment
156Incorrect syntax near keywordInvalid syntax around a T-SQL keywordSQL statementReview syntax
207Invalid column nameColumn doesn’t exist or name is incorrectTable/schema/columnVerify column and aliases
208Invalid object nameTable/view/procedure doesn’t exist in current contextDatabase/schema/objectVerify database and schema
209Ambiguous column nameSame column name exists in multiple referenced objectsJOIN/queryQualify column with alias
213Column/value mismatchINSERT doesn’t match table definitionINSERTSpecify target columns explicitly
2714Object already existsObject with same name already existsObject nameALTER, DROP, or rename appropriately
2812Could not find stored procedureProcedure doesn’t exist in current database/schemaProcedure nameVerify database and schema
8120Column invalid in SELECT list because not contained in GROUP BYAggregation/GROUP BY problemSELECT and GROUP BYAdd column to GROUP BY or aggregate it
8622Query processor unable to produce planHints/restrictions prevent valid planQuery hints and indexesRemove inappropriate hints and retest
8623Query processor ran out of internal resourcesQuery is too complex for available optimizer resourcesQuery complexitySimplify/rewrite query
8630Internal query processor errorQuery optimizer encountered an internal conditionError log and SQL versionInvestigate and check current updates/CUs

2. Data Type & Conversion Errors

ErrorMeaningWhy It HappensFirst CheckSolution
245Conversion failed when converting data typeValue cannot be converted to target typeSource values and data typesValidate input or use appropriate conversion
241Conversion failed when converting date/timeInvalid date/time valueInput dateCorrect date format/value
242Date/time conversion resulted in out-of-range valueDate is outside valid rangeDate expressionValidate date calculation
257Implicit conversion not allowedSQL Server cannot perform required conversionData typesUse compatible types or explicit conversion
295Data conversion errorValue cannot be convertedInput dataValidate source data
8114Error converting data typeConversion failedSource and destination typesCorrect conversion
8115Arithmetic overflowValue exceeds data type rangeNumeric value/typeUse larger appropriate data type
8116Argument data type invalidFunction doesn’t accept supplied typeFunction argumentsUse supported data type
8117Operand data type invalidOperation isn’t supported for the typeExpressionCorrect data types
8134Divide by zeroDenominator is zeroCalculationHandle zero using validation or NULLIF()
8144Too many parametersProcedure/function received extra parametersEXEC statementMatch parameters with definition
8146Procedure has no parametersParameters supplied to procedure that accepts noneEXEC statementRemove unnecessary parameters
535Date/time difference overflowDate calculation exceeds supported rangeDATEDIFF/date expressionUse appropriate data type or calculation
8118Operand/data type issueInvalid operation involving data typesExpressionCheck data types and implicit conversions

Example: Avoiding divide-by-zero

SELECT
    SalesAmount / NULLIF(Quantity, 0) AS AveragePrice
FROM Sales;

3. Data Integrity & Constraint Errors

ErrorMeaningWhy It HappensFirst CheckSolution
515Cannot insert NULLNOT NULL column receives NULLColumn definition and inputSupply a valid value
547Constraint conflictFOREIGN KEY/CHECK constraint violatedRelated rows and constraintCorrect data or application logic
2601Cannot insert duplicate key rowUnique index violationExisting duplicate valueCorrect duplicate data or INSERT logic
2627Violation of PRIMARY KEY/UNIQUE constraintDuplicate key valueExisting keyCorrect INSERT/UPDATE logic
544Explicit value must be specified for identity column when IDENTITY_INSERT is ONIdentity configuration issueIDENTITY_INSERTCorrect identity handling
1776Referenced table has no primary/unique key suitable for FKInvalid FK definitionParent tableReference an appropriate key
1785Adding FK may create multiple cascade pathsCascade relationship conflictFK definitionsRedesign cascade behavior
1788Foreign key columns don’t match referenced columnsFK definition mismatchColumn types/countMake FK and referenced columns compatible
3726Cannot drop object because it is referencedDependencies existForeign keys/dependenciesRemove or change dependencies
3728Constraint cannot be droppedDependency or incorrect constraint nameConstraint definitionVerify dependency and name

4. String & Data Truncation Errors

ErrorMeaningWhy It HappensFirst CheckSolution
8152String or binary data would be truncatedSource value is larger than destinationColumn lengthsIncrease destination size or correct source
2628String or binary data would be truncated with more detailValue exceeds destination column capacityError message/columnFix source or target column size

Example

CREATE TABLE Employee
(
    Name VARCHAR(10)
);

INSERT INTO Employee
VALUES ('Vivek Johari');

The destination column cannot hold the supplied value.

The correct solution isn’t always “increase the column size.” First determine whether the source data is actually valid.

5. Authentication & Login Errors

ErrorMeaningWhy It HappensFirst CheckSolution
18456Login failedAuthentication/login problemError stateCheck login, password, authentication mode and state
18452Login failed because login is from an untrusted domainWindows/domain trust issueDomain connectivityCheck domain trust and authentication
18461Login failed because server is in single-user modeAnother connection consumed the available slotExisting sessionsIdentify the connection using the slot
18470Login failed because login is disabledLogin is disabledsys.server_principalsEnable login if appropriate
18487Password expiredPassword policy expired login passwordLogin policyReset password
18488Password must be changedLogin requires password changeLogin policyChange password
17806SSPI-related authentication errorKerberos/Windows authentication issueSPN/domain configurationCheck SPN, service account and Kerberos configuration

Important: Error 18456

Do not stop at:

Login failed for user.

The state value is important for determining the reason.

6. Database Access & Permission Errors

ErrorMeaningWhy It HappensFirst CheckSolution
229Permission deniedUser lacks required permissionUser/role/object permissionsGrant least-privilege permission
262Permission problemRequired permission isn’t availableSecurity configurationReview roles/GRANTs
4060Cannot open requested databaseLogin cannot access database or database unavailableUser mapping/database stateFix mapping or database availability
15151Cannot alter/drop objectPermission/object ownership issueUser permissionsCorrect permissions/ownership
15023User already existsDatabase user already existsDatabase principalsMap/fix existing user
15401Windows account lookup failedDomain/account issueWindows/domainVerify account and domain
15405Cannot use special principalRestricted system/security principalPrincipal name/typeReview security configuration

7. Transactions, Blocking & Locking

These errors are especially important for DBAs.

ErrorMeaningWhy It HappensFirst CheckSolution
1204SQL Server cannot obtain a LOCK resourceExcessive locking/resource pressureLocks and active transactionsInvestigate transaction size/blocking
1205Transaction chosen as deadlock victimTwo or more transactions are deadlockedDeadlock graphFix access order, indexing or transaction design
1222Lock request timeout period exceededRequired lock wasn’t acquired within timeoutBlocking chainIdentify blocker and investigate
1223Lock request timed outLock unavailableBlocking sessionsInvestigate blocking
1224Lock escalation/resource conditionSQL Server is unable to manage locks as expectedLocking workloadInvestigate transactions and lock escalation
1206Transaction involved in deadlock processingTransaction deadlock conditionDeadlock informationAnalyze deadlock pattern

Error 1205: Deadlock

A common mistake is to simply kill a blocking session.

A deadlock is different from ordinary blocking.

A better approach is:

Capture deadlock → Identify participating queries → Identify resources → Compare access order → Fix root cause

8. Memory & Resource Errors

ErrorMeaningWhy It HappensFirst CheckSolution
701Insufficient system memorySQL Server cannot obtain required memorySQL/OS memoryInvestigate memory pressure
802Insufficient buffer pool memoryBuffer pool cannot provide required memoryMemory pressureInvestigate workload/configuration
8645Timeout waiting for memory resourcesQuery couldn’t obtain execution memory in timeMemory grantsTune query/workload
8651Requested memory grant unavailableRequired memory grant isn’t availableMemory grants/resource poolReduce query memory requirement or address pressure
8642Cannot start required thread resourcesParallel query cannot obtain required workersParallelism/loadReduce load or review MAXDOP
8646Unable to find index entryPossible index corruption or update-plan problemAffected index/tableRun DBCC CHECKDB/CHECKTABLE and investigate
8648Row too large for hash table pageHash operation encountered row-size limitationExecution plan/queryReview query; consider appropriate plan strategy
8649Query cost exceeds configured thresholdQuery estimated cost exceeded configured thresholdQuery cost/configurationReview query and relevant threshold/configuration
8653Query plan cannot be produced because filegroup is offlineReferenced object resides in offline filegroupFilegroup stateBring filegroup online if appropriate
8655Query plan cannot be produced because index is disabledQuery references disabled indexIndex statusRebuild/re-enable or change query/index strategy

Important correction: Error 8646 is not a generic memory error, and 8649 is not a generic parallelism error. Their exact meanings are different and should not be mixed with memory/resource errors.

9. Storage, Disk & Database File Errors

ErrorMeaningWhy It HappensFirst CheckSolution
1101Filegroup has insufficient spaceFilegroup cannot allocate more spaceDatabase files/free spaceAdd space or manage files
1105Could not allocate spaceDatabase/filegroup lacks available spaceFile size and diskIncrease capacity
1117Cannot extend fileFile growth cannot occurFile growth/diskCheck growth settings and disk
112Insufficient disk spaceOperating system cannot allocate spaceDiskFree/add storage
823Physical I/O errorStorage/OS I/O failureSQL Error Log + OSInvestigate storage immediately
824Logical consistency I/O errorData read failed a consistency checkError Log/DBCCInvestigate possible corruption
825I/O operation required retryStorage temporarily failed an I/O operationError Log/storageInvestigate proactively
945Database cannot be openedDatabase/files aren’t accessible or database state prevents openingDatabase state/filesInvestigate files and database state
926Database in recovery stateDatabase recovery is in progress/problematicError LogDetermine recovery status
927Database is recovering/restoringDatabase isn’t ready for normal accessDatabase stateWait for operation or investigate
942Database is offlineDatabase has been taken offlineDatabase stateDetermine why it is offline
5120Unable to open database fileFile inaccessiblePath and file permissionsCorrect permissions/path

Errors 823, 824 and 825

These deserve special attention.

823 generally points toward a physical I/O problem.

824 indicates SQL Server detected a logical consistency problem while processing I/O.

825 means SQL Server had to retry an I/O operation.

Don’t treat these as ordinary application errors. Investigate the SQL Server Error Log, Windows/system logs, storage subsystem and database consistency.

10. Transaction Log Errors

ErrorMeaningWhy It HappensFirst CheckSolution
9002Transaction log is fullLog cannot reuse spacelog_reuse_wait_descResolve the actual reuse blocker
9003Invalid log scan numberLog/metadata issueError LogInvestigate database/log integrity
3313Error during database recoveryRecovery encountered a problemError LogInvestigate underlying error
3314Recovery cannot undo operationRecovery encountered an operation failureError LogInvestigate storage/database condition

Don’t blindly increase the log

For Error 9002, first run:

SELECT
    name,
    recovery_model_desc,
    log_reuse_wait_desc
FROM sys.databases;

The important question is:

Why can’t SQL Server reuse the transaction log?

Possible causes include:

  • Long-running transaction
  • Missing log backups
  • Availability Group/replication-related conditions
  • Other log-reuse dependencies

11. Backup & Restore Errors

ErrorMeaningWhy It HappensFirst CheckSolution
3154Backup belongs to a different databaseBackup/database mismatchBackup metadataVerify source and target
3156File cannot be restoredRestore path/file conflictRESTORE outputUse correct file mapping
3241Backup media is invalidBackup may be damaged/incompatibleBackup file/mediaValidate backup
3242Backup media/device problemBackup media can’t be processedStorage/mediaCheck backup file/device
3254Backup device/file problemBackup destination issuePath/permissions/storageCorrect destination
4305Backup in the log chain is too earlyWrong backup sequenceBackup historyRestore correct sequence
4306Log backup cannot be appliedLSN/backup chain problemBackup historyIdentify missing/incorrect backup
4326Log backup contains incomplete recovery informationBackup chain/recovery issueBackup metadataVerify backup sequence
4330Restore operation failedRestore encountered an errorFull RESTORE outputInvestigate underlying error

Best practice: Never troubleshoot a restore error using only the final line of the message. Read the complete RESTORE output.

12. Database State & File Problems

ErrorMeaningWhy It HappensFirst CheckSolution
5171Invalid database/file header conditionDatabase file metadata/header problemError LogInvestigate file integrity
5172Invalid file headerDatabase file header is invalidDatabase filesInvestigate possible corruption
5173File/database association problemFile belongs to another database or metadata mismatchFile metadataInvestigate database files
1823Cannot create databaseCreation/path/resource problemDisk/path/permissionsCorrect creation environment
3729Cannot drop databaseDatabase is being usedActive sessionsIdentify and handle connections
3702Database currently in useActive connection existsSessionsDisconnect appropriate sessions

13. Connectivity & Network Errors

Some connection errors originate from the client/network stack rather than the SQL Server Database Engine itself, so always investigate the full message.

ErrorMeaningWhy It HappensFirst CheckSolution
2File/path not foundClient or SQL operation cannot find specified pathPathVerify path
5Access denied / connection-related OS errorPermissions/firewall/resource issue depending on contextComplete messageCheck permissions/network
26Error locating server/instanceClient can’t locate SQL ServerServer/instance nameVerify connection configuration
40Unable to open connection to SQL ServerConnectivity problemServer/networkCheck SQL service, TCP/IP and firewall
53Network path/server unavailableServer cannot be reachedConnectivityCheck DNS/network/firewall
64Network name unavailableConnection lostNetworkInvestigate network path
10053Transport-level connection abortedHost/network software terminated connectionNetwork/client logsInvestigate network
10054Connection forcibly closedConnection reset by peer/networkNetwork/serverInvestigate network and server
10060Connection timeoutServer didn’t respond in timeNetwork/firewallCheck connectivity and timeout
17830Network error during connectionNetwork/client issueNetwork configurationInvestigate connection path

14. Linked Server & Distributed Query Errors

ErrorMeaningWhy It HappensFirst CheckSolution
7303Cannot initialize data sourceOLE DB/linked-server provider issueProvider configurationTest provider and remote connection
7391Distributed transaction could not startMSDTC/distributed transaction problemMSDTC configurationCheck MSDTC or redesign transaction
7399OLE DB provider reported an errorRemote provider returned an errorComplete provider messageInvestigate provider/remote server
7411Server not configured for RPCRPC disabledLinked-server optionsConfigure RPC if required
7412Distributed query problemRemote/linked-server issueLinked server connectionTest remote server/provider

15. Stored Procedure & Parameter Errors

ErrorMeaningWhy It HappensFirst CheckSolution
201Required parameter not suppliedProcedure parameter is missingProcedure definitionSupply parameter
8144Too many parametersExtra parameters suppliedEXEC statementRemove extra parameters
8145Parameter already declaredDuplicate parameterProcedure/callRemove duplicate
8146Procedure has no parametersParameters supplied to parameterless procedureEXECRemove parameters
2812Procedure not foundWrong procedure/database/schemaObject nameVerify procedure

16. Query Processor & Execution Plan Errors

ErrorMeaningFirst CheckNext Step
8621Query processor ran out of internal resourcesQuery complexitySimplify/rewrite query
8622Query processor cannot produce plan due to hints/restrictionsQuery hintsRemove inappropriate hints
8623Query processor ran out of internal resourcesComplex queryBreak query into simpler operations
8630Internal query processor errorError log/SQL versionInvestigate and check updates
8642Parallel query cannot obtain required thread resourcesCPU/workload/parallelismInvestigate workload and MAXDOP
8645Timeout waiting for memory resourcesMemory grantsTune query/workload
8646Index entry cannot be found; possible corruption/update-plan issueIndex/tableRun consistency checks
8648Hash-table row too largeExecution plan/queryReview query/plan
8649Estimated query cost exceeds configured thresholdQuery cost/configurationInvestigate query and threshold
8651Requested memory grant unavailableMemory grant/resource poolReduce memory demand/address pressure
8653Filegroup offline prevents plan generationFilegroup stateCheck filegroup
8655Disabled index prevents plan generationIndex statusReview/re-enable/rebuild index

Microsoft’s current error catalog confirms these distinctions; for example, 8646 is an index/corruption or update-plan message, 8649 concerns the configured query-cost threshold, 8645 concerns waiting for memory, and 8651 concerns an unavailable memory grant.

17. SQL Server Agent & Job Troubleshooting

SQL Server Agent job failures don’t always have one universal Database Engine error number.

When a SQL Agent job fails, check:

  1. Job history
  2. Step history
  3. SQL Agent error log
  4. SQL Server Error Log
  5. Job owner
  6. Proxy credentials
  7. Database permissions
  8. CmdExec/PowerShell subsystem
  9. Network/share access
  10. The actual error returned by the job step

Common problems

ProblemTypical CauseFirst Check
Job cannot access databasePermission/loginJob owner/proxy
Job cannot access network shareSQL Agent service accountShare + NTFS permissions
SSIS step failsPackage/environment issueSSIS execution log
PowerShell step failsExecution policy/accountAgent subsystem
Job doesn’t startSchedule/Agent serviceSQL Server Agent status

Important: Don’t create artificial error-code mappings for SQL Agent problems. The actual job-step error should be captured and diagnosed.

18. Azure SQL Database Errors

Azure SQL introduces additional transient and resource-governance errors. These should be treated separately from traditional SQL Server errors.

ErrorMeaningWhy It HappensFirst CheckSolution / Next Step
40197Service error while processing requestAzure SQL service/infrastructure transient conditionAzure service health + complete messageRetry; investigate if persistent
40501Service currently busyResource governance/throttlingResource utilizationRetry with backoff and tune workload
40531Cannot connect/login to serverAzure SQL connectivity/authentication conditionComplete message/networkCheck connectivity/authentication
40544Database reached size quotaDatabase exceeded configured size limitDatabase sizeDelete/archive data, optimize storage or scale
40553Session terminated due to excessive memory usageQuery/session consumed excessive memoryQuery/workloadReduce rows/memory requirement and optimize
40613Database isn’t currently availableTransient service/database availability conditionAzure status/database stateRetry and investigate if persistent
10928Resource limit reachedDatabase/pool worker/session limit reachedResource ID + workloadInvestigate workers/sessions/blocking and scale if appropriate
10929Server too busy to support requests above current resource guaranteeResource governanceResource usageRetry/tune/scale
49918Not enough resources to process requestAzure resource pressureResource utilizationRetry and investigate workload
49919Too many create/update operationsAzure management operation limitCurrent operationsWait and retry
49920Too many operations in progressAzure resource operation limitCurrent operationsWait and retry
40615Cannot connect to serverAzure SQL firewall/connectivity issueFirewall/networkCorrect firewall/network configuration

Microsoft specifically identifies 40197, 40613 and related errors as transient conditions, and recommends resilient retry logic for cloud-connected applications. Microsoft also documents 10928/10929 as Azure SQL resource-governance errors and 40501 as an engine-throttling/resource-limit error.

Azure SQL retry principle

For transient errors, don’t simply retry in a tight loop.

Use:

Retry → Delay → Exponential backoff → Maximum retry count → Fail gracefully

Microsoft recommends retry logic for cloud-connected applications and notes that an initial delay of around five seconds can be appropriate for these Azure SQL transient conditions.

19. Security & Permission Troubleshooting Checklist

When you see a permission error, don’t immediately grant db_owner.

Check:

SELECT
    dp.name,
    dp.type_desc,
    dp.authentication_type_desc
FROM sys.database_principals AS dp
WHERE dp.name = USER_NAME();

Then determine:

  • Is the login mapped to the correct database user?
  • Is the user a member of the appropriate role?
  • Does the user have permission on the object?
  • Is the object owned by the expected schema?
  • Is the application using the expected login?

Use least privilege rather than solving every permission problem with excessive access.

20. The Most Important DBA Error Codes to Remember

If you don’t want to memorize 100+ numbers, start with these:

ErrorRemember It As
1205Deadlock
1222Lock timeout
1204Lock resource problem
9002Transaction log full
1105Could not allocate database space
823Physical I/O
824Logical I/O consistency
825I/O retry
701Memory
8645Memory-resource timeout
8651Memory grant unavailable
18456Login failed
4060Cannot open database
229Permission denied
208Invalid object
207Invalid column
547Constraint conflict
2601Duplicate unique index
2627Duplicate PK/unique constraint
515NULL into NOT NULL
8152Data truncation
2628Detailed truncation
245Conversion failed
8114Conversion error
8115Arithmetic overflow
8134Divide by zero
40501Azure SQL service busy
40613Azure SQL database unavailable
10928Azure SQL resource limit
10929Azure SQL resource pressure
40544Azure SQL database size quota

How to Troubleshoot Any Unknown SQL Server Error

You don’t need to memorize every error number.

Use this process.

              ERROR OCCURS
                   |
                   v
       Capture COMPLETE message
                   |
                   v
       Record error number + state
                   |
                   v
       Identify database/object/session
                   |
                   v
        Check SQL Server Error Log
                   |
                   v
       Check relevant DMV / Query Store
                   |
                   v
       Identify probable root cause
                   |
                   v
           Test the solution
                   |
                   v
        Apply controlled change
                   |
                   v
              Monitor

Useful T-SQL for Error Investigation

1. Find the SQL Server Error Message

SQL Server stores system and user-defined messages in sys.messages. Microsoft documents message_id, severity, event logging status, language and message text in this catalog view.

SELECT message_id, severity, is_event_logged, [text] FROM sys.messages WHERE language_id = 1033 AND message_id = 1205;

Change 1205 to the error number you want to investigate.

2. Search for an Error Number

SELECT
    message_id,
    severity,
    [text]
FROM sys.messages
WHERE language_id = 1033
  AND message_id IN
  (
      1205,
      1222,
      9002,
      823,
      824,
      825,
      18456
  );

3. Check Database State

SELECT
    name,
    state_desc,
    recovery_model_desc,
    user_access_desc
FROM sys.databases;

4. Check Transaction Log Reuse

SELECT
    name,
    recovery_model_desc,
    log_reuse_wait_desc
FROM sys.databases;

This is especially useful for Error 9002.

5. Check Blocking

SELECT
    session_id,
    blocking_session_id,
    wait_type,
    wait_time,
    wait_resource,
    status,
    command
FROM sys.dm_exec_requests
WHERE blocking_session_id <> 0;

Useful for investigating 1222 and general blocking.

6. Check Active Requests

SELECT
    session_id,
    status,
    command,
    cpu_time,
    total_elapsed_time,
    logical_reads,
    reads,
    writes
FROM sys.dm_exec_requests;

7. Capture Errors in TRY…CATCH

For application and stored-procedure troubleshooting:

BEGIN TRY

    -- Your SQL code here

END TRY
BEGIN CATCH

    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage;

END CATCH;

This is especially useful because SQL Server provides functions such as ERROR_NUMBER(), ERROR_SEVERITY(), ERROR_STATE(), ERROR_PROCEDURE(), ERROR_LINE() and ERROR_MESSAGE() for error handling.

Error Code vs Error State

One of the most important concepts for SQL Server troubleshooting is that the error number isn’t always enough.

For example:

Error Number: 18456
State:       XX
Message:     Login failed for user...

The state can provide additional diagnostic information.

Therefore, whenever possible capture:

Error Number
Error Message
Severity
State
Database
Server
Login/User
Procedure
Line Number
Timestamp
Session ID

Don’t Just Search the Error Number

Suppose you see:

SQL Server Error 9002

A beginner might search:

“How to fix SQL Server error 9002?”

and immediately increase the transaction log.

An experienced DBA asks:

“Why is the log not reusable?”

Then checks:

SELECT
    name,
    log_reuse_wait_desc
FROM sys.databases;

Similarly:

Error 1205

Don’t simply kill sessions.

Ask:

Why are these transactions deadlocking?

Error 824

Don’t simply rerun the query.

Ask:

Is there a database/storage consistency problem?

Error 18456

Don’t automatically reset the password.

Ask:

What is the error state and authentication context?

Error 10928

Don’t immediately scale the database.

Ask:

Which resource limit was reached and why?

This difference between error recognition and root-cause analysis is one of the most important skills for a DBA.

SQL Server Error Troubleshooting Cheat Sheet

Error CategoryFirst Tool/Check
Login failureError state + SQL Error Log
PermissionUsers, roles and permissions
Invalid objectDatabase/schema/object
Duplicate keyExisting data + index/constraint
FK violationParent/child relationship
Blockingsys.dm_exec_requests
DeadlockDeadlock graph / Extended Events
Log fulllog_reuse_wait_desc
Disk fullDatabase files + OS storage
I/O errorSQL Error Log + storage
Corruption suspicionDBCC CHECKDB
Memory issueMemory grants + resource pressure
Slow queryQuery Store + execution plan
Backup failureFull backup/restore output
Azure throttlingAzure resource metrics
Azure transient errorRetry logic + service health
Network failureTCP/IP, DNS, firewall and connectivity

DBA Emergency Errors

If you are a SQL Server DBA, take these errors particularly seriously:

823

Possible physical I/O/storage problem.

824

Logical consistency error and possible corruption.

825

Storage/I/O retry warning.

9002

Transaction log is full.

701

Serious memory pressure.

8646

Potential index corruption/update-plan issue.

1205

Deadlock.

1204

Lock resource exhaustion.

The correct response to these errors depends on the environment, but they should not simply be dismissed as ordinary application errors.

SQL Server Error Codes: A Practical Learning Strategy for Freshers

If you’re new to SQL Server, don’t try to memorize all 100+ errors.

Start with these groups:

Beginner

Learn:

102, 105, 207, 208, 245, 515, 547, 8134, 18456, 229

SQL Developer

Add:

2601, 2627, 8152, 2628, 8114, 8115, 8120, 2812

DBA

Add:

1204, 1205, 1222, 9002, 1105, 823, 824, 825, 701, 8645

Azure SQL Professional

Add:

40501, 40613, 10928, 10929, 40544, 40553, 49918, 49919, 49920

This gives you a practical progression rather than trying to memorize a giant list.

Summary

SQL Server has a huge number of system messages, and Microsoft maintains them through the Database Engine error catalog and sys.messages. The catalog is the authoritative place to inspect the actual message, severity and logging characteristics for an installed SQL Server version.

But knowing an error number isn’t enough to become a good SQL Server professional.

The real skill is:

Recognize the error → collect evidence → identify the root cause → choose the safest solution → validate the result.

You don’t need to Google or ask AI every time a familiar error appears.

Use this cheat sheet as your first reference, then use Microsoft’s documentation, SQL Server logs, DMVs, Query Store, execution plans, Extended Events and other diagnostic tools when deeper investigation is required.

Bookmark this page

SQL Server & DBA Error Codes Cheat Sheet – 100+ Common Errors, Causes & Solutions

Keep it handy whenever you’re working with SQL Server.

Official Microsoft reference: Microsoft’s Database Engine error catalog and sys.messages should be used to verify error details for the specific SQL Server version/environment you’re troubleshooting.


Discover more from Technology with Vivek Johari

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from Technology with Vivek Johari

Subscribe now to keep reading and get access to the full archive.

Continue reading