1.25k likes | 1.4k Views
Basic SQL. SMSU Computer Services Short Course. Contact Information. Greg Snider – MIS Database Analyst Ext. 6-4397 Email – SGS345B Don’t hesitate to email or call if you have any questions after you start using QM and SQL. Confidentiality.
E N D
Basic SQL SMSU Computer Services Short Course
Contact Information • Greg Snider – MIS Database Analyst • Ext. 6-4397 • Email – SGS345B Don’t hesitate to email or call if you have any questions after you start using QM and SQL.
Confidentiality • “The confidentiality of student information is protected by the Family Education Rights and Privacy Act (FERPA). Do not release confidential information obtained through QM reports to anyone except SMSU faculty or staff who have a need for the information and be sure to properly dispose of reports when you no longer have need for them.”
Contents • Concepts • What is SQL? • Terminology • SQL Language • Its parts • SELECT Statement • Query Manager
What is SQL? • S(trucured) Q(uery) L(anguage) • A standard language for accessing data • Designed to be portable • Used by most database vendors • It’s how you access data stored in a …
Terminology • Table • A set of rows with columns containing data • Think of a table as a large spreadsheet
Terminology Hot and Cold Running Tables • Cold or Query Table is refreshed nightly or as predetermined. • Hot or Live Table can be updated as you write and run your queries. • At this point, all the tables you use in your queries are cold tables.
Terminology • View • Another way of accessing the data in a table • May or may not contain all the columns in a table • Can be a join of two or more tables • Transparent to the user
SQL Language • Language elements • Statements • Functions • Joins • Unions • Subselects
Language Elements • Data types • Constants • Expressions • Predicates
Data Types • Character strings • Datetime • Date • Time • Numeric • Integer • Decimal • Numeric
Character Strings • Fixed length • 1 – 254 positions
Date • Date • Format MM/DD/YYYY • 10 positions • When using a date, it must be enclosed in single quotes, ’09/16/2004’
Numeric • Integer • Small • 32768 - +32767 • Large • -2147483648 - +2147483647 • Decimal • 15 digits max • (Precision, Scale) • Precision – how many digits total • Scale – how many digits to the right of the decimal point • Numeric • 31 digits max
Constants • Integer constants • 456, -789 • Decimal constants • 978.34, 9584.2746 • String (character) constants • ‘ABCE’, ‘Computers for Learning’
Expressions • Operators • || or CONCAT, /, *, +, - • || only for strings • Standard rules apply for arithmetic operations
Date Arithmetic • Admit_date + 2 months + 2 days is valid • Grad_date – Admit_date is valid
Predicates • =, <>, <, >, <=, >= • Between: expression (NOT) BETWEEN 123 and 999 • Null: expression IS (NOT) NULL • Like: expression (NOT) LIKE pattern • Pattern % represents 0 or more characters _ represents only 1 character • Exists discussed when we talk about subselects • In expression IN (value1, value2, value3, …) • AND and OR may be used
Statements • Select
Select • Select clause • From clause • Where clause • Group by clause • Having clause • Order by clause
Select Clause • SELECT columns, expressions • Tells what you want to see
From Clause • FROM datacoll.view-name • Datacoll is the owner of all our views
Where Clause • WHERE search-condition
Group By Clause • GROUP BY column1, column2, …
Having Clause • HAVING search-condition • Each column used in the search must: • Unambiguously identify a grouping column or • Be specified with a column function
Examples • Example 1: Show all rows and columns of the table datacoll.classes • Example 2: Show the job code, maximum salary and minimum salary for each group of rows in EMP with the same job code, but only for groups with more than 1 row and with a maximum salary greater than 50000
Examples • Example 1: • SELECT * FROM DATACOLL.CLASSES • Example 2: • SELECT JOB, MAX(SALARY), MIN(SALARY) FROM EMP GROUP BY JOB HAVING COUNT(*) > 1 AND MAX(SALARY) > 500000
Column Functions • AVG • COUNT • MAX • MIN • SUM • On all column functions, you can use DISTINCT to remove duplicates • On COUNT, DISTINCT also removes null values
Scalar Functions 1 • CHAR(expression) or CHAR(expression,USA) • The first form returns the character representation of a number • The second returns the character represention of a date or time • DATE(expression) • If the expression is a number <= 3652059, the result is the date that is n-1 days after 01/01/0001 • If the expression is a character string with length 7 in yyyyddd format, the result is the date represented by the string • If the expression is any other character string, it must be in valid date format (’01/01/2005’)
Scalar Functions 2 • DAY(expression) • if the expression is a date, the result is the day part of the value • DAYS(expression) • The expression must be a date or a valid string of a date • The result is 1 more that the number of days from 01/01/0001 to the expression
Scalar Functions 3 • DECIMAL(expression, integer, integer) • 2nd and 3rd arguments are for precision and scale • If 3rd is omitted, default is 0 • If 2nd is omitted, precision is 15
Scalar Functions 4 • HOUR(expression) • INTEGER(expression) • MINUTE(expression) • MONTH(expression) • SECOND(expression
Scalar Functions 5 • SUBSTR(string,start,length) • Lentgh may be omitted. If it is, the default is the length of the string – start + 1 • TIME(expression)
Joins 1 • Joins are the combined data from 2 or more tables • Specify more than 1 table in the FROM clause, seperated by a comma • Specify a search condition for the join in the WHERE clause; otherwise, you get all possible combinations of rows for the tables in the FROM clause • In this case, the number of rows return is the product of the number of rows in each table
Joins 2 -- Intersections or Differences • Intersections • Difference
Joins 3 - Intersection • Identify the juniors who have a foreign language major and the classes they are taking this fall Classes Table Classes Student Table
Joins 4 -Intersection Example • Select Name, Course_Code, Course_No, Section_No, Credit_Hours • From Tstudent S, Tclasses C • Where First_major_curr like ‘FL%’ • and Sem = ‘4’ • and Year = ‘93’ • and S.Soc_Sec = C.Soc_Sec • Correlation names • Defined in the FROM clause • Used to designate table names
Joins 4 • Example: • Select name, stu_class, crs_cd, crs_num from datacoll.students s, datacoll.classes c where s.soc_sec = c.soc_sec
Unions 1 • Merging results from 2 or more queries • Identify Sr and JR in FL Student Table Classes Table
Union 2 - Example • Select Name, Adviser_Curr, Course_code, Comb_Grade_Pts, Course_no, Section_no, ’1’ • From Tstudent S, Tclasses C • Where S.Soc_Sec = C.Soc_Sec and Sem = ‘4’ and Year = ‘93’ and First_major_curr like ‘FL%’ and class_curr = ‘SR’ • Union
Union 3 - Example cont • Select Name, Adviser_curr, Course_code, Comb_Grade_Pts, Course_no, Section_no, ‘2’ • From Tstudent S, Tclasses C • Where S. Soc_sec = C.Soc_sec and Sem = ‘4’ and Year = ‘93’ and Class_curr = ‘JR’ and First_major_curr like ‘FL%’ • Order by 7,1
Union 4 - Example 2 • List the names of all students who are either advised by advisor E333 or are juniors. Advised by E333 Final Report Juniors
Union and Union All - 5 • Union All--In the previous example, if students were both Juniors and advised by E333, they would be on the final report two times. • Union -- Sorts and removes duplicates • Union All -- does not eliminate duplicate rows from the report
Unions 6 - Rules • Select -- any number of columns can be selected • Each Select must produce similar results • same number of columns • by position, same general type, ie... • Char--char--dec Dec--char-char --NO • Char--char--dec Char--char--dec --Yes
Unions 6 - Rules continued • You may use any combination of Union and Union All • Efficient to use union all on all but the last UNION statement (Sort only once) • ORDER BY statement must follow all SELECTs and reference only column positions, not names
Combining Union and Union All S o r t I n t e r n a l a r e a Final Report Query 1 Final Report Union All Query 2 Union All Query 3 Union Query 4
Unions 1 • SELECT stmt UNION (ALL) SELECT stmt UNION (ALL) … • UNION without the ALL option causes duplicate rows to be eliminated • UNION ALL causes all rows from all SELECT stmts to be returned • Same number of columns must be returned by all SELECT stmts • The corresponding columns in all SELECT stmts must have the same compatable data types
Subselects select empno, actno, emstdate, emendate from empprojact where empno in (select empno from emp where workdept = ‘E11’ select workdept, max(salary) from emp group by workdept having max(salary) > (select avg(salary) from emp select workdept, max(salary) grom emp q group by workdept having max(salary) < (select avg(salary) from emp where not workdept = q.workdept)
Lunch Break • Class resumes at 1:00