29
Fri, Nov
0 New Articles

SQL 101: DDL Recap—Improving Our Basic SQL Tables, Part 2

SQL
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Our example table is starting to look like a proper one! Let’s continue with a couple of typical SQL features: default values for optional columns and audit-related columns. These may seem like simple things, but they’ll save you a ton of time.

Time. That’s more and more the issue, especially when something goes wrong and you need to get things done quickly. So let’s introduce a couple of time-saving features into our example table; you’ll thank me later for them!

Providing Proper Default Values for Optional and Audit-Related Columns

Now that I have created a primary key for this table, let’s see what other enhancements can be performed. A quick inspection of the application’s student enrollment screen shows that the fields Email address, Driver’s license, and Social Security Number have a default value of N/A. However, this is an application-only behavior: if a record is inserted via SQL and a value for these fields is not provided, they’ll be left blank because that was the default value specified on the CREATE TABLE statement. The screen also shows the current user, time, and date, even though those details are not stored with the student’s record. This is a shortcoming of the application, because auditors really like to know this kind of stuff when they come snooping around.

Let’s address all of these issues. Again, I could destroy the table with a DROP statement, fix the CREATE TABLE statement, and recreate the table. However, this would also delete the data in the table, if there is any. Instead, I’ll use another ALTER TABLE statement:

ALTER TABLE UMADB_CHP3.PFSTM

ADD COLUMN STCU VARCHAR(18) DEFAULT USER

ADD COLUMN STCT TIMESTAMP DEFAULT CURRENT TIMESTAMP

   ALTER COLUMN STEM SET DEFAULT 'N/A'   

   ALTER COLUMN STDL SET DEFAULT 'N/A'

   ALTER COLUMN STSN SET DEFAULT 'N/A'

   ALTER COLUMN STSC SET DEFAULT '1'

;

A couple of notes about this statement: First, it shows that you can change more than one thing at a time; I’m adding new columns and changing existing ones at the same time. Second, there are a few keywords, known as special registers, that you can use to refer to “system things,” such as the current user’s name or the current timestamp. There are others, such as CURRENT_DATE, CURRENT_TIME, CURRENT TIMEZONE, CURRENT SERVER, and CURRENT SCHEMA, to name just a few. These will allow you to mimic a typical native application’s behaviors. In fact, storing information about the record-creation user and timestamp is a good practice—and the auditors love stuff like that. I’ll show you later how to do the same for the last update user and timestamp, another auditor-favorite feature of a proper table.

I don’t want to sound repetitive, but remember: SQL is not DDS. If you add new columns to a table, always remember to execute the appropriate LABEL ON statement to provide clear and concise descriptions for your columns. Let’s do that for the three new columns added to PFSTM:

LABEL ON COLUMN UMADB_CHP3.PFSTM

   (

      STID TEXT IS 'Record ID'

      , STCU TEXT IS 'Created by'

      , STCT TEXT IS 'Created on'

   )

;

If you back up a bit, to the last ALTER TABLE statement, you’ll probably notice I also provided a new default for the STSC column. This is just another example of how you can simplify data insertion: specifying that new records are in active status ('1') by default saves me the trouble of including that information on future INSERT statements. Speaking of INSERT statements, let’s see how the table changes I’ve performed impact those statements. Here’s how I’d mimic the native application’s student enrollment functionality before my ALTER TABLE statements:

INSERT INTO UMADB_CHP3.PFSTM

(STNM, STDB, STAD, STPN, STMN, STEM, STDL, STSN, STSC)

VALUES(

'Mailer, Norman'

      , 19750318

      , '2234 Blackstone Avenue, Joyville, South Carolina'

      , '555-001-123'

      , '999-010-469'

      , 'N/A'

      , 'N/A'

      , 'N/A'

      , '1'

)

;

Even though I don’t have a value for the email, driver’s license, and Social Security Number, I still had to mention them on the INSERT in order to force the appropriate “not available” value the application is expecting. I also had to include STSC with the value '1' to indicate that the record is active. Now let’s see how the same INSERT looks after the changes performed via ALTER TABLE:

INSERT INTO UMADB_CHP3.PFSTM

(STNM, STDB, STAD, STPN, STMN)

VALUES(

'Mailer, Norman'

      , 19750318

      , '2234 Blackstone Avenue, Joyville, South Carolina'

      , '555-001-123'

      , '999-010-469'

)

