Fun with SQL

Embed Size (px)

DESCRIPTION

Developers deal with SQL databases daily, yet very few speak SQL fluently. Even when an ORM hides most of SQL's details, SQL fluency will allow for increased performance and better troubleshooting capabilities. Given at UTOSC 2009

Text of Fun with SQL

  • 1. Fun With SQLJoshua Tolley End PointCorporation Why and Why NotJoins CROSS JOINFun With SQL INNER JOIN OUTER JOIN NATURAL JOIN Self JoinsOther Useful Joshua Tolley Operations Subqueries End Point Corporation Set Operations Common OperationsAdvanced Operations Common Table October 5, 2009 Expressions Window FunctionsReal, Live Queries Something Simple Something FunKey Points

2. Fun With SQLJoshua Tolley End PointCorporation Why and Why NotJoins CROSS JOIN INNER JOIN OUTER JOIN NATURAL JOIN The degree of normality in a database is inversely Self Joinsproportional to that of its DBA. - Anon, twitter Other Useful Operations Subqueries Set Operations Common OperationsAdvanced Operations Common Table Expressions Window FunctionsReal, Live Queries Something Simple Something FunKey Points 3. Fun With SQL Why Not Do Stu in SQL Joshua Tolley End PointDatabases are harder to replicate, if you really need toCorporationscale out Why and Why NotOften, one complex SQL query is more ecient than Joinsseveral simple onesCROSS JOINSometimes, indeed, its useful to reduce the load on the INNER JOIN OUTER JOINdatabase by moving logic into the application. BeNATURAL JOINcareful doing this Self JoinsOther Useful c.f. Premature Optimization Operations SubqueriesMore complex queries are harder to write and debug Set Operations Common OperationsTrue. But so is more complex programming. Advanced OperationsMore complex queries are harder for the next guy toCommon Table Expressionsmaintain Window Functions Also, good DBAs are often more expensive than good Real, Live Queries Something SimpleprogrammersSomething Fun These are both true. But complex programming is also Key Points hard for the next guy to maintainOf all the reasons not to write uent SQL, this isprobably the most widely applicable 4. Fun With SQL Why do stu in SQL?Joshua TolleyEnd Point CorporationWhy and Why Not The database is more ecient than your application forJoins processing big chunks of dataCROSS JOININNER JOIN ...especially if your code is in an interpreted language OUTER JOINNATURAL JOIN The database is better tested than your applicationSelf JoinsApplications trying to do what SQL should be doing Other UsefulOperations often get big and complex quicklySubqueriesSet Operations ...and also buggy quicklyCommon OperationsThats what the database is there forAdvancedOperations SQL is designed to express relations and conditions on Common TableExpressionsWindow Functions them. Your applications language isnt.Real, Live Queries A better understanding of SQL allows you to writeSomething SimpleSomething Funqueries that perform betterKey Points 5. Fun With SQL Why do stu in SQL? Joshua Tolley End PointCorporation Why and Why NotJoins CROSS JOIN INNER JOIN OUTER JOIN NATURAL JOIN Self Joins In short, the database exists to manage data, and yourOther Useful Operations application exists to handle business logic. Write software Subqueries accordingly.Set Operations Common OperationsAdvanced Operations Common Table Expressions Window FunctionsReal, Live Queries Something Simple Something FunKey Points 6. Fun With SQLJoshua Tolley End PointCorporation Why and Why NotJoins CROSS JOIN INNER JOIN OUTER JOIN NATURAL JOIN Self Joins So lets get started... Other Useful Operations Subqueries Set Operations Common OperationsAdvanced Operations Common Table Expressions Window FunctionsReal, Live Queries Something Simple Something FunKey Points 7. Fun With SQL Tables well useJoshua TolleyEnd Point CorporationWhy and Why Not JoinsCROSS JOIN# SELECT * FROM a; # SELECT * FROM b; INNER JOINOUTER JOINNATURAL JOIN id | value id | valueSelf Joins ----+------- ----+------- Other UsefulOperations1 | a1 5 | b5 SubqueriesSet Operations2 | a2 4 | b4 Common Operations 3 | a3 3 | b3 AdvancedOperations4 | a4 6 | b6 Common TableExpressions(4 rows) (4 rows) Window Functions Real, Live QueriesSomething SimpleSomething Fun Key Points 8. Fun With SQL JOINsJoshua TolleyEnd Point CorporationWhy and Why Not JoinsCROSS JOININNER JOINOUTER JOINNATURAL JOINIf you want data from multiple tables, you probably Self Joins Other Usefulwant a join Operations ...but see also Subqueries, later on SubqueriesSet OperationsCommon OperationsThere are several dierent kinds of joins AdvancedOperationsCommon TableExpressionsWindow Functions Real, Live QueriesSomething SimpleSomething Fun Key Points 9. Fun With SQL JOINsJoshua TolleyEnd Point CorporationWhy and Why Not JoinsCROSS JOIN INNER JOIN [alias1] OUTER JOIN[ [ [NATURAL] [ [FULL | RIGHT | LEFT] [OUTER] | NATURAL JOIN Self JoinsINNER] ] | CROSS ] JOIN Other Useful Operations [alias2] Subqueries Set Operations [USING (...) |Common OperationsON (Advanced Operations [,...] ) ]Common Table ExpressionsWindow Functions Real, Live QueriesSomething SimpleSomething Fun Key Points 10. Fun With SQL CROSS JOINJoshua TolleyEnd Point CorporationWhy and Why Not JoinsSELECT FROM table1 JOIN table2CROSS JOININNER JOINWith no explicit join type and no join qualiers (an ON OUTER JOINNATURAL JOINclause, WHERE clause involving both relations, etc.)Self Joins this is a CROSS JOINOther UsefulOperationsEquivalent to SubqueriesSet OperationsCommon OperationsSELECT FROM table1, table2AdvancedSELECT FROM table1 CROSS JOIN table2OperationsCommon TableCartesian product of the two relationsExpressionsWindow FunctionsCombines every row of table1 with every row of table2 Real, Live QueriesMakes LOTS of rows, and can thus be very slow Something SimpleSomething Fun Key Points 11. Fun With SQL CROSS JOIN Joshua Tolley End PointCorporation # SELECT * FROM a, b; Why and Why Not id | value | id | valueJoins CROSS JOIN ----+-------+----+------- INNER JOIN OUTER JOIN 1 | a1| 5 | b5NATURAL JOIN Self Joins 1 | a1| 4 | b4Other Useful Operations Subqueries 3 | a3| 3 | b3Set Operations Common Operations 3 | a3| 6 | b6Advanced Operations 4 | a4| 5 | b5Common Table Expressions 4 | a4| 4 | b4Window Functions4 | a4| 3 | b3Real, Live Queries Something Simple 4 | a4| 6 | b6Something Fun(16 rows) Key Points 12. Fun With SQL INNER JOIN Joshua Tolley End PointCorporation Why and Why NotJoins CROSS JOIN INNER JOIN OUTER JOIN NATURAL JOINSELECT FROM table1 INNER JOIN table2 ON Self JoinsOther Useful(table1.eld = table2.eld ...)Operations SubqueriesOnly returns rows satisfying the ON conditionSet Operations Common OperationsEquivalent to a CROSS JOIN with a WHERE clause Advanced Operations Common Table Expressions Window FunctionsReal, Live Queries Something Simple Something FunKey Points 13. Fun With SQL INNER JOINJoshua TolleyEnd Point CorporationWhy and Why Not JoinsCROSS JOININNER JOINOUTER JOIN # SELECT * FROM a INNER JOIN b USING (id); NATURAL JOINSelf Joinsid | value | valueOther Useful ----+-------+------- OperationsSubqueries 3 | a3| b3 Set OperationsCommon Operations 4 | a4| b4Advanced (2 rows) OperationsCommon TableExpressionsWindow Functions Real, Live QueriesSomething SimpleSomething Fun Key Points 14. Fun With SQL OUTER JOINJoshua TolleyEnd Point CorporationWhy and Why Not JoinsReturn all rows from one or both relationsCROSS JOININNER JOINOUTER JOINLEFT: Return all rows from the relation on the left NATURAL JOINSelf JoinsRIGHT: Return all rows from the relation on the right Other UsefulOperationsFULL: Return all rows from both relations SubqueriesSet OperationsReturns nulls for values from one relation when itCommon Operations Advancedcontains to match with the other relation OperationsCommon TableThe OUTER keyword is redundantExpressionsWindow Functions Requires ON or USING clause Real, Live QueriesSomething SimpleSomething Fun Key Points 15. Fun With SQL LEFT JOIN Joshua Tolley End PointCorporation Why and Why NotJoins CROSS JOIN # SELECT * FROM a LEFT JOIN b USING (id); INNER JOIN OUTER JOINid | value | value NATURAL JOIN Self Joins ----+-------+-------Other Useful 1 | a1| Operations Subqueries 2 | a2| Set Operations Common Operations 3 | a3| b3Advanced Operations 4 | a4| b4Common Table Expressions (4 rows)Window FunctionsReal, Live Queries Something Simple Something FunKey Points 16. Fun With SQL RIGHT JOINJoshua TolleyEnd Point CorporationWhy and Why Not JoinsCROSS JOIN # SELECT * FROM a RIGHT JOIN b USING (id); INNER JOINOUTER JOINid | value | valueNATURAL JOINSelf Joins ----+-------+------- Other Useful 3 | a3| b3 OperationsSubqueries 4 | a4| b4 Set OperationsCommon Operations 5 | | b5 AdvancedOperations 6 | | b6 Common TableExpressions (4 rows) Window Functions Real, Live QueriesSomething SimpleSomething Fun Key Points 17. Fun With SQL FULL JOIN Joshua Tolley End PointCorporation Why and Why NotJoins # select * from a full join b using (id); CROSS JOINid | value | value INNER JOIN OUTER JOIN ----+-------+-------NATURAL JOIN Self Joins 1 | a1| Other Useful Operations 2 | a2| Subqueries Set Operations 3 | a3| b3Common Operations4 | a4| b4Advanced Operations 5 | | b5Common Table Expressions 6 | | b6Window Functions(6 rows)Real, Live Queries Something Simple Something FunKey Points 18. Fun With SQL ApplicationsJoshua TolleyEnd Point CorporationWhy and Why NotFind rows with no match in table b:JoinsCROSS JOININNER JOINOUTER JOIN # SELECT * FROM a LEFT JOIN b USING (id) NATURAL JOINSelf Joins WHERE b.value IS NULL; Other Usefulid | value | valueOperationsSubqueries ----+-------+------- Set OperationsCommon Operations 1 | a1|AdvancedOperations 2 | a2|Common TableExpressions (2 rows) Window Functions Real, Live QueriesSomething SimpleSomething Fun Key Points 19. Fun With SQL NATURAL JOIN Joshua Tolley End PointCorporation Why and Why NotJoins CROSS JOIN INNER JOIN OUTER JOIN NATURAL JOIN Self JoinsOther UsefulNATURAL is syntactic sugar to match all columns with Operationsthe same nameSubqueries Set Operations Common OperationsAdvanced Operations Common Table Expressions Window FunctionsReal, Live Queries Something Simple Something FunKey Points 20. Fun With SQL NATURAL JOINJoshua TolleyEnd Point Corporation # SELECT