- Common SQL syntax errors and how to resolve them
- SQL Keyword errors
- Arrangement of commands
- Using quotation marks
- Finding SQL syntax errors
- Related posts:
- About Milena Petrovic
- SQL Errors: Five Common SQL Mistakes
- Watch Your Language (and Syntax)
- 1. Misspelling Commands
- 2. Forgetting Brackets and Quotes
- 3. Invalid statement order
- 4. Omitting Table Aliases
- 5. Using Case-Sensitive Names
- Everybody Makes SQL Mistakes
Common SQL syntax errors and how to resolve them
In the SQL Server Management Studio, errors can be tracked down easily, using the built in Error List pane. This pane can be activated in the View menu, or by using shortcuts Ctrl+\ and Ctrl+E
The Error List pane displays syntax and semantic errors found in the query editor. To navigate directly to the SQL syntax error in the script editor, double-click the corresponding error displayed in the Error List
SQL Keyword errors
SQL keyword errors occur when one of the words that the SQL query language reserves for its commands and clauses is misspelled. For example, writing “UPDTE” instead of “UPDATE” will produce this type of error
In this example, the keyword “TABLE” is misspelled:
As shown in the image above, not only the word “TBLE” is highlighted, but also the words around it. The image below shows that this simple mistake causes many highlighted words
In fact, there are total of 49 errors reported just because one keyword is misspelled
If the user wants to resolve all these reported errors, without finding the original one, what started as a simple typo, becomes a much bigger problem
It’s also possible that all SQL keywords are spelled correctly, but their arrangement is not in the correct order. For example, the statement “FROM Table_1 SELECT *” will report an SQL syntax error
Arrangement of commands
The wrong arrangement of keywords will certainly cause an error, but wrongly arranged commands may also be an issue
If the user, for example, is trying to create a new schema into an existing database, but first wants to check if there is already a schema with the same name, he would write the following command
However, even though each command is properly written, and is able to run separately without errors, in this form it results in an error
As the error message states, CREATE SCHEMA command has to be the first command that is given. The correct way of running this commands together looks like this
Using quotation marks
Another common error that occurs when writing SQL project is to use double quotation marks instead of single ones. Single quotation marks are used to delimit strings. For example, double quotation marks are used here instead of single ones, which cause an error
Replacing quotation marks with the proper ones, resolves the error
There are situations where double quotation marks need to be used, for writing some general quotes, for example
As shown in the previous example, this will cause an error. But, this doesn’t mean that double quotes can’t be used, they just have to be inside the single quotes. However, adding single quotes in this example won’t solve the problem, but it will cause another one
Since there is an apostrophe inside this quote, it is mistakenly used as the end of a string. Everything beyond is considered to be an error
To be able to use an apostrophe inside a string, it has to be “escaped”, so that it is not considered as a string delimiter. To “escape” an apostrophe, another apostrophe has to be used next to it, as it is shown below
Finding SQL syntax errors
Finding SQL syntax errors can be complicated, but there are some tips on how to make it a bit easier. Using the aforementioned Error List helps in a great way. It allows the user to check for errors while still writing the project, and avoid later searching through thousands lines of code
Another way to help, is to properly format the code
This can improve code readability, thus making the search for errors easier
Milena is a SQL Server professional with more than 20 years of experience in IT. She has started with computer programming in high school and continued at University.
She has been working with SQL Server since 2005 and has experience with SQL 2000 through SQL 2014.
Her favorite SQL Server topics are SQL Server disaster recovery, auditing, and performance monitoring.
- Using custom reports to improve performance reporting in SQL Server 2014 – running and modifying the reports — September 12, 2014
- Using custom reports to improve performance reporting in SQL Server 2014 – the basics — September 8, 2014
- Performance Dashboard Reports in SQL Server 2014 — July 29, 2014
About Milena Petrovic
Milena is a SQL Server professional with more than 20 years of experience in IT. She has started with computer programming in high school and continued at University. She has been working with SQL Server since 2005 and has experience with SQL 2000 through SQL 2014. Her favorite SQL Server topics are SQL Server disaster recovery, auditing, and performance monitoring. View all posts by Milena «Millie» Petrovic
SQL Errors: Five Common SQL Mistakes
As you learn SQL, watch out for these common coding mistakes
YouвЂ™ve written some SQL code and youвЂ™re ready to query your database. You input the code and вЂ¦. no data is returned. Instead, you get an error message.
DonвЂ™t despair! Coding errors are common in any programming language, and SQL is no exception. In this article, weвЂ™ll discuss five common mistakes people make when writing SQL.
The best way to prevent mistakes in SQL is practice. LearnSQL.com offers over 30 interactive SQL courses. Try out our SQL Practice track with 5 courses and over 600 hands-on exercises.
Watch Your Language (and Syntax)
The most common SQL error is a syntax error. What does syntax mean? Basically, it means a set arrangement of words and commands. If you use improper syntax, the database does not know what youвЂ™re trying to tell it.
To understand how syntax works, we can think of a spoken language. Imagine saying to a person вЂњNice dofвЂќ when you mean вЂњNice dogвЂќ. The person does not know what вЂњdofвЂќ means. So when you tell your database to find a TABEL instead of a TABLE, the database does not know what it needs to do.
People tend to make the same kinds of syntax mistakes, so their errors are usually easy to spot and very much the same. After you read this article, you should be able to remember and avoid (or fix) these common mistakes. Knowing what errors to look for is very important for novice SQL coders, especially early on. New coders tend to make more mistakes and spend more time looking for them.
The types of SQL errors we will look at are:
- Misspelling Commands
- Forgetting Brackets and Quotes
- Specifying an Invalid Statement Order
- Omitting Table Aliases
- Using Case-Sensitive Names
Ready? LetвЂ™s start.
1. Misspelling Commands
This is the most common type of SQL mistake among rookie and experienced developers alike. LetвЂ™s see what it looks like. Examine the simple SELECT statement below and see if you can spot a problem:
If you run this query, youвЂ™ll get an error which states:
Each database version will tell you the exact word or phrase it doesnвЂ™t understand, although the error message may be slightly different.
What is wrong here? You misspelled FROM as FORM. Misspellings are commonly found in keywords (like SELECT, FROM, and WHERE), or in table and column names.
Most common SQL spelling errors are due to:
- вЂњChubby fingersвЂќ where you hit a letter near the right one: SELEVT or FTOM or WJIRE
- вЂњReckless typingвЂќ where you type the right letters in the wrong order: SELETC or FORM or WHEER
Use an SQL editor that has syntax highlighting: the SELECT and WHERE keywords will be highlighted, but the misspelled FORM will not get highlighted.
If youвЂ™re learning with interactive SQL courses in LearnSQL.com , the code editor puts every SELECT statement keyword in light purple. If the keyword is black, as it is with any other argument, you know thereвЂ™s a problem. (In our example, FORM is black).
So if we correct our statement we get:
The keyword is now the right color and the statement executes without an error.
2. Forgetting Brackets and Quotes
Brackets group operations together and guide the execution order. In SQL (and in all of the programming languages I use), the following order of operations …
вЂ¦ is not the same as:
Can you figure out why?
A very common SQL mistake is to forget the closing bracket. So if we look at this erroneous statement :
We get an error code with the position of the error (the 102nd character from the beginning):
Remember: brackets always come in pairs.
The same is true with single quotes ( вЂ ‘ ) or double quotes ( ” ” ). There is no situation in SQL where we would find a quote (either a single quote or a double quote) without its mate. Column text values can contain one quote ( e.g. exp.last_name = «O’Reilly» ) and in these situations we must mix two types of quotes or use escape characters. ( In SQL, using escape characters simply means placing another quote near the character you want to deactivate вЂ“ e.g. exp.last_name = ‘O’вЂ™Reilly. )
Practice, practice, practice. Writing more SQL code will give you the experience you need to avoid these mistakes. And remember people usually forget the closing bracket or quotation mark. They rarely leave out the opening one. If youвЂ™re running into problems, take a close look at all your closing punctuation!
3. Invalid statement order
When writing SELECT statements, keep in mind that there is a predefined keyword order needed for the statement to execute properly. There is no leeway here.
LetвЂ™s look at an example of a correctly-ordered statement:
ThereвЂ™s no shortcut here; you simply have to remember the correct keyword order for the SELECT statement:
- SELECT identifies column names and functions
- FROM specifies table name or names (and JOIN conditions if youвЂ™re using multiple tables)
- WHERE defines filtering statements
- GROUP BY shows how to group columns
- HAVING filters the grouped values
- ORDER BY sets the order in which the results will be displayed
You cannot write a WHERE keyword before a FROM , and you canвЂ™t put a HAVING before a GROUP BY . The statement would be invalid.
LetвЂ™s look at what happens when you mix up the statement order. In this instance, weвЂ™ll use the common SQL error of placing ORDER BY before GROUP BY :
The error message we see is pretty intimidating!
DonвЂ™t be discouraged! You can see that all of the keywords are highlighted correctly and all the quotations and brackets are closed. So now you should check the statement order. When youвЂ™re just beginning your SQL studies, I suggest using a SELECT order checklist. If you run into a problem, refer to your list for the correct order.
4. Omitting Table Aliases
When joining tables, creating table aliases is a popular practice. These aliases distinguish among columns with the same name across tables; thus the database will know which column values to return. This is not mandatory when weвЂ™re joining different tables, since we can use the full table names. But it is mandatory if we join a table to itself.
Suppose weвЂ™re writing an SQL statement to find an exhibitionвЂ™s current location and the location from the previous year:
The database would return an error:
Note: Whenever you encounter вЂњambiguous column nameвЂќ in your error message, you surely need table aliases.
The correct statement (with aliases) would be:
Practice using table aliases for single-table SELECT statements. Use aliases often вЂ“ they make your SQL more readable.
5. Using Case-Sensitive Names
This error only occurs when you need to write non-standard names for tables or database objects.
LetвЂ™s say that you need to have a table named LargeClient and for some reason you add another table called LARGECLIENT. As you already know, object names in databases are usually case-insensitive. So when you write a query for the LargeClient table, the database will actually query LARGECLIENT.
To avoid this, you must put double quotes around the table name. For example:
When creating a table, you will need to use double quotes if:
- The table will have a case-sensitive name.
- The table name will contain special characters. This includes using a blank space, like “Large Client”.
Avoid using these names if you can. If not, remember your double quotes!
Everybody Makes SQL Mistakes
Those are the five most common errors in SQL code. YouвЂ™ll probably make them many times as you learn this language. Remember, everybody makes mistakes writing code. In fact, making mistakes is a normal and predictable part of software development.
So donвЂ™t be discouraged. When you make mistakes in the future, try to analyze your code in a structured way. With a structured analysis, you can find and correct your errors quicker.
If you would like to learn about some other syntactic mistakes that IвЂ™ve not included here, please let me know. In an upcoming article, weвЂ™ll look at non-syntactic errors. These return or modify data and are therefore much more dangerous. Subscribe to our blog so you wonвЂ™t miss it!