Relational Database Development

Similar documents
Using SQL Queries in Crystal Reports

Ad Hoc Advanced Table of Contents

Information and Computer Science Department ICS 324 Database Systems Lab#11 SQL-Basic Query

Structured Query Language (SQL)

3.GETTING STARTED WITH ORACLE8i

Netezza SQL Class Outline

Microsoft Access Lesson 5: Structured Query Language (SQL)

Joins Joins dictate how two tables or queries relate to each other. Click on the join line with the right mouse button to access the Join Properties.

Creating QBE Queries in Microsoft SQL Server

Oracle SQL. Course Summary. Duration. Objectives

Performing Queries Using PROC SQL (1)

Access Queries (Office 2003)

Oracle Database: SQL and PL/SQL Fundamentals

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Excel: Introduction to Formulas

Microsoft Access 3: Understanding and Creating Queries

Chapter 1 Overview of the SQL Procedure

Database Query 1: SQL Basics

COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries

Advanced Query for Query Developers

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database: SQL and PL/SQL Fundamentals NEW

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Information Systems SQL. Nikolaj Popov

AN INTRODUCTION TO THE SQL PROCEDURE Chris Yindra, C. Y. Associates

Advanced Online Media Dr. Cindy Royal Texas State University - San Marcos School of Journalism and Mass Communication

Introduction to Microsoft Jet SQL

SQL Basics. Introduction to Standard Query Language

EXCEL Using Excel for Data Query & Management. Information Technology. MS Office Excel 2007 Users Guide. IT Training & Development

Appendix A Practices and Solutions

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

User Training Guide Entrinsik, Inc.

SQL SELECT Query: Intermediate

Database Applications Microsoft Access

Programming with SQL

Financial Data Access with SQL, Excel & VBA

Recognizing PL/SQL Lexical Units. Copyright 2007, Oracle. All rights reserved.

A Brief Introduction to MySQL

Database Administration with MySQL

MICROSOFT ACCESS STEP BY STEP GUIDE

History of SQL. Relational Database Languages. Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG)

Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro

Access 2003 Introduction to Queries

Using AND in a Query: Step 1: Open Query Design

SES Project v 9.0 SES/CAESAR QUERY TOOL. Running and Editing Queries. PS Query

Oracle Database: SQL and PL/SQL Fundamentals NEW

Exploring Microsoft Office Access Chapter 2: Relational Databases and Multi-Table Queries

Kaseya 2. Quick Start Guide. for VSA 6.3

SQL Server Database Coding Standards and Guidelines

Oracle Database 12c: Introduction to SQL Ed 1.1

Introduction to SQL and SQL in R. LISA Short Courses Xinran Hu

Participant Guide RP301: Ad Hoc Business Intelligence Reporting

FileMaker 13. SQL Reference

Advance DBMS. Structured Query Language (SQL)

Excel Working with Data Lists

Oracle Database 10g: Introduction to SQL

1 Structured Query Language: Again. 2 Joining Tables

Jet Data Manager 2012 User Guide

Introduction to SQL for Data Scientists

Inquiry Formulas. student guide

Essentials of SQL. Essential SQL 11/06/2010. NWeHealth, The University of Manchester

Resources You can find more resources for Sync & Save at our support site:

Chapter 8. SQL-99: SchemaDefinition, Constraints, and Queries and Views

HRS 750: UDW+ Ad Hoc Reports Training 2015 Version 1.1

MOC 20461C: Querying Microsoft SQL Server. Course Overview

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

P_Id LastName FirstName Address City 1 Kumari Mounitha VPura Bangalore 2 Kumar Pranav Yelhanka Bangalore 3 Gubbi Sharan Hebbal Tumkur

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

Paper Merges and Joins Timothy J Harrington, Trilogy Consulting Corporation

I PUC - Computer Science. Practical s Syllabus. Contents

NATIONAL INSTITUTE OF HOTEL MANAGEMENT, KOLKATA

Q&As: Microsoft Excel 2013: Chapter 2

Boats bid bname color 101 Interlake blue 102 Interlake red 103 Clipper green 104 Marine red. Figure 1: Instances of Sailors, Boats and Reserves

SQL Programming. Student Workbook

MS Access: Advanced Tables and Queries. Lesson Notes Author: Pamela Schmidt

Using Multiple Operations. Implementing Table Operations Using Structured Query Language (SQL)

Microsoft Excel 2010 Part 3: Advanced Excel

Microsoft Access 2010 Overview of Basics

How To Create A Table In Sql (Ahem)

In This Issue: Excel Sorting with Text and Numbers

InterBase 6. Embedded SQL Guide. Borland/INPRISE. 100 Enterprise Way, Scotts Valley, CA

Results CRM 2012 User Manual

Parameter Fields and Prompts. chapter

PeopleSoft Query Training

Click&DECiDE Business Application Intelligence

Handling Missing Values in the SQL Procedure

Instant SQL Programming

Excel 2007: Basics Learning Guide

A table is a collection of related data entries and it consists of columns and rows.

Data Tool Platform SQL Development Tools

Commonly Used Excel Functions. Supplement to Excel for Budget Analysts

Click to create a query in Design View. and click the Query Design button in the Queries group to create a new table in Design View.

VBScript Database Tutorial Part 1

DbSchema Tutorial with Introduction in SQL Databases

Chapter 5. Microsoft Access

IRA Pivot Table Review and Using Analyze to Modify Reports. For help,

Key Functions in Oracle SQL

Access 2010: Creating Queries Table of Contents INTRODUCTION TO QUERIES... 2 QUERY JOINS... 2 INNER JOINS... 3 OUTER JOINS...

Aggregating Data Using Group Functions

Introduction to Proc SQL Steven First, Systems Seminar Consultants, Madison, WI

Transcription:

Relational Database Development 152-156 Structured Query Language (SQL) Single Table Queries Text References Basic Select Pages 97 98, 100 Selecting Fields Pages 98 99 Selecting Records (Criteria) Pages 100 107 110 112 128 Distinct Pages 117 119 Sorting Results Pages 112 114 Calculated Fields Pages 107-110 Calc Fields and Order By, Where Pages Formatting Results Pages Grouping Pages 114 117 123 128 Select Statement Clause Order Pages Sub-Queries Pages 120 123 Import Employee database in MySQL Access the MySQL documentation online for more information on MySQL commands and functions: http://dev.mysql.com/doc Basic Query Select * From tblname; * represents all fields Selecting Specific Fields for Display List the fields in the order desired between Select and From Separate fields with a comma Show all fields from tblemployees, tblplants, tbltrips Show employee firstname, lastname, plantid, unionmember 1

Selecting Records Add the Where keyword after the table name Follow the keyword with a condition that records must meet to be included in the query results Select * From tblname Where condition SQL Conditional operators =, <, >, <=, >=, <>,!= Between And Literals for character data comparison must be surrounded with apostropes or quotes Literals for date data comparison must be surrounded with apostrophes in yyyy-mm-dd format or entered as yyyymmdd (no dashes, apostrophes optional) Compound condition operators And, Or, Not, &&, Seems to be no order of precedence. All conditions evaluated left to right. Same fields, but only show Coloma (plant ID=1) Display (all fields) employees hired between 1997 and 2001 (17) Display employees not working in Polonia=2 (37) using <>!= not Bit fields require a little extra thought You can compare to the bit values 0 (false) and 1 (true) Alternatively, you can compare a bit field to the values False and True This seems more self-documenting The best way to use bit (yes/no true/false) values in conditions is to just use the field name (see first examples below) 0 = false any non-zero = True Works with imported Access data where true = -1 Examples: Select * From tblstudent Where fulltime; Select * From tblstudent Where Not fulltime; Select * From tblstudent Where fulltime = 1; Select * From tblstudent Where fulltime = True; Display employees who are not union members (=0, =False, not unionmember) (8 rows) Display employees who are union members (True) (no match) Display where union = -1 Import was from Access. Use Update command to change all -1 to 1 set sql_safe_updates=0; Display employees who are union members (True) (42 rows) Display females in Coloma(1) who are union (2 rows) 2

In fieldname In (valuelist) Records that match any one of the values in valuelist are included in the query results Shorter than using multiple OR conditions Example: Where Color In ( Red, White, Blue ) Like fieldname Like substring Like allows you to search for records where a field contains a given substring The substring can appear at the beginning, end or in the middle of the field. The Like keyword is always used with the wildcard character: % The wildcard character represents any character or characters (including no characters). The wildcard character can be placed at the beginning of the substring, end of the substring, in the middle of the string, or any combination of those locations. Examples: Where Name Like Dav% Shows all names that start with Dav Where Name Like %son Shows all names that end with son Where Name Like %son% Shows all names that contain the letters son anywhere in the field. Where Name Like A%son Shows all names that start with the letter A and end in son There is a second wildcard character, underscore (_) that matches any single character. Name Like T_m Shows all names that are exactly 3 characters long, starting with T, ending with m (Tom, Tim, T2m). Select employees who work in Coloma(1) and Polonia(2). (25 rows) Use Or Use In Display trips where the destination starts with C (59 rows) That contains c Display employees whose phone contains 333 (2 rows) 3

RLike Similar to Like but using regular expressions Where custname RLike '^[afw].*$' All customers whose names start with a, f or w List employees whose lastnames starts with a, d or p DISTINCT Is Null, Is Not Null To check for empty fields use: fieldname Is Null Not fieldname = Null (doesn t work, but not sytax error) Removes duplicate values from a queries results Select Major From tblenroll Where Course='152-120'; This example will simply list the major of each student in this class. If more than one student has the same major, the major will be repeated for each student. Select Distinct(Major) From tblenroll Where Course='152-120'; This version only shows each major once. Select Count(Distinct(CrsNumber)) From tblofferings Where Semester='SP2002'; Counts the number of courses offered in the SP2002 semester, ignoring duplicate offerings of the same course. List trips where duration is null. Expenses is null Expenses null and duration not null Using tblemployee generate a list of plants Generate a list of destinations that have been traveled to. Generate a list of destinations each employee (ID) has traveled to (sort by city, employee) (232 rows) Note # of rows in trips (300) 4

Sorting Query Results Query results are displayed in an undefined order unless you specify otherwise. Order By clause allows you to specify how records are to be sorted. Order By field1[desc][, field2] etc. If Order By clause is used with the Where clause, the Where clause must be specified first The Order By keywords are followed by one or more field names that specify which fields values should be used to sort the list. The first field listed is the primary sort key the list sorted by these values first. The second field is the secondary sort key if the values in the primary sort key are the same, those records are sorted by the values in this sort key. You can specify as many secondary sort keys are you need to break ties in the previous sort keys By default, records are sorted in ascending order (A-Z, 0-9). To reverse the sort order (descending), use the keyword Desc after any sort key. Examples: Order By ZipCode Order By LName, FName Order By AmtOwed Desc Order By AmtOwed Desc, LName, FName Where ZipCode= 54481 Order By LName Calculated Fields As you know, calculated fields are not typically stored in the database. Queries can be used to display calculated fields users need. To create a calculated value, simply enter the equation for the calculated field in the field list. Use parenthesis to improve readability. Calculated values can also be used in comparisons (Where) +-*/ are the only operators available. Everything else is a function. Note, you can include the select all operator in the field list along with calculated fields: Provide a list of trips to Chicago order by expenses. Most expensive first. Where expenses > 500 (8 rows) Provide a list of cities and expenses sorted by destination then expenses, descending Calc cost per day for every trip where cost per day > 200 order by cost per day desc Select *, InstCost*0.055 From tblinstall 5

Date Calculations To add a certain number of days to a date, you can use the AddDate or SubDate functions Examples: AddDate(CurDate(), 45) SubDate(CurDate(), 30) To add months or years, you can use the second version of the AddDate or SubDate function. AddDate(datevalue, Interval value inttype) inttype is either Day, Week, Month or Year value is the number of days, months or years you want to add datevalue is the name of the field or another date value you want to add to. Newer versions of MySQL even allow you to add intervals to dates by simply using the + operator Subtraction works too Examples: Select checkoutdate, AddDate(checkOutDate, Interval 14 Day) As duedate From tbllibrary; Select CustName, AddDate(startDate, Interval 18 Month) As subscriptionend From tblsubscribers; Select checkoutdate, checkoutdate + Interval 14 Day As duedate From tbllibrary; Concatenating Strings To concatenate strings in MySQL, you must use the Concat function: neither + nor & work Surround literals with apostrophes You CAN include numeric fields in a Concat statement Example: Select Concat(City, ', ', State, ' ', Zip) As CSZ From tblcustomer; Calc return date from every trip Using interval Using + (note format) Using + interval Show a list all employees and their hire dates in one field. 6

Renaming Calculated Fields To improve the appearance of the query results and simplify Order By clauses, you can assign field names (an alias in SQL speak) to calculated fields If you don t, the formula appears as the column header Include the keyword As or, simply a space, after the formula, followed by the name for the field Example: (See examples above) Using Calculated Fields in Order By and Where Clauses You CANNOT use an alias in a Where clause For example (using the tblcustomer example from above), you CAN NOT append the following Where clause to the SQL statement Where CSZ Like 'Steven%' Set calc field name to Combined Sort by Combined Show only employees whose last name is alphabetically before D (10 rows) Instead, you d have to repeat the formula Where Concat(City, ', ', State, ' ', Zip) Like 'Steven%' Actually, depending on your needs, you might be able to leave out the literals (comma and spaces) and maybe even the zip code in the Where clause. They shouldn t affect the results of the filter. You CAN use an alias in an Order By clause (see below) Can also repeat the formula though that s much longer. For example (using the tblcustomer example from above), you CAN append the following Order By clause to the SQL statement Order By CSZ 7

Formatting Results Formatting is normally done by front end programs (written in a programming language) that access the database tables. If you need to however, you can format the output of SQL queries. Formatting Decimal Values To format numbers, use the Format function Format(field, decimals) The Format function requires two parameters: the field to format the number of decimal places to display All numbers include commas when appropriate Example: Select Format(Avg(Salary),2) As AvgSalary From tblemployee; Formatting Dates Use the Date_Format function to format dates Date_Format(datefield, 'formatstring') Datefield is the field name or date literal to be formatted Formatstring will probably include some of the following: %d (day) %m (month) %Y (4-digit year) See the Date_Format documentation for additional formatting codes Calc cost per day of trip formatted 2 decimals Sort by Cost per day Note sorting error. Correct in Order By List trip date, duration and return date of each trip. Format MMMM d, yyyy (see documentation) Sort by return date desc 8

Functions Count Returns the number of records that would have appeared in the query results instead of the records themselves Select Count(*) From STUDENT Where Major= CIS If implementation of SQL doesn t support the *, use the primary key field name instead Sum Returns the sum of a field of all the records that would have appeared instead of the records themselves Select Sum(Credits) From ENROLL Where LName= Gaul Avg Returns the average of a field from all the records. Min Returns the smallest value of a field from all the records. Max Returns the largest value of a field from all the records. Display total number of trips (to Chicago) Display total amount of expenses (format) (to Chicago) Display min and max duration Display average cost per day 9

Grouping Grouping combines records with the same value in a designated field and calculates a statistical value(s) for every group Group By fieldname Select LName, Sum(Credits) From ENROLL Where Semester='SP2014' Group By LName; Displays the total credits for each student enrolled in the SP2014 semester (sorted by last name). Results of queries that use grouping are sorted by the group field by default. You can specify an Order By clause to override this. Having clause The Having clause allows you to control which groups show in the query results You can use an alias in a Having clause Select LName, Sum(Credits) As totalcredits From tblenroll Where Semester='SP2014' Group By LName Having totalcredits> 12 Order By totalcredits Desc; Displays the total credits for each student enrolled in the SP2014 semester (sorted by total credits descending) (2013) Having is compatible with format. However, formatting converts numbers to strings. When doing a Having comparison, compare to a string. select plantid, format(sum(salary),1) as TotalSalary from tblemployees group by plantid having totalsalary> 400,000 ; Having vs. Where Where restricts records from being included in the query results Having restricts group statistics from being included in the query results With Rollup Adding this clause to a grouped query includes the grand total (or grand average) in an additional row at the bottom of the query. With Rollup must follow the Group By clause With Rollup is not compatible with Order By Calc total salary for all employees format For non-union employees Calc total salary grouped by union status if(unionmember, Union, Salaried ) As Type Calc total salary grouped by plant Grouped by plant, then union status Add grand totals Calc average expenses per day for each employee Sort descending (format) Only include people who average over $300/day Only include Chicago Display the number of trips taken to each city in descending order of number trips. 10

Clause Order The last example under grouping above shows the correct order of clauses when many SQL clauses are included in the same statement. These clauses must always be specified in this order the clauses cannot be rearranged. For example, you cannot designate an Order By clause before the Where clause. 1. Select 2. From 3. Where 4. Group by 5. With Rollup 6. Having 7. Order by (not with Rollup) Sub-Queries Sub-queries allow you to use the results of one query as a criteria for another. For this unit, the sub-query must return a single value. In the next unit, sub-queries will return multiple fields and multiple rows. Example: Display the student(s) with the highest GPA Select LastName, FirstName, GPA From tblstudent Where GPA= (Select Max(GPA) From tblstudent); Display name and salary of person with highest salary (using order by) Display name and salary of union member with lowest salary. Display name and salary of person with highest salary. Display name an salary of union member with lowest salary. Display destination and cost per day for any trip over the average cost per day sorted by cost per day, highest to lowest. Display the city and avg cost with the highest average cost per day. Note: can be done using Limit 1 (end of statement) but Limit is MySQL, not standard Select * for all employees who work in the Coloma plant using a subquery to determine plant 11