;

The statement is much shorter, but there’s no loss of functionality because the defaults are used by the database engine to fill the columns for which I didn’t specify a value. Additionally, the three new columns (the unique ID, record-creation user, and respective timestamp) are automatically filled in by the system.

Time for Some Practice

Before moving on to the section on views, it’s time for you to practice what you’ve learned so far. Try to modify the CREATE TABLE and LABEL ON statements that were automatically generated for the rest of the tables in order to include the three new columns I added to PFSTM: the unique ID, the creation user, and the creation timestamp. Try following the same naming convention I’m using for the column names: a two-character prefix indicates the table (for instance, CO for courses) followed by two characters that define the type of value the column will hold (for instance, CU for creation user). Let me get you started: here are the modified CREATE TABLE and LABEL ON statements for the Grades table:

CREATE TABLE UMADB_CHP3.PFGRM

   (

      GRID INTEGER

         PRIMARY KEY

         GENERATED ALWAYS

         AS IDENTITY(START WITH 1

               INCREMENT BY 1)

      , GRSN CHAR(60) CCSID 37 NOT NULL DEFAULT ''

      , GRCN CHAR(60) CCSID 37 NOT NULL DEFAULT ''

      , GRCY DECIMAL(4, 0) NOT NULL DEFAULT 0

      , GRGR CHAR(2) CCSID 37 NOT NULL DEFAULT ''

      , GRCU VARCHAR(18) DEFAULT USER

      , GRCT TIMESTAMP DEFAULT CURRENT TIMESTAMP

   )       

   RCDFMT PFGRMR

;

LABEL ON TABLE UMADB_CHP3.PFGRM

            IS 'UMADB - Grades Master File' ;

LABEL ON COLUMN UMADB_CHP3.PFGRM

   (

      GRID TEXT IS 'Record ID'

      , GRSN TEXT IS 'Student name'

      , GRCN TEXT IS 'Class name'

      , GRCY TEXT IS 'Class year'

      , GRGR TEXT IS 'Grade'

      , GRCU TEXT IS 'Created by'

      , GRCT TEXT IS 'Created on'

   )

;

The next task is to copy the data from UMADB_CHP2’s physical files to UMADB_CHP3’s tables. You can either use the traditional CPYF or use what you’ve learned in the previous subseries and issue INSERT ... SELECT statements instead. If you need some help, you can find a file with all the necessary statements here.

Now that our tables are proper SQL tables, we can start working on other things to make our database easier to use: SQL Views. But that’s for the next article…

Rafael Victoria-Pereira

Rafael Victória-Pereira has more than 20 years of IBM i experience as a programmer, analyst, and manager. Over that period, he has been an active voice in the IBM i community, encouraging and helping programmers transition to ILE and free-format RPG. Rafael has written more than 100 technical articles about topics ranging from interfaces (the topic for his first book, Flexible Input, Dazzling Output with IBM i) to modern RPG and SQL in his popular RPG Academy and SQL 101 series on mcpressonline.com and in his books Evolve Your RPG Coding and SQL for IBM i: A Database Modernization Guide. Rafael writes in an easy-to-read, practical style that is highly popular with his audience of IBM technology professionals.

Rafael is the Deputy IT Director - Infrastructures and Services at the Luis Simões Group in Portugal. His areas of expertise include programming in the IBM i native languages (RPG, CL, and DB2 SQL) and in "modern" programming languages, such as Java, C#, and Python, as well as project management and consultancy.


MC Press books written by Rafael Victória-Pereira available now on the MC Press Bookstore.

Evolve Your RPG Coding: Move from OPM to ILE...and Beyond Evolve Your RPG Coding: Move from OPM to ILE...and Beyond
Transition to modern RPG programming with this step-by-step guide through ILE and free-format RPG, SQL, and modernization techniques.
List Price $79.95

Now On Sale

Flexible Input, Dazzling Output with IBM i Flexible Input, Dazzling Output with IBM i
Uncover easier, more flexible ways to get data into your system, plus some methods for exporting and presenting the vital business data it contains.
List Price $79.95

Now On Sale

SQL for IBM i: A Database Modernization Guide SQL for IBM i: A Database Modernization Guide
Learn how to use SQL’s capabilities to modernize and enhance your IBM i database.
List Price $79.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: