Learning how to add comments to your SQL code

It's important to add comments to your SQL code to ensure it's clear to you and others what is in the script. You may want to save this script for later or share it with others, and it will make a lot of difference if you comment your code with explanations. For straightforward scripts like we've been running in this chapter, it might not make much difference, but for larger and more complex queries, it will be beneficial.  

When creating comments, it's important to note a few things, such as who created the code, when the code was created, who last modified the code, the date of the modification, and an explanation of why it was created or modified.  

We briefly covered commenting on your code in Chapter 4, Designing and Creating a DatabaseTo create a single-line comment, use #. To create a multi-line comment, place your comment between /* and */. The following code sample shows you how to use each of these comments:

# this is single line comment 

/*
this is a multi line comment
*/

To comment properly in a SQL script, you should put something like this at the top of your script: 

/*
Created by: Josephine Bush
Created on: November 15, 2019
Purpose: Selecting distinct rows in appearances table to provide in a report

Modified by Modified on Modification notes
JBush 11/16/19 Changed distinct to include teams and playerids
*/

You can set whatever format you want in the comments at the top of the file. The previous code example is just that, an example, but it's good to be as thorough as possible for future reference.  

It's also good to make other comments along the way with either single- or multi-line comments, especially if your script file contains a lot of SQL statements. 

You can place comments anywhere in your code, as long as it won't cause the code to fail or cause an error. For example, if you want to comment out a section of the SELECT clause, you can do that like this: 

USE lahmansbaseballdb;
SELECT playerid, g_all, g_batting, /*g_defense*/ FROM appearances
LIMIT 500 OFFSET 1000;

In the previous query, g_defense was commented out. The g_defense column will no longer be returned in the results of the query. However, there's a problem here – I didn't comment out the comma before the field I commented out. This syntax will cause an error such as Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM appearances LIMIT 500 OFFSET 1000' at line 1. We can fix this like so:

USE lahmansbaseballdb;
SELECT playerid, g_all, g_batting/*, g_defense*/ FROM appearances
LIMIT 500 OFFSET 1000;

By making this fix, the script will run correctly. It won't include the g_defense column in the results. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.17.91