`

MariaDB_Basic SQL Debugging

 
阅读更多

Basic SQL Debugging

via: https://mariadb.com/kb/en/basic-sql-debugging/

 

Designing Queries

Following a few conventions makes finding errors in queries a lot easier, especially when you ask for help from people who might know SQL, but know nothing about your particular schema. A query easy to read is a query easy to debug. Use whitespace to group clauses within the query. Choose good table and field aliases to add clarity, not confusion. Choose the syntax that supports the query's meaning.

Using Whitespace

A query hard to read is a query hard to debug. White space is free. New lines and indentation make queries easy to read, particularly when constructing a query inside a scripting language, where variables are interspersed throughout the query.

There is a syntax error in the following. How fast can you find it?

SELECT u.id, u.name, alliance.ally FROM users u JOIN alliance ON
(u.id=alliance.userId) JOIN team ON (alliance.teamId=team.teamId
WHERE team.teamName='Legionnaires' AND u.online=1 AND ((u.subscription='paid'
AND u.paymentStatus='current') OR u.subscription='free') ORDER BY u.name;

Here's the same query, with correct use of whitespace. Can you find the error faster?

SELECT
    u.id
    , u.name
    , alliance.ally
FROM
    users u
    JOIN alliance ON (u.id = alliance.userId)
    JOIN team ON (alliance.teamId = team.teamId
WHERE
    team.teamName = 'Legionnaires'
    AND u.online = 1
    AND (
        (u.subscription = 'paid' AND u.paymentStatus = 'current')
        OR
        u.subscription = 'free'
    )
ORDER BY
    u.name;

Even if you don't know SQL, you might still have caught the missing ')' following team.teamId.

The exact formatting style you use isn't so important. You might like commas in the select list to follow expressions, rather than precede them. You might indent with tabs or with spaces. Adherence to some particular form is not important. Legibility is the only goal.

Table and Field Aliases

Aliases allow you to rename tables and fields for use within a query. This can be handy when the original names are very long, and is required for self joins and certain subqueries. However, poorly chosen aliases can make a query harder to debug, rather than easier. Aliases should reflect the original table name, not an arbitrary string.

Bad:

SELECT *
FROM
    financial_reportQ_1 AS a
    JOIN sales_renderings AS b ON (a.salesGroup = b.groupId)
    JOIN sales_agents AS c ON (b.groupId = c.group)
WHERE
    b.totalSales > 10000
    AND c.id != a.clientId

As the list of joined tables and the WHERE clause grow, it becomes necessary to repeatedly look back to the top of the query to see to which table any given alias refers.

Better:

SELECT *
FROM
    financial_report_Q_1 AS frq1
    JOIN sales_renderings AS sr ON (frq1.salesGroup = sr.groupId)
    JOIN sales_agents AS sa ON (sr.groupId = sa.group)
WHERE
    sr.totalSales > 10000
    AND sa.id != frq1.clientId

Each alias is just a little longer, but the table initials give enough clues that anyone familiar with the database only need see the full table name once, and can generally remember which table goes with which alias while reading the rest of the query.

Placing JOIN conditions

The manual warns against using the JOIN condition (that is, the ON clause) for restricting rows. Some queries, particularly those using implicit joins, take the opposite extreme - all join conditions are moved to the WHERE clause. In consequence, the table relationships are mixed with the business logic.

Bad:

SELECT *
FROM
    family,
    relationships
WHERE
    family.personId = relationships.personId
    AND relationships.relation = 'father'

Without digging through the WHERE clause, it is impossible to say what links the two tables.

Better:

SELECT *
FROM
    family
    JOIN relationships ON (family.personId = relationships.personId)
WHERE
    relationships.relation = 'father'

The relation between the tables is immediately obvious. The WHERE clause is left to limit rows in the result set.

Compliance with such a restriction negates the use of the comma operator to join tables. It is a small price to pay. Queries should be written using the explicit JOIN keyword anyway, and the two should never be mixed (unless you like rewriting all your queries every time a new version changes operator precedence).

Finding Syntax Errors

Syntax errors are among the easiest problems to solve. MariaDB provides an error message showing the exact point where the parser became confused. Check the query, including a few words before the phrase shown in the error message. Most syntax and parsing errors are obvious after a second look, but some are more elusive, especially when the error text seems empty, points to a valid keyword, or seems to error on syntax that appears exactly correct.

Interpreting the Empty Error

Most syntax errors are easy to interpret. The error generally details the exact source of the trouble. A careful look at the query, with the error message in mind, often reveals an obvious mistake, such as mispelled field names, a missing 'AND', or an extra closing parenthesis. Sometimes the error is a little less helpful. A frequent, less-than-helpful message:

ERROR 1064: You have an error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near ' ' at line 1

The empty ' ' can be disheartening. Clearly there is an error, but where? A good place to look is at the end of the query. The ' ' suggests that the parser reached the end of the statement while still expecting some syntax token to appear.

Check for missing closers, such as ' and ):

SELECT * FROM someTable WHERE field = 'value

Look for incomplete clauses, often indicated by an exposed comma:

SELECT * FROM someTable WHERE field = 1 GROUP BY id,

Checking for keywords

MariaDB allows table and field names and aliases that are also reserved words. To prevent ambiguity, such names must be enclosed in backticks (`):

SELECT * FROM actionTable WHERE `DELETE` = 1;

If the syntax error is shown near one of your identifiers, check if it appears on the reserved word list.

A text editor with color highlighting for SQL syntax helps to find these errors. When you enter a field name, and it shows up in the same color as the SELECT keyword, you know something is amiss. Some common culprits:

  • DESC is a common abbreviation for "description" fields. It means "descending" in a MariaDB ORDERclause.
  • DATETIME, and TIMESTAMP are all common field names. They are also field types.
  • ORDER appears in sales applications. MariaDB uses it to specify sorting for results.

Some keywords are so common that MariaDB makes a special allowance to use them unquoted. My advice: don't. If it's a keyword, quote it.

Version specific syntax

As MariaDB adds new features, the syntax must change to support them. Most of the time, old syntax will work in newer versions of MariaDB. One notable exception is the change in precedence of the comma operator relative to the JOIN keyword in version 5.0. A query that used to work, such as

SELECT * FROM a, b JOIN c ON a.x = c.x;

will now fail.

More common, however, is an attempt to use new syntax in an old version. Web hosting companies are notoriously slow to upgrade MariaDB, and you may find yourself using a version several years out of date. The result can be very frustrating when a query that executes flawlessly on your own workstation, running a recent installation, fails completely in your production environment.

This query fails in any version of MySQL prior to 4.1, when subqueries were added to the server:

SELECT * FROM someTable WHERE someId IN (SELECT id FROM someLookupTable);

This query fails in some early versions of MySQL, because the JOIN syntax did not originally allow an ON clause:

SELECT * FROM tableA JOIN tableB ON tableA.x = tableB.y;

Always check the installed version of MariaDB, and read the section of the manual relevant for that version. The manual usually indicates exactly when particular syntax became available for use.

The initial version of this article was copied, with permission, from http://hashmysql.org/wiki/Basic_Debugging on 2012-10-05.

 

分享到:
评论

相关推荐

    navicat150_mariadb_cs_x64.exe

    navicat150_mariadb_cs_x64.exe 一款专门为mariadb 数据库使用的navicat工具

    Mariadb_install_win.rar

    标题"Mariadb_install_win.rar"表明这是一个关于在Windows操作系统上安装MariaDB的压缩包文件,特别是通过批处理(BAT)脚本来实现一键安装的过程。MariaDB是一个开源的关系型数据库管理系统,它是MySQL的一个分支,...

    (34条消息) CentOS 7 安装mariadb_centos7安装mariadb_托塔雨天王的博客-CSDN博客.mhtml

    (34条消息) CentOS 7 安装mariadb_centos7安装mariadb_托塔雨天王的博客-CSDN博客.mhtml

    mariadb_deploy.sh

    Centos7自动安装mariadb并设置密码允许用户远程登录脚本

    navicat110_mariadb_cs_x86.zip

    标题中的"navicat110_mariadb_cs_x86.zip"指向的是一款专为32位Windows系统设计的Navicat for MariaDB的11.0版本。这款工具以其直观的界面和强大的功能,让数据库管理变得轻松而高效。 首先,Navicat for MariaDB是...

    Automatic_installation_for_MariaDB_on_Linux(MariaD_ansible-

    Automatic_installation_for_MariaDB_on_Linux(MariaD_ansible-mariadb

    Mariadb_install_linux.rar

    本文将详细介绍如何使用提供的shell脚本"Mariadb_install_linux"在CentOS 7上进行MariaDB的安装。MariaDB是MySQL的一个分支,由MySQL的创始人创建,旨在保持开源和不受Oracle公司控制。 1. **CentOS 7系统准备**: ...

    mariadb_10.0.14 龙芯cpu 安装包

    mariadb_10.0.14 龙芯cpu 安装包,已经适配了3A3000,3a4000. 安装后需要命令好启动。 安装路径为\usr\local\mysql。 仅供研究使用,请勿商用。

    mariadb_v10.5.8_winx64_itmop.com.zip

    这个“mariadb_v10.5.8_winx64_itmop.com.zip”压缩包包含了在Windows 64位系统上运行的MariaDB 10.5.8版本。 MariaDB 10.5.8是该数据库系统的一个重要版本,提供了许多新特性和改进。以下是一些关键知识点: 1. *...

    mariadb_cluster1:Docker 容器上的 MariaDB 集群

    Docker pull jsdizon/mariadb_cluster1 创建图像。 git clone https://github.com/jsdizon/mariadb_cluster1.git docker build -t mariadbcluster . 单个 Docker 服务器 假设我们有一个 docker 服务器,我们将...

    MariaDB_Query_Pro_V6.0.0.1

    A simple tool, which can help you bring all data stored in Excel Data Files into MariaDB, and then you can handle your data in MariaDB via this tool through Excel. Just try it!

    NetBackup82_MariaDB_AdminGuide.pdf

    VERITAS NetBackup 8.2 中文管理指南是 Veritas Technologies LLC 发布的一份关于 VERITAS NetBackup for MariaDB 的管理指南,该指南适用于 Windows 和 Linux 平台,版本为 8.2。本指南最后一次更新时间为 2019 年 ...

    NetBackup83_MariaDB_AdminGuide.pdf

    物理备份直接备份数据库文件,而逻辑备份则基于SQL语句,适用于复杂的数据库结构和特定的恢复场景。 4. **备份与恢复流程**:NetBackup提供了详细的步骤来执行MariaDB数据库的备份和恢复操作。备份过程中,数据会被...

    NetBackup812_MariaDB_AdminGuide.pdf

    Veritas NetBackup 8.1.2 是一款强大的数据保护解决方案,特别针对MariaDB数据库管理系统设计的管理员指南。本指南提供了在Windows和Linux操作系统上管理MariaDB备份的详细信息,帮助用户确保数据的安全性和可恢复性...

    NetBackup811_MariaDB_AdminGuide.pdf

    Veritas NetBackup 8.1.1 for MariaDB Administrator's Guide是专为在Windows和Linux平台上管理和保护MariaDB数据库设计的一份详细指南。Veritas Technologies LLC是一家知名的备份和恢复解决方案提供商,其...

    navicat150_mariadb_en.dmg navicat-for-mariadb: 15.0.12

    用于MariaDB的Navicat为MariaDB数据库管理和开发提供了本机环境。连接到本地/远程MariaDB服务器,并与Amazon RDS兼容。适用于MariaDB的Navicat支持大多数附加功能,例如新的存储引擎,微秒,虚拟列等。

    mariadb_mysql_CH_ZN.txt

    Wamp数据库帮助中文

    CENTOS7.X下MariaDB_Galera集群安装及配置真实可用

    按照解压后Galera.txt中的操作一步步做,20分钟安装配置好CENTOS7.X(现本人在用的是7.6)下的MariaDB 10.3.12(最新稳定版2019.1.7发布)的Galera 25.24的双主集群。 MariaDB 为Mysql的开原版,百分百兼容Mysql,双...

Global site tag (gtag.js) - Google Analytics