The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by ronald.torres.h, 2023-08-14 13:05:07

RPT101i SQL I (With Answers)

RPT101i SQL I (With Answers)

EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Cogito RPT101i SQL I (With Answers) If completing Continuing Epic Education requirements, visit your My Certificates page for additional information.


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Epic Systems Corporation 1979 Milky Way | Verona, WI 53593 | Voice: 608.271.9000 | Fax: 608.271.7237 www.epic.com [email protected] Last Revised: April 15, 2023


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Table of Contents Introduction Relational Databases Write a Basic Query Logical Expressions Functions Join Tables Introduction to Grouping Performance 1 • 1 2 • 1 3 • 1 4 • 1 5 • 1 6 • 1 7 • 1 8 • 1 RPT101i SQL I 3


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 4 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Introduction Introduction Other Email Contacts Epic Resources View a Training Companion With and Without Answers How to Use This Training Companion Practice Scope of the SQL Self‐Studies Epic Version Caboodle and Clarity Microsoft SQL Server and Oracle Uses of SQL SQL Self‐Assessments What If I Already Know SQL? What Is Covered On Each Self‐Assessment? When Should I Complete the Self‐Assessments? How Do I Complete a Self‐Assessment? What If I Don't Pass? What If I Need More Information? Reviewing the Chapter 1 • 3 1 • 3 1 • 4 1 • 6 1 • 6 1 • 7 1 • 9 1 • 9 1 • 9 1 • 9 1 • 9 1 • 11 1 • 11 1 • 11 1 • 11 1 • 11 1 • 12 1 • 13 Introduction 1 • 1 RPT101i SQL I 5


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 1 • 2 Introduction 6 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Introduction Welcome to Epic's RPT101i SQL I self‐study. This document will help you write and interpret SQL queries and make the most of Epic's other relational database training materials and documentation. When you have questions, please email [email protected]. That email address sends emails to a queue which is monitored by a member of Cogito's training team each day, meaning it is a more efficient way to get your questions answered compared to trying to find a single person to email. When sending an email, it is helpful if you can provide some additional information right away: What companion, chapter, and page﴾s﴿ you are referencing If you are asking about something you see in the system, please include: Companion or task name, section header, page number, and step Any configuration you did that the trainer may need to look up What troubleshooting you previously tried that didn't give you the intended results Other Email Contacts Below are a few other common resources you may need. When in doubt, you can always email the training team and a trainer will help you find the right support. Introduction 1 • 3 RPT101i SQL I 7


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 I have questions about... Who should I contact? Logging into the UserWeb [email protected] Troubleshooting issues when launching a cert environment or a Virtual Training environment Preparing for a virtual class? Be sure to review How to Prepare For Virtual Training first. Still having issues? Contact your trainers. If you already received a pre‐class email you can reply to that email. Otherwise, consult the email address at the beginning of these training materials. Accessing or viewing e‐learning lessons E‐[email protected] Registering for class [email protected] Signing up for a proctored exam or finding a proctor [email protected] Requesting an exam review for a proctored exam Reply to your exam score email Understanding Continuing Epic Education requirements ﴾Application Essentials and New Version Training﴿ [email protected] Understanding how to best build at my organization Your Epic representative﴾s﴿ Principal Trainer ﴾TED﴿ certificates [email protected] Epic Resources This table outlines pertinent supplemental resources that are available to you that will help you find the information that you need. Here is a list of the tools available and how they should be used: Epic's online documentation portal. Contains training materials, setup and support guides, and a variety of other useful documents. https://galaxy.epic.com 1 • 4 Introduction 8 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Epic provided platform for E‐Learning content. Hosts e‐ learnings created by Epic as well as customer built modules. https://welearning.epic.com Online collection of tools and information about Epic and our software. On your front page you can favorite discussions to read/participate in. https://userweb.epic.com The Community Library is Epic's content sharing program. Technical Services routinely extract content data from customers' systems, which Epic then hosts on the UserWeb for customer review and use. https://comlib.epic.com Epic's web‐based issue tracking tool. Use Sherlock to have direct access to create and update Support Logs ﴾SLGs﴿, Release Authorizations, and Reportable Issues. https://sherlock.epic.com Epic's training website encompassing a variety of training‐ related tools used by our organizations. Contains Certification Tracking, Course Catalog, Exam Requests, training announcements, and Training Wheels materials. https://training.epic.com The Data Handbook provides reference information to access data within your enterprise production database. https://datahandbook.epic.com Nova is an Epic‐developed web program for release note management. You can use Nova to assign and review release notes, select which enhancements to implement, and report on release note progress. https://nova.epic.com Introduction 1 • 5 RPT101i SQL I 9


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Looking for more guidance through these tools? Check out the UserWeb Overview document which can be found by clicking the blue button in the top right of your screen as soon as you log into the https://userweb.epic.com site: UserWeb Overview View a Training Companion With and Without Answers In Galaxy, you can view a training companion with and without answers using a toggle on the menu on the right: You can also download either version from the toolbar: 1. Click Download Options. 2. Select ﴾Without Answers﴿ or ﴾With Answers﴿. How to Use This Training Companion This training companion is intended as a tool for learning. Use it as a resource and a place for notes. You'll find informative text boxes and do‐now steps throughout the lessons to draw your attention to specific content. There are a number of different types of text boxes you might encounter. Each has a different purpose as defined below: 1 • 6 Introduction 10 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 A "Critical Box" means that information shared here is critical. An "Example Box" illustrates the definitions, tasks, and concepts described in the surrounding text. Often, there is a narrative to give context to one or more SQL queries that can be run in the study environments. A "Real World Context" box has tips for how you can use SQL to help you write and troubleshoot SQL. See the Practice section for more information. A "Beyond the Basics" box means you are being provided additional information that may be helpful to enhance understanding, but is not critical. You do not need to know this information for this course's assessment. Practice While completing this self‐study, try the examples, practice, and complete the exercises. Reference the Cogito's Introduction to Epic's Cert Environments document for information on how to log in and use our study system. Specifically, use the instructions to connect to SQL Management Studio to create, save, open, and run queries against training databases. Here are some recommended ways to try the examples, practice, and complete the exercises: Connect to our practice environment by accessing Study SQL Studio from access.epic.com ﴾euaccess.epic.com for trainees who connect to that server﴿. Instead of typing out an example query, copy the example query from a digital copy of the training companion. Then paste it into the SQL Management Studio named Study SQL Studio from access.epic.com ﴾euaccess.epic.com﴿, run the query, and look at the result. Instead of starting an exercise query from scratch, start with a similar query. Then modify the query as necessary. Instead of creating an entire query and hoping it will run as desired, create the query incrementally. First, write a simple query, run it, and resolve any errors. Then add a little more to the query, run it, and resolve any errors. Repeat until you have the full, desired query. Get curious! If you don't think your result set looks right, or if you think you could write your query in a different way, explore away! Run modified or brand‐new queries that aren't specifically described in the training companion but pique your interest. To check if a specific part of a query is behaving correctly, temporarily modify the query to make Introduction 1 • 7 RPT101i SQL I 11


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 validation easier. Just remember to revert your changes when you're done. Throughout this training companion, watch for boxes like this one that explain how you can temporarily modify a query to check that the original query is behaving as expected. These recommendations will make more sense as you work through the SQL self‐studies, so refer back to this list often. Moreover, you may benefit from following most of these same recommendations even after you've completed the SQL self‐studies. 1 • 8 Introduction 12 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Scope of the SQL Self‐Studies There are many uses of SQL in the industry and with Epic's software. This section outlines expectations of the material covered in the SQL self‐studies and the corresponding self‐assessments. Epic Version The content in this document is intended to be useful for all versions of Epic. This document is part of Epic's training curricula starting with the Epic 2018 version. The SQL self‐assessments do not assume nor test knowledge of a specific version of Epic. Caboodle and Clarity This document is designed for business intelligence developers working with Epic's relational databases: Caboodle and Clarity. Examples use Caboodle and Clarity database objects. However, knowledge of Caboodle and Clarity is not assumed and not directly taught in this document. The SQL self‐assessments do not assume nor test knowledge of Caboodle and Clarity. To differentiate between the two databases, database objects in PascalCase are in Caboodle while database objects in ALL_CAPS are in Clarity. In Management Studio, the USE command can be used to quickly switch between databases ﴾see the Change Databases section of Cogito's Introduction to Epic's Cert Environments﴿. ‐‐This is a Caboodle example USE Caboodle_Feb SELECT * FROM PatientDim ‐‐This is a Clarity example USE Clarity_Feb SELECT * FROM PATIENT Microsoft SQL Server and Oracle The cert environments and all implementations of Caboodle use Microsoft SQL Server. Some implementations of Clarity use Microsoft SQL Server and some use Oracle. Therefore, this document uses SQL Server but calls out where and how Oracle differs. Most of the content in this document is not specific to a given version of SQL Server or Oracle, but where necessary the focus is on recent target platforms as listed in Epic's Target Platform Guide, found on Galaxy. The SQL self‐assessments DO NOT test information specific to SQL Server nor specific to Oracle. To do well on the self‐assessments, you DO need to know either SQL Server or Oracle, but not both. Uses of SQL This document is designed for business intelligence developers writing SQL queries to retrieve data from Introduction 1 • 9 RPT101i SQL I 13


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 relational databases. SQL queries and other commands that modify relational databases are beyond the scope of this document. In short, much of the SQL self‐studies are about using the SELECT statement. 1 • 10 Introduction 14 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 SQL Self‐Assessments What If I Already Know SQL? Depending on how much SQL you already know, you may not need to work through every page of the self‐studies. The end of each lesson has a list of objectives in the form of a study checklist. Make sure you're comfortable with each of the lesson's objectives that are listed. For any objectives with which you are not comfortable, work through the corresponding sections in the training companion. Once you're comfortable with all the objectives, go on to the next lesson. What Is Covered On Each Self‐Assessment? Each SQL self‐assessment tests your mastery of the material covered in the corresponding SQL self‐study. The RPT121i SQL II self‐assessment does not directly test material from RPT101i SQL I; rather the RPT121i SQL II self‐assessment is written assuming you know the material from RPT101i SQL I. See the Scope of the SQL Self‐Studies section for further clarification. When Should I Complete the Self‐Assessments? All of the SQL self‐assessments can be completed immediately; there are no prerequisite tasks other than being familiar with the content of the training companions. You need to pass the RPT101i SQL I self‐assessment prior to attending a data model class. Historically, trainees who have attempted to learn SQL and a data model at the same time have struggled. If you're unable to pass the assessment prior to your data model class﴾es﴿, you should reschedule your class registration﴾s﴿. Trainees who have not passed the RPT101i SQL I self‐assessment prior to a data model class will be unregistered. The RPT121i SQL II self‐assessment may be taken after the data model class﴾es﴿, but it should be completed prior to attempting the data model after‐class exercises and data model exam﴾s﴿. Passing both SQL self‐assessments is required for data model certifications. How Do I Complete a Self‐Assessment? In general, Epic self‐assessments are accessed on the Epic UserWeb. 1. Access your training track in EpicU by going to the Training Home > Your In‐Progress Certificates > select the relevant training track. 2. Find the section of the track with Self‐Assessment in its title. 3. Click the Take Assessment link. Alternatively, you can access self‐assessments through the Course Catalog. Use the appropriate application and/or role filters to locate your training track. Within the relevant course card, expand the Self‐Assessment header to find the link to the self‐assessment. Introduction 1 • 11 RPT101i SQL I 15


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 The SQL self‐assessments are open book and open system. There is no time limit, though the exam is similar in structure to Epic's two‐hour exams. Like other self‐assessments, your progress is saved when you close the web page. So, you can pause, resume, and continue the assessment until you submit it for grading. For customers and consultants, a passing score is 80%. For Epic employees, a passing score is 85%. What If I Don't Pass? What If I Need More Information? After you submit your self‐assessment and the grading is completed, you will receive an email summarizing your results. Included is a list of objectives for which you missed points. Use the list to direct your studies should you want to reattempt the self‐assessment. The self‐assessments can be attempted up to two times per day, even if you've already passed. Once you achieve a passing score, any additional attempts will not affect your progress toward certification. In addition to the Epic‐provided training materials and the email address listed at the beginning of this training companion, remember that SQL is an industry‐standard language. Here are some non‐Epic vendor‐specific resources: Microsoft's Transact‐SQL Reference ﴾Database Engine﴿ documentation Oracle's Database SQL Language Reference website While completing your studies, use your favorite internet search engine to find further documentation. Also consider reaching out to your coworkers. The self‐assessments must be completed on your own, but studying doesn't have to be a solo effort. For the RPT101i SQL I self‐assessment, the objectives in the email are links to specific sections of the RPT101i Self‐Assessment Study Guide. Use this study guide to identify what areas you still need to study to prepare for the RPT101i SQL I self‐assessment. Each tested objective is listed with questions to check your understanding. The questions are open‐ended and intentionally do not include the answers. If you can answer each of the questions confidently, then you are ready for the assessment. Otherwise, see the links to the pertinent references to the training materials. Our course content is confidential information. If you are planning to create online flashcards or any other online study tools to help you study, we ask that you ensure that your flashcards are password protected and not available to the general public. We appreciate your help in protecting our intellectual property. 1 • 12 Introduction 16 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Reviewing the Chapter Review Questions 1. How can you tell the difference between Caboodle and Clarity database objects in the training materials? 2. How do you change databases in the cert environments? 3. Whom should you contact if you have questions about the SQL self‐study training materials? Choose only ONE answer. A. [email protected] B. [email protected] C. [email protected] D. Your Epic representative﴾s﴿ Review Key Introduction 1 • 13 RPT101i SQL I 17


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Review Key 1. How can you tell the difference between Caboodle and Clarity database objects in the training materials? Database objects in PascalCase are in Caboodle while database objects in ALL_CAPS are in Clarity. 2. How do you change databases in the cert environments? Run the USE command or use the database dropdown. 3. Whom should you contact if you have questions about the SQL self‐study training materials? Choose only ONE answer. A. [email protected] B. [email protected] C. [email protected] D. Your Epic representative﴾s﴿ A. [email protected] Study Checklist 1 • 14 Introduction 18 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Study Checklist Make sure you can perform the following tasks: ☐ Distinguish between Caboodle and Clarity database objects in the training materials ☐ Change databases in the cert environments ☐ Execute a SQL query in the cert environments ☐ Save a SQL query in the cert environments ☐ Access exercise answer keys in the cert environments ☐ Start a SQL self‐assessment ☐ Reference Cogito's Introduction to Epic's Cert Environments Make sure you fully understand and can explain the following concepts: ☐ The SQL self‐assessments are not specific to a version of Epic ☐ The SQL self‐assessments only require knowledge of SQL Server or Oracle, but not both ☐ The RPT101i SQL I self‐assessment must be passed before attending a data model class ☐ The RPT121i SQL II self‐assessment should be passed before attempting the data model after‐ class exercises and the data‐model‐specific assessments Introduction 1 • 15 RPT101i SQL I 19


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Relational Databases Introduction Relational Database Terminology Diagram Database Concepts What is SQL? Relational Database Data Types Nullable Other Database Objects Look Up Definitions Log in and Get Ready to Try it Out! Constraints SP_HELPCONSTRAINT ﴾SQL Server﴿ ALL_CONSTRAINTS ﴾Oracle﴿ Columns SP_COLUMNS ﴾SQL Server﴿ DESCRIBE ﴾Oracle﴿ Reviewing the Chapter 2 • 3 2 • 4 2 • 5 2 • 5 2 • 5 2 • 6 2 • 6 2 • 6 2 • 8 2 • 8 2 • 8 2 • 8 2 • 9 2 • 10 2 • 10 2 • 13 2 • 15 2 • 1 Relational Databases 20 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Relational Databases 2 • 2 RPT101i SQL I 21


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Introduction Data can be stored in computers in any number of ways including text, spreadsheets, and images. Some methods of storing data are more structured than others. Structured data can make working with the data easier and more efficient. A text file can store any number of characters in any order. If the file contains monetary information about transactions, summing the transaction amounts of a specified date range may prove difficult. On the other hand, a well‐built spreadsheet will have data stored in rows and columns where each of the rows and columns have a different meaning. If each row is a transaction and there is a separate column for date and amount, then the same task is trivial. Relational databases allow storing data in a highly structured way, even more structured than spreadsheets. This allows for more efficient data retrieval and summarization. In this lesson, you'll be introduced to some core relational database concepts that you'll put into practice throughout the rest of this training companion. By the End of This Lesson, You Will Be Able To... Identify types of database objects in a relational database Identify data types of columns in a relational database List constraints of a table List columns of a table Describe how SQL is used to retrieve data from a relational database 2 • 3 Relational Databases 22 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Relational Database Terminology Diagram Relational database terminology with Clarity examples Relational Databases 2 • 4 RPT101i SQL I 23


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Database Concepts What is SQL? SQL stands for Structured Query Language. It is generally pronounced "es‐queue‐el" or "see‐kwell". SQL is the industry standard for communicating with relational databases ﴾covered in the next section﴿. SQL has many implementations, including Microsoft SQL Server and Oracle. A block of SQL code that is to be executed on a relational database is known as a SQL statement. A SQL statement that results in a dataset is called a SQL query. Relational Database In relational databases, each type of entity is represented by a different table. A table is a database object made up of rows and columns; each row represents a different entity and each column represents a different attribute about that entity. In relational database terminology, row and record are often used interchangeably. In the PATIENT table, each row represents one patient. The PAT_NAME column holds the name of each patient. In the CLARITY_SER table, each row represents one provider. The PROV_NAME column holds the name of each provider. When referring to a specific column "COLUMN_NAME" in a specific table "TABLE_NAME", to avoid ambiguity it's customary to refer to the pair by listing both separated by a period: "TABLE_NAME.COLUMN_NAME". Special columns hold values that indicate how the different entities relate to each other, hence the term relational database. Each table has a primary key: one or more columns whose value﴾s﴿ uniquely identify a row in that table. Tables may have one or more foreign keys. A foreign key is one or more columns whose value﴾s﴿ uniquely identify a row in another table. In other words, foreign keys hold primary key values of another table. The primary key of the PATIENT table is the PAT_ID column: every value in PATIENT.PAT_ID will be unique. The primary key of the CLARITY_SER table is PROV_ID. The column PATIENT.CUR_PCP_PROV_ID holds a value that corresponds to a patient's current general primary care provider. PATIENT.CUR_PCP_PROV_ID is a foreign key to CLARITY_SER.PROV_ID. Our task in relational database reporting is to take a request for information and translate that into a SQL query. Our research will determine: 1. Which tables do we need? 2. Which columns do we need? 3. How will we use the columns to get the information requested? 2 • 5 Relational Databases 24 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Throughout this training companion, we will assume we have answered the first two questions and we'll primarily focus on the last question. Data Types Each column has a data type: a restriction on what format the data in that column can hold. The data type often dictates how the column can be used. Below is an overview of relational database data types and some specific, common data types used in SQL Server and Oracle. Classification SQL Server Examples Oracle Examples Data Type Description Character string NVARCHAR, VARCHAR VARCHAR2 A combination of characters is often called a string. 'Bob Thompson', 'V13.4', and '‐46' are all valid strings. A string column has a defined maximum length. Numeric NUMERIC, FLOAT, BIGINT, INT, TINYINT, BIT NUMBER, FLOAT Numeric columns contain real numbers. 42, ‐1, 3.141592653, and 6.022x10^23 are all examples. In general, number columns will have a defined precision and scale. The precision is the maximum number of digits, the scale is the number of digits to the right of the decimal point. Date/time DATE, DATETIME, DATETIME2 DATE Date/time columns hold dates and times. Values in these columns may also vary by levels of precision: from days down to fractions of seconds. Nullable The intersection of a row and column in a table is a specific value. In some cases, the value may be NULL . This means that the value is not populated. There is nothing there: not '', not 0, not 'NULL'; nothing. This may indicate that the value was never recorded or that the value isn't applicable to the row. A column is nullable if it allows NULL values. Primary keys are inherently non‐nullable, but other columns may be non‐nullable as well. Whether or not a column is nullable has implications on how the column should be used. Other Database Objects Below are descriptions of types of database objects that may make querying relational databases more efficient. We will make use of some of these in this document and reference others in your follow‐up Relational Databases 2 • 6 RPT101i SQL I 25


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 training. Object Description Views Views are queries that are stored in the database. A view can be accessed as if it were a table. Unlike tables, however, views do not actually hold data. This means that using a view will not necessarily increase the efficiency of a query. However, views can reduce the amount of work that business intelligence developers must do by reducing the complexity of a query. Examples: V_SCHED_APPT, V_ACCESS_LOG Stored procedures A SQL statement stored in your SQL Server so that it can be run as needed. These are often used to populate tables based off of other information already stored in the database. Example: ESP_F_SCHED_APPT ﴾the script that populates F_SCHED_APPT﴿ Materialized views Materialized views are tables populated from queries that run against other tables. Materialized views are often populated by stored procedures. Using materialized views can reduce the amount of work that business intelligence developers must do: one materialized view might take the place of several tables. Materialized views can increase query efficiency; they are like pre‐compiled and saved query results. Examples: F_SCHED_APPT, D_MU_MEASURES Functions Functions can take in parameters and return results. In general, they do not make changes to the database. Functions can be used directly by SQL queries. Functions will be discussed in more detail in the Functions lesson of this training companion. Example: CURRENT_TIMESTAMP 2 • 7 Relational Databases 26 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Look Up Definitions With the appropriate security, you can retrieve metadata about database objects from the database. Keep in mind that this metadata is what is enforced by the database. The applications that populate and work with the data may enforce additional structure. The PAT_ENC table has one row per encounter The PAT_ENC_CSN_ID column is the primary key The PAT_ENC_DX table has one row per encounter diagnosis The PAT_ENC_CSN_ID column is a foreign key to the PAT_ENC table In the examples below, you'll find that the primary key of the PAT_ENC_DX table is documented but the foreign key to the PAT_ENC table is not. This is an example of a foreign key that is enforced by the application but not by the database. Looking up definitions that aren't stored in the database are beyond the scope of this lesson, but they are still provided in examples and exercises for context. The methods of retrieving metadata about database objects is different between SQL Server and Oracle. Review the Microsoft SQL Server and Oracle section of the Introduction lesson for a reminder of what is expected on the assessments. Log in and Get Ready to Try it Out! See the Practice and Caboodle and Clarity sections of the Introduction lesson so you can perform the examples and exercises throughout the rest of this training companion. You can explore by writing your own queries too. Try out the example in the next section. Constraints Primary keys and foreign keys are two constraints on the structure of the data that can be enforced by the database. SP_HELPCONSTRAINT ﴾SQL Server﴿ In SQL Server, the SP_HELPCONSTRAINT stored procedure can be used to list the primary keys and foreign keys of a table. Run SP_HELPCONSTRAINT TableName where TableName is the name of the table for which you want to list the constraints. One of the results of the stored procedure is a table that includes two columns: constraint_type holds the type of constraint constraint_keys lists the columns of the constraint Relational Databases 2 • 8 RPT101i SQL I 27


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Because calling a stored procedure is different from running a SELECT statement, switching databases may be required prior to calling a stored procedure instead of with the stored procedure. If you're using a USE statement to switch databases, run it separately or follow it with a GO command. For example, USE Clarity_Feb GO SP_HELPCONSTRAINT PAT_ENC_DX The PAT_ENC_DX table has one row per encounter diagnosis Running SP_HELPCONSTRAINT PAT_ENC_DX yields a result with at least one constraint: constraint_type constraint_keys PRIMARY KEY ﴾clustered﴿ PAT_ENC_CSN_ID, LINE Therefore, the primary key of the PAT_ENC_DX table is made up of two columns: PAT_ENC_CSN_ID LINE Many of the Caboodle database objects referenced in this training companion are actually views in the FullAccess schema. Many of these views reference tables of the same name in the dbo schema. Because views may not have as many constraints as the underlying tables, running SP_HELPCONSTRAINT on the table in the dbo schema may be more useful. Use the syntax SP_HELPCONSTRAINT 'Schema.TableName' where Schema is the desired schema. For example, USE Caboodle_Feb GO SP_HELPCONSTRAINT 'dbo.AddressDim' ALL_CONSTRAINTS ﴾Oracle﴿ In Oracle, the ALL_CONSTRAINTS and ALL_CONS_COLUMNS tables can be used to list the primary keys and foreign keys of a table. Querying both tables and filtering on the desired table name returns each constraint on a column in the table. The syntax used for querying the tables is beyond the scope of this lesson but will be introduced in later lessons. The result will include three columns: 2 • 9 Relational Databases 28 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 CONSTRAINT_TYPE holds the type of constraint ﴾P for primary key, R for foreign key﴿ POSITION holds the primary key position COLUMN_NAME holds the column name The PAT_ENC_DX table has one row per encounter diagnosis The query SELECT CONSTRAINT_TYPE, POSITION, COLUMN_NAME FROM ALL_CONSTRAINTS INNER JOIN ALL_CONS_COLUMNS ON ALL_CONSTRAINTS.CONSTRAINT_NAME = ALL_CONS_COLUMNS.CONSTRAINT_NAME AND ALL_CONSTRAINTS.OWNER = ALL_CONS_COLUMNS.OWNER WHERE ALL_CONSTRAINTS.TABLE_NAME = 'PAT_ENC_DX' yields a result with at least two rows: CONSTRAINT_TYPE POSITION COLUMN_NAME P 2 LINE P 1 PAT_ENC_CSN_ID Therefore, the primary key of the PAT_ENC_DX table is made up of two columns: PAT_ENC_CSN_ID LINE Columns A column's data type and whether or not a column allows NULL values is also strictly enforced by the database. SP_COLUMNS ﴾SQL Server﴿ In SQL Server, the SP_COLUMNS stored procedure can be used to list the columns of a table. Run SP_COLU MNS table_name where table_name is the name of the table for which you want to list the columns. The result is a table that includes several columns: COLUMN_NAME holds the name of the column TYPE_NAME holds the data type PRECISION holds the precision ﴾most applicable to numeric data types﴿ Relational Databases 2 • 10 RPT101i SQL I 29


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 LENGTH holds the length ﴾most applicable to date/time data types﴿ SCALE holds the scale ﴾most applicable to numeric data types﴿ IS_NULLABLE indicates if the column is nullable 2 • 11 Relational Databases 30 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 The PAT_ENC_DX table has one row per encounter diagnosis The PAT_ENC_CSN_ID column is the first of two columns in the primary key The LINE column is the second of two columns in the primary key The CONTACT_DATE column holds the date of the encounter The DX_ID column holds the diagnosis ID The PRIMARY_DX_YN column indicates if the diagnosis is primary Running SP_COLUMNS PAT_ENC_DX yields a result with at least these rows and columns ﴾the column names listed prior to this example have been abbreviated﴿: COLUMN TYPE PRE C LEN SCA LE IS_NULLABL E LINE int 10 4 0 NO CONTACT_DATE datetime 23 16 3 YES PAT_ENC_CSN_ID numeric 18 20 0 NO DX_ID numeric 18 20 0 YES PRIMARY_DX_YN varchar 1 1 NUL L YES Therefore: PAT_ENC_CSN_ID has a datatype of NUMERIC﴾18, 0﴿ and must be populated LINE has a datatype of INT and must be populated CONTACT_DATE has a datatype of DATETIME and may not be populated DX_ID has a datatype of NUMERIC﴾18, 0﴿ and may not be populated PRIMARY_DX_YN has a datatype of VARCHAR﴾1﴿ and may not be populated For the numeric examples above, the numbers in parenthesis represent the precision and scale, respectively. For the character string example, the number in parenthesis represents the maximum length. Relational Databases 2 • 12 RPT101i SQL I 31


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 DESCRIBE ﴾Oracle﴿ DESCRIBE ﴾Oracle﴿ In Oracle, the DESCRIBE stored procedure can be used to list the columns of a table. Run DESCRIBE table_ name where table_name is the name of the table for which you want to list the columns. The result is a table that includes three columns: 'Name' holds the name of the column 'Null' indicates if the column is nullable 'Type' holds the data type 2 • 13 Relational Databases 32 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 The PAT_ENC_DX table has one row per encounter diagnosis The PAT_ENC_CSN_ID column is the first of two columns in the primary key The LINE column is the second of two columns in the primary key The CONTACT_DATE column holds the date of the encounter The DX_ID column holds the diagnosis ID The PRIMARY_DX_YN column indicates if the diagnosis is primary Running DESCRIBE PAT_ENC_DX yields a result with at least these rows: Name Null Type LINE NOT NULL NUMBER﴾38﴿ CONTACT_DATE DATE PAT_ENC_CSN_ID NOT NULL NUMBER﴾18﴿ DX_ID NUMBER﴾18﴿ PRIMARY_DX_YN VARCHAR2﴾1﴿ Therefore: PAT_ENC_CSN_ID has a datatype of NUMBER﴾18,0﴿ and must be populated LINE has a datatype of NUMBER﴾38,0﴿ and must be populated CONTACT_DATE has a datatype of DATE and may not be populated DX_ID has a datatype of NUMBER﴾18,0﴿ and may not be populated PRIMARY_DX_YN has a datatype of VARCHAR2﴾1﴿ and may not be populated For the numeric examples above, the numbers in parenthesis represent the precision and scale, respectively. For the character string example, the number in parenthesis represents the maximum length. Relational Databases 2 • 14 RPT101i SQL I 33


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Reviewing the Chapter Review Questions 1. Which of the following database object types is more typically used to make a change to data on a database when called? Choose only ONE answer. A. A view B. A stored procedure C. A materialized view D. A function 2. Which database object type can reference other database objects at query run time: table, view, or materialized view? 3. What data types would you expect to store a dollar amount, a person's name, and birthday, respectively? Review Key 2 • 15 Relational Databases 34 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Review Key 1. Which of the following database object types is more typically used to make a change to data on a database when called? Choose only ONE answer. A. A view B. A stored procedure C. A materialized view D. A function B. A stored procedure. 2. Which database object type can reference other database objects at query run time: table, view, or materialized view? View. 3. What data types would you expect to store a dollar amount, a person's name, and birthday, respectively? Numeric, character string, date/time. Study Checklist Relational Databases 2 • 16 RPT101i SQL I 35


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Study Checklist Make sure you can define the following key terms: ☐ SQL ☐ Relational database ☐ SQL query ☐ Table ☐ Row ☐ Column ☐ Primary key ☐ Foreign key ☐ Data type ☐ Character string data types ☐ Numeric data types ☐ Date/time data types ☐ Precision ☐ Scale ☐ NULL ☐ View ☐ Materialized view ☐ Stored procedure Make sure you can perform the following tasks: ☐ Determine the primary key of a table ☐ Determine the foreign keys of a table ☐ List the columns of a table ☐ Determine the datatype of a column ☐ Determine if a column is nullable 2 • 17 Relational Databases 36 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Make sure you fully understand and can explain the following concepts: ☐ How data is stored in a relational database ☐ How functions and stored procedures differ Relational Databases 2 • 18 RPT101i SQL I 37


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Write a Basic Query Introduction SQL Query Data Flow Example The SELECT Statement The SELECT Clause Exercise 1: SELECT All Rows and Columns Comments SELECT Columns Exercise 2: SELECT Columns Exercise 3: SELECT Additional Columns The ORDER BY Clause Exercise 4: ORDER BY a Column Exercise 5: ORDER BY Multiple Columns Exercise 6: ORDER BY a Column in Reverse The SELECT TOP Statement ﴾SQL Server﴿ SQL Writing Style Column Aliases General Style Choices Exercise 7: Add Column Aliases Exercise 8: SELECT Columns with Aliases Reviewing the Chapter 3 • 3 3 • 4 3 • 5 3 • 7 3 • 7 3 • 7 3 • 8 3 • 9 3 • 9 3 • 11 3 • 11 3 • 11 3 • 12 3 • 13 3 • 14 3 • 14 3 • 14 3 • 15 3 • 15 3 • 17 3 • 1 Write a Basic Query 38 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Write a Basic Query 3 • 2 RPT101i SQL I 39


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 Introduction A SQL query is a request for information: a description of the output you would like. The database will then determine how to best compile and return that information. This is different than many other popular programming languages in which your code is a set of instructions for the computer to follow. Using formal terminology, SQL is a declarative programming language in contrast with imperative programming languages. For those who have primarily used imperative programming languages ﴾such as C, Java, Perl, or Python﴿, using SQL will require a mind shift. For those new to programming, welcome! In this lesson, you'll learn the basics of how to specify what you'd like returned by your query. By the End of This Lesson, You Will Be Able To... Write and run a query Describe how the SELECT clause is used Describe how the FROM clause is used Identify column aliases in a SQL query 3 • 3 Write a Basic Query 40 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 SQL Query Data Flow Example Write a Basic Query 3 • 4 RPT101i SQL I 41


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 The SELECT Statement A SQL query is made of several clauses. Each of these clauses fulfills one or more purposes in the query as a whole. The two SQL clauses that are required for any SQL query to get information from the database are the SELECT and FROM clauses. A query may also be called a SELECT statement. Clause Description SELECT List the columns that should appear in your result grid. FROM Specify the data sources used in your query, typically tables. The result of any SQL query is a table. This means that you can write queries and use them as tables. This will be discussed further in the RPT121i SQL II training companion. SQL queries must be written with their clauses in the following order: SELECT FROM WHERE GROUP BY HAVING ORDER BY However, when implementing the query, SQL effectively processes the clauses in the following order: FROM WHERE GROUP BY HAVING SELECT ORDER BY Because of this, when you are analyzing a SQL query, you may find it helpful to read the query in this second order. 3 • 5 Write a Basic Query 42 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 The SELECT , FROM , WHERE , GROUP BY , and ORDER BY clauses are all introduced in the RPT101i SQL I training companion. The HAVING clause is introduced in the RPT121i SQL II training companion. Recall that SQL is a declarative programming language: when we write a SQL query, we describe the result we want, but we can't control how the result is generated. In particular, SQL may not technically process the clauses in the order specified above. For many useful situations, this is a moot point because SQL effectively processes the clauses in that order. Therefore, unless otherwise specified, the training materials from here forward won't include the word "effectively" when describing the order a SQL query is processed. Write a Basic Query 3 • 6 RPT101i SQL I 43


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 The SELECT Clause One of the most basic requests that can be made to a database is to ask it to list all of the contents in a table. This request is fulfilled by the syntax... SELECT * FROM TableName ...where TableName is the specific table name. In words, this is "return every row and every column in the table." The asterisk ﴾ * ﴿ means "all columns," and we have not limited the rows returned. Exercise 1: SELECT All Rows and Columns In this exercise, you'll practice returning all rows and columns in a table. Background The AddressDim table has one row per address documented. Task Write a query to return all columns for every address in the AddressDim table. Comments Comments are sections of text within your query that are not treated as code; in fact, they are completely ignored by SQL. Proper documentation with comments enables both you and others to better use, understand, view, and edit your queries. Comments can start at any point during the query, on their own line or not. Line comments start with a double‐dash ﴾ ‐‐ ﴿, which will cause the rest of the line to become a comment. Block comments start with a forward‐slash followed by an asterisk ﴾ /* ﴿, which will cause all text to be treated as a comment until it reaches an asterisk followed by a forward‐slash ﴾ */ ﴿. 3 • 7 Write a Basic Query 44 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 ‐‐Below are two equivalent queries SELECT ‐‐ Everything to the right of the double‐dash ‐‐ is ignored * ‐‐ Even if it's the only thing on the line FROM AddressDim /* This is a block comment. It can occupy several lines. */ SELECT /* Block Comments can even be embedded in a line */ * FROM AddressDim Comments can provide a method of troubleshooting since they can be used to temporarily disable sections of code. This can make it easier to selectively focus your attention on a certain section of code. To comment out a section of code means to put that section of code in a comment. Commenting out a section of code enables easily re‐adding the code later by uncommenting the section of code: undoing the commenting syntax. In the next section is an example query that returns values of two columns. SELECT PatientKey, Name FROM PatientDim To temporarily modify the query to only return the Name column ﴾so it's easier for you to devote your attention to that column﴿ you can comment out the PatientKey column so that it isn't evaluated by the SELECT clause. SELECT ‐‐PatientKey, Name FROM PatientDim After you are done investigating the Name column, uncomment the PatientKey column. Both line comments and block comments can be used to comment out code. Portions of individual clauses and even entire clauses can be commented out. As you learn more SQL syntax, revisit this concept and consider how commenting out code could be useful. SELECT Columns Often, using SELECT * FROM TableName will get you plenty of data, but will probably return more than you need. Instead, you will want to choose specific columns. Write a Basic Query 3 • 8 RPT101i SQL I 45


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 The SELECT list is a comma‐separated list of columns to return in your results. /* A query demonstrating returning the PatientKey and Name columns from the PatientDim table */ SELECT PatientKey, Name FROM PatientDim Exercise 2: SELECT Columns In this exercise, you'll practice writing a query in the order that it will be processed. Background The CLARITY_SER table has one row per provider Task Write a query to return the PROV_ID, PROV_NAME, PROV_TYPE, STAFF_RESOURCE_C, and EXTERNAL_NAME columns from the CLARITY_SER table. Save your query so you can build on in Exercise 7: Add Column Aliases. Step‐by‐Step 1. Create a new query and type the following text. FROM CLARITY_SER Recall that the FROM clause is processed before the SELECT clause. Building the query in the same order as it is processed can help you ensure that you're building a query with valid syntax. Also, building the FROM clause first improves completion matching for the rest of the query. 2. Add the following text before the FROM clause. SELECT PROV_ID, PROV_NAME, PROV_TYPE, STAFF_RESOURCE_C, EXTERNAL_NAME 3. Test the query by running it. 4. Save your query so you can build on it in Exercise 7: Add Column Aliases. Exercise 3: SELECT Additional Columns In this exercise, you'll practice writing a query to return columns from a table. Background 3 • 9 Write a Basic Query 46 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 The VisitFact table has one row per visit encounter Task Write a query to return the VisitKey, PatientKey, EncounterDateKey, MinutesInRoom, DepartmentKey, and PrimaryVisitProviderKey from the VisitFact table. Write a Basic Query 3 • 10 RPT101i SQL I 47


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 The ORDER BY Clause The queries we've seen so far did not return rows in any specified order. We can control the order the results are returned by using the ORDER BY clause . For example, you may want to sort by name in alphabetical order, by dollar amount from highest to lowest, or in chronological order. All of this can be done by adding the ORDER BY clause to a query and adding appropriate columns to that clause. Review The SELECT Statement section as a reminder of where the ORDER BY clause appears and when it is processed in relation to the other clauses. To sort by a column, it does not need to appear in the SELECT clause. ORDER BY is followed by a comma‐delimited list of columns that you want to sort in order of precedence. By default, results appear in ascending order. To do a reverse sort, add the DESC keyword after the column. This is particularly effective at sorting dates, as in the following example, where the DESC keyword will put the most recent dates at the top of the set. SELECT * FROM PAT_ENC ORDER BY CONTACT_DATE DESC Exercise 4: ORDER BY a Column In this exercise, you'll practice sorting a query result by a column. Background The AddressDim table has one row per address The Address column holds the street address The City column holds the city The StateOrProvince column holds the state or province The PostalCode column holds the postal code Task Write a query that lists each address, city, state ﴾or province﴿, and postal code, sorted by postal code. Exercise 5: ORDER BY Multiple Columns In this exercise, you'll practice sorting a query result by multiple columns. Background The V_PAT_FACT view has one row per patient The PAT_ID column holds the patient's ID The PAT_NAME column holds the patient's name The AGE_YEARS column holds the patient's age in years 3 • 11 Write a Basic Query 48 RPT101i SQL I


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 The CUR_PCP_NAME_WID column holds the patient's current general primary care provider's name and ID The CUR_PCP_PROV_ID column holds the patient's current general primary care provider's ID Task Write a query that returns each patient's ID, name, age, and current general provider's name with ID. Sort by provider ID and then by patient name. Exercise 6: ORDER BY a Column in Reverse In this exercise, you'll practice sorting a query result in reverse chronological order. Background The ORDER_PROC table has one row per procedure order The ORDER_PROC_ID column holds the order's ID The PROC_ID column holds the procedure's internal ID The DESCRIPTION column holds the procedure description The ORDERING_DATE column holds the ordering date Task Write a query that returns each procedure order's ID, internal procedure ID, procedure description, and ordering date sorted by the ordering date, putting the most recent orders at the top of the list. This is the end of the exercise. The ORDER BY clause can be useful when validating or troubleshooting a query without affecting which rows are returned. For example, if you're not sure if a column returned by your query is ever populated, temporarily add it to the ORDER BY clause ﴾optionally with DES C ﴿. If that column is populated, you'll see the values listed in the last ﴾or first, respectively﴿ rows of your result. Write a Basic Query 3 • 12 RPT101i SQL I 49


EpicUUID: 5143F74D-DB01-4131-AAA3-52F4753E50D4 The SELECT TOP Statement ﴾SQL Server﴿ If you're using SQL Server, you just need a little more syntax to greatly reduce the performance impact of your test queries on the database. Go to the Use Fewer Rows While Developing section of the Performance lesson now, and then return to this lesson. Oracle folks, your time will come later. 3 • 13 Write a Basic Query 50 RPT101i SQL I


Click to View FlipBook Version