Skip to content

Instantly share code, notes, and snippets.

@jpotts18
Last active August 29, 2015 14:20
Show Gist options
  • Save jpotts18/6c5b5ed1b134d96e955b to your computer and use it in GitHub Desktop.
Save jpotts18/6c5b5ed1b134d96e955b to your computer and use it in GitHub Desktop.

Basic SQL Debugging

Use Whitespace

Can you find the syntax error?

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;

What about now?

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;

Use a GUI

  • brew cask install sequel-pro
  • brew cask install mysqlworkbench

Check your indexes

If it is an id it needs to be indexed.

Explain your queries

When you precede a SELECT statement with the keyword EXPLAIN, MySQL displays information from the optimizer about the statement execution plan. That is, MySQL explains how it would process the statement, including information about how tables are joined and in which order.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment