75
1 Basic SQL Basic SQL Missouri State Missouri State University University Computer Services Computer Services Short Course Short Course

1 Basic SQL Missouri State University Computer Services Short Course

Embed Size (px)

Citation preview

Page 1: 1 Basic SQL Missouri State University Computer Services Short Course

11

Basic SQLBasic SQL

Missouri State UniversityMissouri State University

Computer ServicesComputer Services

Short CourseShort Course

Page 2: 1 Basic SQL Missouri State University Computer Services Short Course

22

Contact InformationContact Information

Greg Snider – MIS Database AnalystGreg Snider – MIS Database Analyst

Ext. 6-4397Ext. 6-4397

Email – [email protected][email protected]

Don’t hesitate to email or call if you have Don’t hesitate to email or call if you have any questions after you start writing your any questions after you start writing your own queries.own queries.

Page 3: 1 Basic SQL Missouri State University Computer Services Short Course

33

Web Sites to noteWeb Sites to note

https://www.secure.missouristate.edu/mis/https://www.secure.missouristate.edu/mis/QDUG/QDUG.aspQDUG/QDUG.asp - The site for the Query Developer User - The site for the Query Developer User GroupGroup

https://www.secure.missouristate.edu/mis/https://www.secure.missouristate.edu/mis/database/DBS0100.aspdatabase/DBS0100.asp - The site for table documentation (what - The site for table documentation (what columns are in what tables, what those columns are in what tables, what those columns contain, etc.)columns contain, etc.)

Page 4: 1 Basic SQL Missouri State University Computer Services Short Course

44

ContentsContents

ConceptsConcepts– What is SQL?What is SQL?– TerminologyTerminology

SQL LanguageSQL Language– Its partsIts parts

SELECT StatementSELECT Statement

Query ManagerQuery Manager

Page 5: 1 Basic SQL Missouri State University Computer Services Short Course

55

What is SQL?What is SQL?

S(trucured) Q(uery) L(anguage)S(trucured) Q(uery) L(anguage)

A standard language for accessing dataA standard language for accessing data

Designed to be portableDesigned to be portable

Used by most database vendorsUsed by most database vendors

It’s how you access data stored in a …It’s how you access data stored in a …

Page 6: 1 Basic SQL Missouri State University Computer Services Short Course

66

TerminologyTerminology

TableTable– A set of rows with columns containing dataA set of rows with columns containing data– Think of a table as a large spreadsheetThink of a table as a large spreadsheet

SOC_SECSOC_SEC NAMENAME STU_ CLASSSTU_ CLASS GPAGPA HRSHRS

495867475495867475 Joe BlowJoe Blow JRJR 3.13.1 110110

547574395547574395 Sue SmithSue Smith SRSR 2.752.75 120120

647567364647567364 Jane DoeJane Doe FRFR 0.00.0 00

775847587775847587 Joe CoolJoe Cool SOSO 2.252.25 5555

Page 7: 1 Basic SQL Missouri State University Computer Services Short Course

Terminology Terminology Live and Cold TablesLive and Cold Tables

Cold or Query Tables are refreshed nightly Cold or Query Tables are refreshed nightly or at predetermined timesor at predetermined times

Live Tables can be updated as you write Live Tables can be updated as you write and run your queries.and run your queries.

Most of the tables you use in your queries Most of the tables you use in your queries are cold tables.are cold tables.

Page 8: 1 Basic SQL Missouri State University Computer Services Short Course

88

TerminologyTerminology

View View – Another way of accessing the data in a tableAnother way of accessing the data in a table– May or may not contain all the columns in a May or may not contain all the columns in a

tabletable– Can be a join of two or more tablesCan be a join of two or more tables– Transparent to the user Transparent to the user – Basically, a stored SQL SELECT statementBasically, a stored SQL SELECT statement

Page 9: 1 Basic SQL Missouri State University Computer Services Short Course

99

ViewViewSOC_SECSOC_SEC NAMENAME STU_ STU_

CLASSCLASSGPAGPA HRSHRS

495867475495867475 Joe Joe BlowBlow

JRJR 3.13.1 110110

547574395547574395 Sue Sue SmithSmith

SRSR 2.752.75 120120

647567364647567364 Jane Jane DoeDoe

FRFR 0.00.0 00

775847587775847587 Joe Joe CoolCool

SOSO 2.252.25 5555

SOC_SECSOC_SEC NAMENAME GPAGPA

495867475495867475 Joe BlowJoe Blow 3.13.1

547574395547574395 Sue SmithSue Smith 2.752.75

Table

View

Page 10: 1 Basic SQL Missouri State University Computer Services Short Course

1010

SQL LanguageSQL Language

Language elementsLanguage elements

StatementsStatements

FunctionsFunctions

JoinsJoins

UnionsUnions

SubselectsSubselects

Page 11: 1 Basic SQL Missouri State University Computer Services Short Course

1111

Language ElementsLanguage Elements

Data typesData types

ConstantsConstants

ExpressionsExpressions

PredicatesPredicates

Page 12: 1 Basic SQL Missouri State University Computer Services Short Course

1212

Data TypesData Types

Character stringsCharacter strings

DatetimeDatetime– DateDate– TimeTime

NumericNumeric– IntegerInteger– DecimalDecimal– NumericNumeric

Page 13: 1 Basic SQL Missouri State University Computer Services Short Course

1313

Character StringsCharacter Strings

Fixed lengthFixed length– 1 to 254 positions1 to 254 positions

Page 14: 1 Basic SQL Missouri State University Computer Services Short Course

1414

DateDate

DateDate– Format MM/DD/YYYYFormat MM/DD/YYYY– 10 positions10 positions

When using a date, it must be enclosed in When using a date, it must be enclosed in single quotes, ’09/16/2004’single quotes, ’09/16/2004’

Page 15: 1 Basic SQL Missouri State University Computer Services Short Course

1515

NumericNumeric

IntegerInteger– Small Small

32768 - +3276732768 - +32767

– LargeLarge-2147483648 - +2147483647-2147483648 - +2147483647

– DecimalDecimal15 digits max15 digits max(Precision, Scale)(Precision, Scale)Precision – how many digits totalPrecision – how many digits totalScale – how many digits to the right of the decimal pointScale – how many digits to the right of the decimal point

– NumericNumeric31 digits max31 digits max

Page 16: 1 Basic SQL Missouri State University Computer Services Short Course

1616

ConstantsConstants

Integer constantsInteger constants– 456, -789456, -789

Decimal constantsDecimal constants– 978.34, 9584.2746978.34, 9584.2746

String (character) constantsString (character) constants– ‘‘ABCE’, ‘Computers for Learning’ABCE’, ‘Computers for Learning’

Page 17: 1 Basic SQL Missouri State University Computer Services Short Course

1717

ExpressionsExpressions

OperatorsOperators– || or CONCAT, /, *, +, -|| or CONCAT, /, *, +, -– || only for strings|| only for strings– Standard rules apply for arithmetic operationsStandard rules apply for arithmetic operations

Page 18: 1 Basic SQL Missouri State University Computer Services Short Course

1818

Date ArithmeticDate Arithmetic

Admit_date + 2 months + 2 days is validAdmit_date + 2 months + 2 days is valid

Grad_date – Admit_date is validGrad_date – Admit_date is valid

Page 19: 1 Basic SQL Missouri State University Computer Services Short Course

1919

PredicatesPredicates

=, <>, <, >, <=, >= =, <>, <, >, <=, >= Between: expression (NOT) BETWEEN 123 and 999Between: expression (NOT) BETWEEN 123 and 999Null: expression IS (NOT) NULLNull: expression IS (NOT) NULLLike: expression (NOT) LIKE patternLike: expression (NOT) LIKE pattern– Pattern % represents 0 or more charactersPattern % represents 0 or more characters _ represents only 1 character_ represents only 1 character

Exists discussed when we talk about subselectsExists discussed when we talk about subselectsIn expression IN (value1, value2, value3, …)In expression IN (value1, value2, value3, …)AND and OR may be usedAND and OR may be used

Page 20: 1 Basic SQL Missouri State University Computer Services Short Course

2020

StatementsStatements

SelectSelect

Page 21: 1 Basic SQL Missouri State University Computer Services Short Course

2121

SelectSelect

Select clauseSelect clause

From clauseFrom clause

Where clauseWhere clause

Group by clauseGroup by clause

Having clauseHaving clause

Order by clauseOrder by clause

Page 22: 1 Basic SQL Missouri State University Computer Services Short Course

2222

Select ClauseSelect Clause

SELECT columns, expressionsSELECT columns, expressions

Tells what you want to seeTells what you want to see

Page 23: 1 Basic SQL Missouri State University Computer Services Short Course

2323

From ClauseFrom Clause

FROM datacoll.view-nameFROM datacoll.view-name

Datacoll is the owner of all our viewsDatacoll is the owner of all our views

Page 24: 1 Basic SQL Missouri State University Computer Services Short Course

2424

Where ClauseWhere Clause

WHERE search-conditionWHERE search-condition

Page 25: 1 Basic SQL Missouri State University Computer Services Short Course

2525

Group By ClauseGroup By Clause

GROUP BY column1, column2, …GROUP BY column1, column2, …

Page 26: 1 Basic SQL Missouri State University Computer Services Short Course

2626

Having ClauseHaving Clause

HAVING search-conditionHAVING search-condition

Each column used in the search must:Each column used in the search must:– Unambiguously identify a grouping column orUnambiguously identify a grouping column or– Be specified with a column functionBe specified with a column function

Page 27: 1 Basic SQL Missouri State University Computer Services Short Course

2727

ExamplesExamples

Example 1: Show all rows and columns of Example 1: Show all rows and columns of the table datacoll.classesthe table datacoll.classes

Example 2: Show the job code, maximum Example 2: Show the job code, maximum salary and minimum salary for each group salary and minimum salary for each group of rows in EMPLOYEE with the same job of rows in EMPLOYEE with the same job code, but only for groups with more than 1 code, but only for groups with more than 1 row and with a maximum salary greater row and with a maximum salary greater than 30000than 30000

Page 28: 1 Basic SQL Missouri State University Computer Services Short Course

2828

ExamplesExamples

Example 1:Example 1:SELECT * FROM DATACOLL.CLASSESSELECT * FROM DATACOLL.CLASSES

Example 2:Example 2:SELECT CURR_POST1, SELECT CURR_POST1,

MAX(ANNUAL_SALARY), MAX(ANNUAL_SALARY), MIN(ANNUAL_SALARY) FROM MIN(ANNUAL_SALARY) FROM DATACOLL.EMPLOYEE DATACOLL.EMPLOYEE

GROUP BY CURR_POST1 GROUP BY CURR_POST1 HAVING COUNT(*) > 1 AND HAVING COUNT(*) > 1 AND

MAX(ANNUAL_SALARY) > 30000MAX(ANNUAL_SALARY) > 30000

Page 29: 1 Basic SQL Missouri State University Computer Services Short Course

2929

How would you use SQL in your How would you use SQL in your job?job?

Page 30: 1 Basic SQL Missouri State University Computer Services Short Course

3030

Column FunctionsColumn Functions

AVGAVG

COUNTCOUNT

MAXMAX

MINMIN

SUMSUM

On all column functions, you can use DISTINCT On all column functions, you can use DISTINCT to remove duplicatesto remove duplicates

On COUNT, DISTINCT also removes null valuesOn COUNT, DISTINCT also removes null values

Page 31: 1 Basic SQL Missouri State University Computer Services Short Course

3131

Scalar FunctionsScalar Functions

There are many available, but SUBSTR is There are many available, but SUBSTR is likely the only one you’ll ever needlikely the only one you’ll ever need

SUBSTR(string,start,length)SUBSTR(string,start,length)– Length may be omitted. If it is, the default is Length may be omitted. If it is, the default is

the length of the string – start + 1the length of the string – start + 1

Page 32: 1 Basic SQL Missouri State University Computer Services Short Course

3232

JoinsJoins

Joins are the combined data from 2 or more Joins are the combined data from 2 or more tablestablesSpecify more than 1 table in the FROM clause, Specify more than 1 table in the FROM clause, separated by a commaseparated by a commaSpecify a search condition for the join in the Specify a search condition for the join in the WHERE clause; otherwise, you get all possible WHERE clause; otherwise, you get all possible combinations of rows for the tables in the FROM combinations of rows for the tables in the FROM clauseclauseIn this case, the number of rows return is the In this case, the number of rows return is the product of the number of rows in each tableproduct of the number of rows in each table

Page 33: 1 Basic SQL Missouri State University Computer Services Short Course

3333

Joins -- Intersections or Joins -- Intersections or DifferencesDifferences

IntersectionsIntersections

DifferenceDifference

Page 34: 1 Basic SQL Missouri State University Computer Services Short Course

3434

Joins - IntersectionJoins - Intersection

Identify the juniors who have a foreign Identify the juniors who have a foreign language major and the classes they are language major and the classes they are taking this falltaking this fall

Page 35: 1 Basic SQL Missouri State University Computer Services Short Course

3535

Joins -Intersection Example Joins -Intersection Example

Select Name, Course_Code, Course_No, Select Name, Course_Code, Course_No, Section_No, Credit_HoursSection_No, Credit_Hours

From datacoll.students S, datacoll.classes CFrom datacoll.students S, datacoll.classes C

Where maj1_curr like ‘FL%’ and Semester = ‘FA’ Where maj1_curr like ‘FL%’ and Semester = ‘FA’ and Year = ‘2005’ and Year = ‘2005’

and S.Soc_Sec = C.Soc_Secand S.Soc_Sec = C.Soc_SecCorrelation namesCorrelation names– Defined in the FROM clauseDefined in the FROM clause– Used to designate table namesUsed to designate table names

Page 36: 1 Basic SQL Missouri State University Computer Services Short Course

3636

JoinsJoins

Example:Example:Select name, stu_class, crs_cd, crs_numSelect name, stu_class, crs_cd, crs_num

from datacoll.students s, datacoll.classes cfrom datacoll.students s, datacoll.classes c

where s.soc_sec = c.soc_secwhere s.soc_sec = c.soc_sec

and curr_stdt = ‘Y’and curr_stdt = ‘Y’

Page 37: 1 Basic SQL Missouri State University Computer Services Short Course

3737

UnionsUnions

Merging results from 1 or more queriesMerging results from 1 or more queries

Each query returns a set of resultsEach query returns a set of results

If specified, these sets are sorted together If specified, these sets are sorted together and any duplicates are removedand any duplicates are removed

Page 38: 1 Basic SQL Missouri State University Computer Services Short Course

3838

Union - ExampleUnion - Example

Select Name, Course_code, Course_no, Select Name, Course_code, Course_no, Section_no, ’FA 2002’Section_no, ’FA 2002’

From datacoll.FA02STDT S, datacoll.FA02CLS CFrom datacoll.FA02STDT S, datacoll.FA02CLS C

Where S.Soc_Sec = C.Soc_Sec and Semester = Where S.Soc_Sec = C.Soc_Sec and Semester = ‘FA’ and Year = ‘2002’ and maj1_curr like ‘FL%’ ‘FA’ and Year = ‘2002’ and maj1_curr like ‘FL%’ and stu_class in (‘JR’, ‘SR’)and stu_class in (‘JR’, ‘SR’)

UnionUnion

Page 39: 1 Basic SQL Missouri State University Computer Services Short Course

3939

Union - Example contUnion - Example cont

Select Name, Course_code, Course_no, Select Name, Course_code, Course_no, Section_no, ‘SP 2003’Section_no, ‘SP 2003’

From datacoll.SP03STDT S, datacoll.SP03CLS CFrom datacoll.SP03STDT S, datacoll.SP03CLS C

Where S. Soc_sec = C.Soc_sec and Semester = Where S. Soc_sec = C.Soc_sec and Semester = ‘SP’ and Year = ‘2003’ and stu_class in (‘JR’, ‘SP’ and Year = ‘2003’ and stu_class in (‘JR’, ‘SR’) and maj1_curr like ‘FL%’ ‘SR’) and maj1_curr like ‘FL%’

Order by 7,1Order by 7,1

Page 40: 1 Basic SQL Missouri State University Computer Services Short Course

4040

Union - Example 2Union - Example 2

List the names of all students in a List the names of all students in a department who are either advised by department who are either advised by advisor E333 or are juniors.advisor E333 or are juniors.

Page 41: 1 Basic SQL Missouri State University Computer Services Short Course

4141

Union and Union AllUnion and Union All

Union All--In the previous example, if Union All--In the previous example, if students were both Juniors and advised by students were both Juniors and advised by E333, they would be on the final report two E333, they would be on the final report two times.times.

Union -- Sorts and removes duplicatesUnion -- Sorts and removes duplicates

Union All -- does not eliminate duplicate Union All -- does not eliminate duplicate rows from the reportrows from the report

Page 42: 1 Basic SQL Missouri State University Computer Services Short Course

4242

Unions - RulesUnions - Rules

Select -- any number of columns can be Select -- any number of columns can be selectedselected

Each Select must produce similar resultsEach Select must produce similar results– same number of columnssame number of columns– by position, same general type, i.e....by position, same general type, i.e....– Char--char--dec Dec--char-char --NOChar--char--dec Dec--char-char --NO– Char--char--dec Char--char--dec --Char--char--dec Char--char--dec --

YesYes

Page 43: 1 Basic SQL Missouri State University Computer Services Short Course

4343

Unions - Rules continuedUnions - Rules continued

You may use any combination of Union You may use any combination of Union and Union Alland Union All

Efficient to use union all on all but the last Efficient to use union all on all but the last UNION statement (Sort only once)UNION statement (Sort only once)

ORDER BY statement must follow all ORDER BY statement must follow all SELECTs and reference only column SELECTs and reference only column positions, not namespositions, not names

Page 44: 1 Basic SQL Missouri State University Computer Services Short Course

4444

Combining Union and Union AllCombining Union and Union All

Query 2

Query 3

Query 4

Union All

Union All

Union

Query 1 Internal

area

Final ReportFinal Report

Sort

Page 45: 1 Basic SQL Missouri State University Computer Services Short Course

4545

UnionsUnions

SELECT stmt UNION (ALL) SELECT stmt SELECT stmt UNION (ALL) SELECT stmt UNION (ALL) …UNION (ALL) …UNION without the ALL option causes duplicate UNION without the ALL option causes duplicate rows to be eliminatedrows to be eliminatedUNION ALL causes all rows from all SELECT UNION ALL causes all rows from all SELECT stmts to be returnedstmts to be returnedSame number of columns must be returned by Same number of columns must be returned by all SELECT stmtsall SELECT stmtsThe corresponding columns in all SELECT stmts The corresponding columns in all SELECT stmts must have the same compatible data typesmust have the same compatible data types

Page 46: 1 Basic SQL Missouri State University Computer Services Short Course

4646

SubselectsSubselects

Queries that are used as part of some Queries that are used as part of some predicatespredicates– ININ– EXISTSEXISTS

Queries that are used in Having clausesQueries that are used in Having clauses

Page 47: 1 Basic SQL Missouri State University Computer Services Short Course

4747

SubselectsSubselectsselect name_reversed, permnt_street, permnt_city, permnt_state, permnt_zipselect name_reversed, permnt_street, permnt_city, permnt_state, permnt_zipfrom datacoll.addresses afrom datacoll.addresses awhere a.soc_sec in (select soc_sec from datacoll.starclswhere a.soc_sec in (select soc_sec from datacoll.starclswhere year = '2005' and semester = 'FA'where year = '2005' and semester = 'FA'and course_code = 'HST' and course_no = '101‘ and grade = 'A')and course_code = 'HST' and course_no = '101‘ and grade = 'A')

select dept_code1, max(annual_salary)select dept_code1, max(annual_salary)from datacoll.empactivefrom datacoll.empactivegroup by dept_code1group by dept_code1having max(annual_salary) > (select avg(annual_salary) from having max(annual_salary) > (select avg(annual_salary) from

datacoll.empactive)datacoll.empactive)

select dept_code1, max(annual_salary) select dept_code1, max(annual_salary) from datacoll.empactive qfrom datacoll.empactive qgroup by dept_code1group by dept_code1having max(annual_salary) < (select avg(annual_salary) from having max(annual_salary) < (select avg(annual_salary) from

datacoll.empactive where not dept_code1 = q.dept_code1)datacoll.empactive where not dept_code1 = q.dept_code1)

Page 48: 1 Basic SQL Missouri State University Computer Services Short Course

4848

EXCELEXCEL

Data -> Import External Data -> New Data -> Import External Data -> New Database QueryDatabase Query

Choose Data Source windowChoose Data Source window– Select PHOENIXSelect PHOENIX

MS Query is invokedMS Query is invoked

When query is complete, close MS Query When query is complete, close MS Query and data will be returned to EXCELand data will be returned to EXCEL

Page 49: 1 Basic SQL Missouri State University Computer Services Short Course

4949

MS QueryMS Query

MS Query is the performs the actual data MS Query is the performs the actual data accessaccess

Queries can be created in SQL, query Queries can be created in SQL, query wizard, or MS Query’s drag and drop wizard, or MS Query’s drag and drop interface.interface.

Page 50: 1 Basic SQL Missouri State University Computer Services Short Course

5050

MS QueryMS Query

It can be used separately from Excel. The It can be used separately from Excel. The program name is MSQRY32.EXE. It can program name is MSQRY32.EXE. It can be found in the C:\Program Files\Microsoft be found in the C:\Program Files\Microsoft Office\OFFICE11 directory. Your OFFICE Office\OFFICE11 directory. Your OFFICE directory may have a different number directory may have a different number associated with it depending upon the associated with it depending upon the OFFICE release.OFFICE release.You may want to create a shortcut for it on You may want to create a shortcut for it on your desktop.your desktop.

Page 51: 1 Basic SQL Missouri State University Computer Services Short Course

5151

Example 1Example 1

Find all current students in a specific Find all current students in a specific department whose age is over 30.department whose age is over 30.

Page 52: 1 Basic SQL Missouri State University Computer Services Short Course

5252

Example 1- Query WizardExample 1- Query Wizard

Start ExcelStart Excel

Data -> Import External Data -> New Data -> Import External Data -> New Database QueryDatabase Query

Select Phoenix as the data sourceSelect Phoenix as the data source

Check the box “Use Query Wizard to Check the box “Use Query Wizard to create/edit queries”create/edit queries”

Sign on to Phoenix using your Phoenix id Sign on to Phoenix using your Phoenix id and passwordand password

Page 53: 1 Basic SQL Missouri State University Computer Services Short Course

5353

Example 1- Query WizardExample 1- Query Wizard

Select the table you want to use from the Select the table you want to use from the list presented. The list consists of all the list presented. The list consists of all the views on Phoenix regardless of your views on Phoenix regardless of your access to them.access to them.When the add tables window opens, for When the add tables window opens, for the first time use only, click the options the first time use only, click the options button and select only views from the button and select only views from the options window. This limits the list to only options window. This limits the list to only views.views.

Page 54: 1 Basic SQL Missouri State University Computer Services Short Course

5454

Example 1- Query WizardExample 1- Query Wizard

Scroll the list to find the view you want to Scroll the list to find the view you want to use. For this example, we’re going to use use. For this example, we’re going to use STDT.STDT.

Click the plus sign to see the columns in Click the plus sign to see the columns in the view.the view.

Select the columns you want and click the Select the columns you want and click the “>” button to add the column to the right “>” button to add the column to the right side.side.

Page 55: 1 Basic SQL Missouri State University Computer Services Short Course

5555

Example 1- Query WizardExample 1- Query Wizard

Use soc_sec, name, birth_date, and Use soc_sec, name, birth_date, and maj1_deptmaj1_deptOn the next window, select MAJ1_DEPT, On the next window, select MAJ1_DEPT, equals, and then the dept. Note that using equals, and then the dept. Note that using the pull down arrow gives you all values the pull down arrow gives you all values for that column in the selected table.for that column in the selected table.We also want to select BIRTH_DATE, less We also want to select BIRTH_DATE, less than or equal to, and 30 years from than or equal to, and 30 years from today’s date. today’s date.

Page 56: 1 Basic SQL Missouri State University Computer Services Short Course

5656

Example 1- Query WizardExample 1- Query Wizard

Clicking the next button allows you to sort Clicking the next button allows you to sort the data.the data.

Clicking next again brings you to the finish Clicking next again brings you to the finish screen where you can return the data to screen where you can return the data to Excel, view the data in Query and Excel, view the data in Query and optionally, save the query to use it again.optionally, save the query to use it again.

This is how you would do it using the This is how you would do it using the Query Wizard.Query Wizard.

Page 57: 1 Basic SQL Missouri State University Computer Services Short Course

5757

Example 1Example 1

Find all current students in a specific Find all current students in a specific department having a GPA over 3.0 whose department having a GPA over 3.0 whose age is over 30.age is over 30.

Page 58: 1 Basic SQL Missouri State University Computer Services Short Course

5858

Example 1 Drag and DropExample 1 Drag and Drop

Click on sheet 2Click on sheet 2

Data -> Import External Data -> New Data -> Import External Data -> New Database QueryDatabase Query

Select Phoenix as the data sourceSelect Phoenix as the data source

Uncheck the box “Use Query Wizard to Uncheck the box “Use Query Wizard to create/edit queries”create/edit queries”

Sign on to Phoenix using your Phoenix id Sign on to Phoenix using your Phoenix id and passwordand password

Page 59: 1 Basic SQL Missouri State University Computer Services Short Course

5959

Example 1 Drag and DropExample 1 Drag and Drop

A list of tables will appear. All tables are A list of tables will appear. All tables are listed whether or not you have access. listed whether or not you have access. Clicking the options button allows you to Clicking the options button allows you to only use views (recommended).only use views (recommended).

We want the STDT view. Select it and We want the STDT view. Select it and click Add and then Close since we only click Add and then Close since we only need 1 table.need 1 table.

View -> Criteria opens up the criteria view.View -> Criteria opens up the criteria view.

Page 60: 1 Basic SQL Missouri State University Computer Services Short Course

6060

Example 1 Drag and DropExample 1 Drag and Drop

Drag MAJ1_DEPT from the column listing Drag MAJ1_DEPT from the column listing to the first criteria entry. Alternatively, click to the first criteria entry. Alternatively, click near the right side of the entry and the near the right side of the entry and the column list will appear allowing you so column list will appear allowing you so select the column.select the column.Next we want BIRTH_DATE. Next we want BIRTH_DATE. Double click the value entry and a new Double click the value entry and a new window opens to choose the operator. We window opens to choose the operator. We want “less than or equal to”.want “less than or equal to”.

Page 61: 1 Basic SQL Missouri State University Computer Services Short Course

6161

Example 1 Drag and DropExample 1 Drag and Drop

There is a values button which lists all distinct There is a values button which lists all distinct values for that column. We want to use values for that column. We want to use 04/18/1976. Then click OK.04/18/1976. Then click OK.

The columns to display can also be selected by The columns to display can also be selected by clicking the column heading and using the drop clicking the column heading and using the drop down list.down list.

Each column is filled in as you select it which is Each column is filled in as you select it which is why you should set the criteria first. This can be why you should set the criteria first. This can be turned off by clicking the auto-query button.turned off by clicking the auto-query button.

Page 62: 1 Basic SQL Missouri State University Computer Services Short Course

6262

Example 1 Drag and DropExample 1 Drag and Drop

When the results are complete, close MS When the results are complete, close MS Query to return the data to Excel.Query to return the data to Excel.

Page 63: 1 Basic SQL Missouri State University Computer Services Short Course

6363

Example 1 SQLExample 1 SQL

Click on sheet 3Click on sheet 3

Data -> Import External Data -> New Data -> Import External Data -> New Database QueryDatabase Query

Select Phoenix as the data sourceSelect Phoenix as the data source

Uncheck the box “Use Query Wizard to Uncheck the box “Use Query Wizard to create/edit queries”create/edit queries”

Sign on to Phoenix using your Phoenix id Sign on to Phoenix using your Phoenix id and passwordand password

Page 64: 1 Basic SQL Missouri State University Computer Services Short Course

6464

Example 1 SQLExample 1 SQL

When the Add tables window opens up, When the Add tables window opens up, click Close.click Close.Click the SQL button and a window opens Click the SQL button and a window opens where you can enter the SQL.where you can enter the SQL.select soc_sec, name, birth_date, select soc_sec, name, birth_date, maj1_deptmaj1_deptfrom stdtfrom stdtwhere maj1_dept = 'HI'where maj1_dept = 'HI'and birth_date <= '04/18/1976'and birth_date <= '04/18/1976'

Page 65: 1 Basic SQL Missouri State University Computer Services Short Course

6565

Example 1 SQLExample 1 SQL

Click OK.Click OK.

A window appears saying “SQL Query A window appears saying “SQL Query can’t be represented graphically. can’t be represented graphically. Continue anyway?” Click OK.Continue anyway?” Click OK.

The results appear.The results appear.

Close MS Query to return the results to Close MS Query to return the results to Excel.Excel.

Page 66: 1 Basic SQL Missouri State University Computer Services Short Course

6666

ExcelExcel

You’ve seen 3 different ways to use MS You’ve seen 3 different ways to use MS Query to get the data.Query to get the data.

Using the method of your choice, get data Using the method of your choice, get data for the following examplefor the following example

Find all seniors who are current students Find all seniors who are current students in a specific department whose overall in a specific department whose overall GPA is 3.0 or greater.GPA is 3.0 or greater.

Page 67: 1 Basic SQL Missouri State University Computer Services Short Course

6767

Example 2Example 2

Find the name, class, permanent city and Find the name, class, permanent city and state of all current students within a state of all current students within a specific department who have a GPA specific department who have a GPA greater than or equal to 3.0greater than or equal to 3.0

Page 68: 1 Basic SQL Missouri State University Computer Services Short Course

6868

Example 2Example 2

Add STDTAdd STDT

Add ADDRESSESAdd ADDRESSES

Drag SOC_SEC from one to the otherDrag SOC_SEC from one to the other

Proceed with the other stepsProceed with the other steps

Page 69: 1 Basic SQL Missouri State University Computer Services Short Course

6969

Grouping in MS QueryGrouping in MS Query

To create groups, view -> Query To create groups, view -> Query properties and check Group Records.properties and check Group Records.

Example: Find a count of all current Example: Find a count of all current students in all departments in a specific students in all departments in a specific college having a GPA over 3.0 college having a GPA over 3.0

Page 70: 1 Basic SQL Missouri State University Computer Services Short Course

7070

Grouping ExampleGrouping Example

View -> CriteriaView -> CriteriaSelect the field coll_codeSelect the field coll_codeEnter the college codeEnter the college codeSelect the field curr_stdtSelect the field curr_stdtEnter the value YEnter the value YSelect the field comb_ug_gpaSelect the field comb_ug_gpaDouble click the value fieldDouble click the value fieldSelect “is greater than or equal to” from the operator pull-Select “is greater than or equal to” from the operator pull-downdownEnter 3.0 in the value fieldEnter 3.0 in the value fieldClick OKClick OK

Page 71: 1 Basic SQL Missouri State University Computer Services Short Course

7171

Grouping exampleGrouping example

Drag coll_code to first field in data paneDrag coll_code to first field in data pane

Drag maj1_dept to second field in data Drag maj1_dept to second field in data panepane

Records -> Add columnRecords -> Add column

Total pull-down – select count, click addTotal pull-down – select count, click add

Page 72: 1 Basic SQL Missouri State University Computer Services Short Course

7272

Grouping ExampleGrouping Example

Click SQL buttonClick SQL button

After the From clause, enter the where After the From clause, enter the where clauseclause

Click OKClick OK

Page 73: 1 Basic SQL Missouri State University Computer Services Short Course

7373

Grouping ExampleGrouping Example

SELECT STDT.COLL_CODE, STDT.MAJ1_DEPT, SELECT STDT.COLL_CODE, STDT.MAJ1_DEPT, Count(*)Count(*)

FROM DATACOLL.STDT STDTFROM DATACOLL.STDT STDTWHERE (STDT.COLL_CODE='HP') AND WHERE (STDT.COLL_CODE='HP') AND

(STDT.COMB_UG_GPA>=3.0) AND (STDT.COMB_UG_GPA>=3.0) AND (STDT.CURR_STDT='Y')(STDT.CURR_STDT='Y')

GROUP BY STDT.COLL_CODE, STDT.MAJ1_DEPTGROUP BY STDT.COLL_CODE, STDT.MAJ1_DEPTORDER BY STDT.COLL_CODE, STDT.MAJ1_DEPTORDER BY STDT.COLL_CODE, STDT.MAJ1_DEPT

Page 74: 1 Basic SQL Missouri State University Computer Services Short Course

7474

iSeries ODBC DriveriSeries ODBC Driver

This is a requirement for using Excel to This is a requirement for using Excel to query Phoenix dataquery Phoenix data

You’ll need to contact Computer Services You’ll need to contact Computer Services – User Support to have this installed on – User Support to have this installed on your machineyour machine– They will install and configure the softwareThey will install and configure the software

Page 75: 1 Basic SQL Missouri State University Computer Services Short Course

7575

QuestionsQuestions