140 likes | 319 Views
Writing Advanced SQL Queries BKF05. Liz Lucchese. Agenda. SQL revealed What is it and why should I care? Advanced query interface So, how do I use this thing? Recipes for success Real world examples to learn syntax. SQL Revealed. What is it? Structured Query Language
E N D
Writing Advanced SQL QueriesBKF05 Liz Lucchese
Agenda • SQL revealed • What is it and why should I care? • Advanced query interface • So, how do I use this thing? • Recipes for success • Real world examples to learn syntax
SQL Revealed What is it? • Structured Query Language • A standardized way to query a database • Why should I care? • It’s used in advanced queries. • It’s easy to learn. • It’s fun!
Anatomy of a SELECT Statement SELECT * FROM STUDENT WHERE STD_YOG = 2007 ORDER BY STD_NAME_VIEW
Advanced Query Interface SELECT * FROM STUDENT WHERE STD_YOG = 2007
Multiple Criteria SELECT * FROM STUDENT WHERE STD_NAME_VIEW LIKE‘A%’ AND STD_GRADE_LEVEL IN (‘01’,‘02’,‘03’)
Parentheses SELECT * FROM STUDENT WHERE (STD_YOG = 2007 AND STD_GRADE_LEVEL <> ‘12’) OR (STD_YOG = 2008 AND STD_GRADE_LEVEL <> ‘11’) OR (STD_YOG = 2009 AND STD_GRADE_LEVEL <> ‘10’) ...
Multiple Tables SELECT * FROM STUDENT INNER JOIN PERSON ON PSN_OID = STD_PSN_OID WHERE PSN_DOB > ‘1999-12-31’ AND PSN_DOB <= ‘2000-12-31’
Nested Query (version 1) SELECT * FROM STUDENT WHERE STD_OID NOT IN (SELECT CTJ_STD_OID FROM STUDENT_CONTACT)
Nested Query (version 2) SELECT * FROM STUDENT WHERE NOT EXISTS (SELECT CTJ_STD_OID FROM STUDENT_CONTACT WHERE STD_OID = CTJ_STD_OID)
Multiple Nested Queries SELECT * FROM STUDENT WHERE STD_OID IN (SELECT REQ_STD_OID FROM STUDENT_COURSE_REQUEST INNER JOIN COURSE_SCHOOL ON CSK_OID = REQ_CSK_OID INNER JOIN DISTRICT_SCHOOL_YEAR_CONTEXT ON CTX_OID = REQ_CTX_OID WHERE CSK_COURSE_NUMBER IN (‘101’,‘102’,‘103’) AND CTX_SCHOOL_YEAR = 2008) AND STD_OID NOT IN (SELECT REQ_STD_OID FROM STUDENT_COURSE_REQUEST INNER JOIN COURSE_SCHOOL ON CSK_OID = REQ_CSK_OID INNER JOIN DISTRICT_SCHOOL_YEAR_CONTEXT ON CTX_OID = REQ_CTX_OID WHERE CSK_COURSE_NUMBER = ‘202’ AND CTX_SCHOOL_YEAR = 2008)
Aggregate Query SELECT * FROM STUDENT WHERE STD_OID IN (SELECT ATT_STD_OID FROM STUDENT_ATTENDANCE WHERE ATT_DATE > ‘2006-09-01’ AND ATT_DATE < ‘2007-06-30’ AND ATT_ABSENT_IND = ‘1’ GROUP BY ATT_STD_OID HAVING COUNT(*) > 5)
Extras • W3Schools SQL Tutorialhttp://www.w3schools.com/sql/default.asp • SQLzoo.nethttp://sqlzoo.net
Thank you. elucchese@x2dev.com