Add content to SQL Roadmap (#6873)

* complete sql content

* add links to topics

---------

Co-authored-by: Kamran Ahmed <kamranahmed.se@gmail.com>
pull/6972/head
dsh 2 months ago committed by GitHub
parent f96201cbbd
commit 1859e94184
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 3
      src/data/roadmaps/sql/content/ceiling@BAqJQvcguhIhzyII5LRH6.md
  2. 3
      src/data/roadmaps/sql/content/check@Q0h9Wfnl_W9ThOkv7Q17A.md
  3. 1
      src/data/roadmaps/sql/content/common-table-expressions@tedQynR0xicVKhuR1oahw.md
  4. 1
      src/data/roadmaps/sql/content/concat@5inpEqafeVCfqsURHzQQg.md
  5. 3
      src/data/roadmaps/sql/content/correlated-subqueries@JZqS3Xapw6mfSPVgFW7av.md
  6. 3
      src/data/roadmaps/sql/content/count@9aHYrOQDkA84tlxcVK5aD.md
  7. 3
      src/data/roadmaps/sql/content/create-table@epEpBxRosLhuAuKwp823r.md
  8. 3
      src/data/roadmaps/sql/content/cross-join@7ow6tiSSCnTpv_GYQU017.md
  9. 3
      src/data/roadmaps/sql/content/data-constraints@qBios3sZVhcJMpXmj9f7B.md
  10. 3
      src/data/roadmaps/sql/content/data-definition-language-ddl@xPOeXK1EPBNG56vgfG-VV.md
  11. 3
      src/data/roadmaps/sql/content/data-integrity-constraints@mBQ3Z8GlFcpIena3IB7D_.md
  12. 3
      src/data/roadmaps/sql/content/data-types@tBzMDfCMh6MIagNaxCzin.md
  13. 3
      src/data/roadmaps/sql/content/date@Ivqo2wa-_NhGU3vGd0pUI.md
  14. 3
      src/data/roadmaps/sql/content/dateadd@1E1WdWOyqxbbdiIbw26dZ.md
  15. 3
      src/data/roadmaps/sql/content/datepart@BJ4fQvagTO0B5UtXblyx8.md
  16. 8
      src/data/roadmaps/sql/content/delete@ddtVaA4Ls6qRj-7OtTSIH.md
  17. 3
      src/data/roadmaps/sql/content/dense_rank@QM0ltgPu8lLLYc2MsTLj-.md
  18. 1
      src/data/roadmaps/sql/content/drop-table@YzJ6QmY2arMfRzMAPaI0T.md
  19. 3
      src/data/roadmaps/sql/content/dropping-views@MIOuWWcCjLAmgzog2DBC3.md
  20. 3
      src/data/roadmaps/sql/content/dynamic-sql@z5Sf0VU14ZCQ80kL1qOqc.md
  21. 3
      src/data/roadmaps/sql/content/floor@o2SH4iQn1Ap2yDZ7cVYLO.md
  22. 1
      src/data/roadmaps/sql/content/foreign-key@DHz6sRLYhFeCbAcNJS8hm.md
  23. 3
      src/data/roadmaps/sql/content/from@N1Racr3ZpU320gS545We8.md
  24. 3
      src/data/roadmaps/sql/content/full-outer-join@aS5zCyJRA779yHF0G2pje.md
  25. 3
      src/data/roadmaps/sql/content/group-by@14TKE6KhrH1yFtHcSZSXq.md
  26. 5
      src/data/roadmaps/sql/content/group-by@Zw8IHfCCMSxmVjx5Ho5ff.md
  27. 3
      src/data/roadmaps/sql/content/having@HhICJpCK5__b-itUoEBES.md
  28. 9
      src/data/roadmaps/sql/content/having@ytwCkSMTiTuemE0KVfAfy.md
  29. 3
      src/data/roadmaps/sql/content/indexes@LcljR70T-OnzSrJJDqOWf.md
  30. 3
      src/data/roadmaps/sql/content/insert@-Hew0y53ziZK3epQnGA0O.md
  31. 9
      src/data/roadmaps/sql/content/insert@mPj6BiK5FKKkIQ9WsWEo6.md
  32. 3
      src/data/roadmaps/sql/content/join-queries@8V6yw7kLaow-VVcv_K_pL.md
  33. 1
      src/data/roadmaps/sql/content/joins@4UQQYbjzwVxZOAxBuXKQS.md
  34. 3
      src/data/roadmaps/sql/content/lag@BcXdxY6bld5c0YNFSKkh-.md
  35. 3
      src/data/roadmaps/sql/content/lead@aJJjaGunRrwyh9MjQfJt-.md
  36. 3
      src/data/roadmaps/sql/content/left-join@X9cJJ8zLZCF2cOoqxwFfY.md
  37. 3
      src/data/roadmaps/sql/content/length@RH8DLiQpDUWqw3U1522q5.md
  38. 3
      src/data/roadmaps/sql/content/lower@knTG6pAq2mYP24WMa29xI.md
  39. 3
      src/data/roadmaps/sql/content/managing-indexes@NtxGd6Vx-REBclry7lZuE.md
  40. 3
      src/data/roadmaps/sql/content/max@YqDJq3fPxUZlwsdq0kJg7.md
  41. 3
      src/data/roadmaps/sql/content/min@bFEYMlqPZtTUYtDQxqHzT.md
  42. 3
      src/data/roadmaps/sql/content/mod@OUw--8zEq6lk5-6oySVHe.md
  43. 3
      src/data/roadmaps/sql/content/modifying-views@3eE-l-P93nOXoWfLr8PSW.md
  44. 3
      src/data/roadmaps/sql/content/nested-subqueries@xkPJ2MYiXmzC4yqQWyB_7.md
  45. 3
      src/data/roadmaps/sql/content/not-null@M4M_-vjM9GNy0NmXZneDA.md
  46. 3
      src/data/roadmaps/sql/content/nullif@KI6vngoYcHsnpIk8ErhhS.md
  47. 61
      src/data/roadmaps/sql/content/operators@ffwniprGJHZzJ7t3lQcXz.md
  48. 58
      src/data/roadmaps/sql/content/optimizing-joins@C0dhS6uLf4TUSfvcWyXhv.md
  49. 55
      src/data/roadmaps/sql/content/order-by@NfCiSPrL4upMssukcw3Kh.md
  50. 67
      src/data/roadmaps/sql/content/performance-optimization@4rqCPpTb0dAgpheBKshRG.md
  51. 62
      src/data/roadmaps/sql/content/pivot--unpivot-operations@nwFaz9i-1s0WVrVaFsoqb.md
  52. 52
      src/data/roadmaps/sql/content/primary-key@Jlwmyq6CUQeDAlL4dazOP.md
  53. 39
      src/data/roadmaps/sql/content/query-analysis-techniques@C6P69YiFdS-ioPXMNfX07.md
  54. 66
      src/data/roadmaps/sql/content/query-optimization@Ps9Yv2s-bKvEegGAbPsiA.md
  55. 50
      src/data/roadmaps/sql/content/rank@cucCPw3KfetAP2OMFUs0X.md
  56. 7
      src/data/roadmaps/sql/content/rdbms-benefits-and-limitations@fNTb9y3zs1HPYclAmu_Wv.md
  57. 54
      src/data/roadmaps/sql/content/recursive-queries@TjgwabhEtaSoYMLNr6q9l.md
  58. 56
      src/data/roadmaps/sql/content/reducing-subqueries@UVTgbZrqpbYl1bQvQejcF.md
  59. 45
      src/data/roadmaps/sql/content/replace@VNbb3YPc0FtrROylRns8h.md
  60. 63
      src/data/roadmaps/sql/content/right-join@shpgZkh1CLqUwjOaRtAFy.md
  61. 49
      src/data/roadmaps/sql/content/rollback@xbD67KVlt3UhHpKh8HLx8.md
  62. 45
      src/data/roadmaps/sql/content/round@9DntFiZV1AyaRPhYP5q6u.md
  63. 43
      src/data/roadmaps/sql/content/row@aLDl75i8gtLRA2Ud-fMmQ.md
  64. 43
      src/data/roadmaps/sql/content/row_number@zW27ZHdLwQY-85iqbBKQZ.md
  65. 58
      src/data/roadmaps/sql/content/savepoint@pJtYvXUo81aZfPuRjIbMq.md
  66. 74
      src/data/roadmaps/sql/content/scalar@eXQ-TrTlqL5p2AdGnozkL.md
  67. 75
      src/data/roadmaps/sql/content/select@i8u8E_sne6XiKJo2FXDog.md
  68. 6
      src/data/roadmaps/sql/content/select@rmqXH29n1oXtZ8tvmcRFn.md
  69. 26
      src/data/roadmaps/sql/content/selective-projection@w53CSY53nAAN0ux-XeJ4c.md
  70. 40
      src/data/roadmaps/sql/content/self-join@6qG0AVYd6Y1B8LOSDoMX9.md
  71. 60
      src/data/roadmaps/sql/content/sql-keywords@6yoo7qC6X2jYDIjd3HIm7.md
  72. 46
      src/data/roadmaps/sql/content/sql-vs-nosql-databases@gx4KaFqKgJX9n9_ZGMqlZ.md
  73. 59
      src/data/roadmaps/sql/content/stored-procedures--functions@w7FNjdwqjY7X69aJqqBy4.md
  74. 60
      src/data/roadmaps/sql/content/subqueries@86iZ8s8EdhSuYwgwAM_EO.md
  75. 61
      src/data/roadmaps/sql/content/substring@PnG_5D6q66NAKxXVOwA6N.md
  76. 58
      src/data/roadmaps/sql/content/sum@w4T3jFb0ilf1KNw-AvRXG.md
  77. 48
      src/data/roadmaps/sql/content/table@R9WDMRd-3wxsKH97-sT3n.md
  78. 63
      src/data/roadmaps/sql/content/time@88KlrMqSza9_YaD7Dv61p.md
  79. 41
      src/data/roadmaps/sql/content/timestamp@7hEqkoxkdAWmakGZsMJx-.md
  80. 45
      src/data/roadmaps/sql/content/transaction-isolation-levels@ujeq8EIFcrqkBjoFizsJM.md
  81. 52
      src/data/roadmaps/sql/content/transactions@OdaBXz2XBAVLsQ-m7xtAM.md
  82. 35
      src/data/roadmaps/sql/content/truncate-table@K5vhqTJrdPK08Txv8zaEj.md
  83. 53
      src/data/roadmaps/sql/content/unique@5yGo8i7eplxtXOD_qfzOs.md
  84. 53
      src/data/roadmaps/sql/content/update@KJJ6PYjTnr_3yU2mNPL9v.md
  85. 26
      src/data/roadmaps/sql/content/update@eu9dJFi6gBPMBdy08Y5Bb.md
  86. 35
      src/data/roadmaps/sql/content/upper@Othfo7NvTVzfyL906PLM1.md
  87. 41
      src/data/roadmaps/sql/content/using-indexes@9wOgP0i9G4HSeZGn2Gm7r.md
  88. 56
      src/data/roadmaps/sql/content/views@2tyezwOIxV6O84N-Q3Awh.md
  89. 58
      src/data/roadmaps/sql/content/what-are-relational-databases@R9DQNc0AyAQ2HLpP4HOk6.md
  90. 25
      src/data/roadmaps/sql/content/where@WhYAy6f7Euk3E49-ot644.md
  91. 40
      src/data/roadmaps/sql/content/window-functions@tBvXLLp5FKeSSN35Kj1X4.md

@ -4,4 +4,5 @@ The `CEILING()` function in SQL returns the smallest integer greater than or equ
Learn more from the following resources: Learn more from the following resources:
- [@article@CEILING Function in SQL](https://www.javatpoint.com/ceiling-function-in-sql) - [@article@CEILING Function in SQL](https://www.javatpoint.com/ceiling-function-in-sql)
- [@article@SQL CEILING](https://www.w3schools.com/sql/func_sqlserver_ceiling.asp)

@ -4,4 +4,5 @@ A `CHECK` constraint in SQL is used to enforce data integrity by specifying a co
Learn more from the following resources: Learn more from the following resources:
- [@article@CHECK - PostgreSQL](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-check/) - [@article@CHECK - PostgreSQL](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-check/)
- [@article@SQL CHECK Constraint](https://www.w3schools.com/sql/sql_check.asp)

@ -5,3 +5,4 @@ Common Table Expressions (CTEs) in SQL are named temporary result sets that exis
Learn more from the following resources: Learn more from the following resources:
- [@article@Common Table Expressions (CTEs)](https://hightouch.com/sql-dictionary/sql-common-table-expression-cte) - [@article@Common Table Expressions (CTEs)](https://hightouch.com/sql-dictionary/sql-common-table-expression-cte)
- [@article@What is a Common Table Expression?](https://learnsql.com/blog/what-is-common-table-expression/)

@ -5,3 +5,4 @@
Learn more from the following resources: Learn more from the following resources:
- [@article@An overview of the CONCAT function in SQL](https://www.sqlshack.com/an-overview-of-the-concat-function-in-sql-with-examples/) - [@article@An overview of the CONCAT function in SQL](https://www.sqlshack.com/an-overview-of-the-concat-function-in-sql-with-examples/)
- [@article@SQL Server CONCAT](https://www.w3schools.com/sql/func_sqlserver_concat.asp)

@ -4,4 +4,5 @@ In SQL, a correlated subquery is a subquery that uses values from the outer quer
Learn more from the following resources: Learn more from the following resources:
- [@official@Correlated Subqueries](https://dev.mysql.com/doc/refman/8.4/en/correlated-subqueries.html) - [@official@Correlated Subqueries](https://dev.mysql.com/doc/refman/8.4/en/correlated-subqueries.html)
- [@video@Intro To Subqueries](https://www.youtube.com/watch?v=TUxadt94L0M)

@ -4,4 +4,5 @@
Learn more from the following resources: Learn more from the following resources:
- [@article@COUNT](https://www.w3schools.com/sql/sql_count.asp) - [@article@COUNT](https://www.w3schools.com/sql/sql_count.asp)
- [@article@COUNT SQL Function](https://www.datacamp.com/tutorial/count-sql-function)

@ -4,4 +4,5 @@
Learn more from the following resources: Learn more from the following resources:
- [@article@CREATE TABLE](https://www.tutorialspoint.com/sql/sql-create-table.htm) - [@article@CREATE TABLE](https://www.tutorialspoint.com/sql/sql-create-table.htm)
- [@article@SQL CREATE TABLE](https://www.programiz.com/sql/create-table)

@ -6,4 +6,5 @@ The issue with cross join is it returns the Cartesian product of the two tables,
Learn more from the following resources: Learn more from the following resources:
- [@article@CROSS JOIN](https://www.w3schools.com/mysql/mysql_join_cross.asp) - [@article@CROSS JOIN](https://www.w3schools.com/mysql/mysql_join_cross.asp)
- [@article@SQL CROSS JOIN With Examples](https://www.sqlshack.com/sql-cross-join-with-examples/)

@ -4,4 +4,5 @@ Data constraints in SQL are rules applied to columns or tables to enforce data i
Learn more from the following resources: Learn more from the following resources:
- [@article@Data Constraints](https://www.w3schools.com/sql/sql_constraints.asp) - [@article@Data Constraints](https://www.w3schools.com/sql/sql_constraints.asp)
- [@article@SQL Contraints](https://www.programiz.com/sql/constraints)

@ -4,4 +4,5 @@ Data Definition Language (DDL) is a subset of SQL used to define and manage the
Learn more from the following resources: Learn more from the following resources:
- [@article@Data Definition Language (DDL)](https://docs.getdbt.com/terms/ddl) - [@article@Data Definition Language (DDL)](https://docs.getdbt.com/terms/ddl)
- [@article@The Definitive Guide on Data Definition Language](https://www.dbvis.com/thetable/sql-ddl-the-definitive-guide-on-data-definition-language/)

@ -6,4 +6,5 @@ Constraints are classified into two types: column level and table level. Column
Learn more from the following resources: Learn more from the following resources:
- [@article@Integrity Constraints in SQL: A Guide With Examples](https://www.datacamp.com/tutorial/integrity-constraints-sql) - [@article@Integrity Constraints in SQL: A Guide With Examples](https://www.datacamp.com/tutorial/integrity-constraints-sql)
- [@article@Integrity Constraints](https://dataheadhunters.com/academy/integrity-constraints-ensuring-accuracy-and-consistency-in-your-data/)

@ -4,4 +4,5 @@ SQL data types define the kind of values that can be stored in a column and dete
Learn more from the following resources: Learn more from the following resources:
- [@article@SQL Data Types](https://www.digitalocean.com/community/tutorials/sql-data-types) - [@article@SQL Data Types](https://www.digitalocean.com/community/tutorials/sql-data-types)
- [@video@MySQL 101 - Data Types](https://www.youtube.com/watch?v=vAiBa69YCnk)

@ -4,4 +4,5 @@ The DATE data type in SQL is used to store calendar dates (typically in the form
Learn more from the following resources: Learn more from the following resources:
- [@article@SQL DATE](https://www.w3schools.com/sql/sql_dates.asp) - [@article@SQL DATE](https://www.w3schools.com/sql/sql_dates.asp)
- [@video@Working with Dates](https://www.youtube.com/watch?v=XyZ9HwXoR7o)

@ -4,4 +4,5 @@
Learn more from the following resources: Learn more from the following resources:
- [@article@DATEADD](https://www.mssqltips.com/sqlservertutorial/9380/sql-dateadd-function/) - [@article@DATEADD](https://www.mssqltips.com/sqlservertutorial/9380/sql-dateadd-function/)
- [@video@DATEADD Function](https://www.youtube.com/watch?v=DYCWOzzOycU)

@ -4,4 +4,5 @@
Learn more from the following resources: Learn more from the following resources:
- [@article@DATEPART](https://www.w3schools.com/sql/func_sqlserver_datepart.asp) - [@article@DATEPART](https://www.w3schools.com/sql/func_sqlserver_datepart.asp)
- [@article@SQL DATEPART](https://hightouch.com/sql-dictionary/sql-datepart)

@ -1 +1,7 @@
# Delete # Delete
DELETE is an SQL statement used to remove one or more rows from a table. It allows you to specify which rows to delete using a WHERE clause, or delete all rows if no condition is provided. DELETE is part of the Data Manipulation Language (DML) and is used for data maintenance, removing outdated or incorrect information, or implementing business logic that requires data removal. When used without a WHERE clause, it empties the entire table while preserving its structure, unlike the TRUNCATE command.
Learn more from the following resources:
- [@article@DELETE](https://www.w3schools.com/sql/sql_delete.asp)

@ -6,4 +6,5 @@ Unlike the `RANK` function, `DENSE_RANK` does not skip any rank (positions in th
Learn more from the following resources: Learn more from the following resources:
- [@article@SQL DENSE_RANK](https://www.sqltutorial.org/sql-window-functions/sql-dense_rank/) - [@article@SQL DENSE_RANK](https://www.sqltutorial.org/sql-window-functions/sql-dense_rank/)
- [@article@Breaking Down DENSE_RANK](https://www.kdnuggets.com/breaking-down-denserank-a-step-by-step-guide-for-sql-enthusiasts)

@ -7,3 +7,4 @@ When you execute the `DROP TABLE` statement, it eliminates both the table and it
Learn more from the following resources: Learn more from the following resources:
- [@article@DROP TABLE](https://www.w3schools.com/sql/sql_drop_table.asp) - [@article@DROP TABLE](https://www.w3schools.com/sql/sql_drop_table.asp)
- [@article@Drop a Table](https://www.coginiti.co/tutorials/beginner/drop-a-table/)

@ -4,4 +4,5 @@ Dropping views in SQL involves using the `DROP VIEW` statement to remove an exis
Learn more from the following resources: Learn more from the following resources:
- [@article@DROP VIEW](https://study.com/academy/lesson/sql-drop-view-tutorial-overview.html) - [@article@DROP VIEW](https://study.com/academy/lesson/sql-drop-view-tutorial-overview.html)
- [@article@DROP or DELETE a View](https://www.tutorialspoint.com/sql/sql-drop-view.htm)

@ -6,4 +6,5 @@ Consider an application where a user can choose multiple search conditions from
Learn more from the following resources: Learn more from the following resources:
- [@article@Dynamic SQL in SQL Server](https://www.sqlshack.com/dynamic-sql-in-sql-server/) - [@article@Dynamic SQL in SQL Server](https://www.sqlshack.com/dynamic-sql-in-sql-server/)
- [@video@Dynamic SQL](https://www.youtube.com/watch?v=01LZMCotcpY)

@ -6,4 +6,5 @@ One important aspect to note is that the `FLOOR` function's argument must be a n
Learn more from the following resources: Learn more from the following resources:
- [@article@FLOOR](https://www.w3schools.com/sql/func_sqlserver_floor.asp) - [@article@FLOOR](https://www.w3schools.com/sql/func_sqlserver_floor.asp)
- [@video@How to Round in SQL](https://www.youtube.com/watch?v=AUXw2JRwCFY)

@ -5,4 +5,5 @@ A foreign key in SQL is a column or group of columns in one table that refers to
Learn more from the following resources: Learn more from the following resources:
- [@article@What is a foreign key?](https://www.cockroachlabs.com/blog/what-is-a-foreign-key/) - [@article@What is a foreign key?](https://www.cockroachlabs.com/blog/what-is-a-foreign-key/)
- [@video@Foreign Keys are easy (kind of)](https://www.youtube.com/watch?v=rFssfx37UJw)

@ -6,4 +6,5 @@ Typically, `FROM` is followed by space delimited list of tables in which the SEL
Learn more from the following resources: Learn more from the following resources:
- [@article@SQL FROM Keyword](https://www.w3schools.com/sql/sql_ref_from.asp) - [@article@SQL FROM Keyword](https://www.w3schools.com/sql/sql_ref_from.asp)
- [@video@How to write basic SQL](https://www.youtube.com/watch?v=YfTDBA45PHk)

@ -4,4 +4,5 @@ A `FULL OUTER JOIN` in SQL combines the results of both `LEFT` and `RIGHT OUTER
Learn more from the following resources: Learn more from the following resources:
- [@article@FULL OUTER JOIN](https://www.w3schools.com/sql/sql_join_full.asp) - [@article@FULL OUTER JOIN](https://www.w3schools.com/sql/sql_join_full.asp)
- [@video@SQL FULL OUTER JOIN](https://www.youtube.com/watch?v=XpBkXo3DCEg)

@ -4,4 +4,5 @@
Learn more from the following resources: Learn more from the following resources:
- [@article@SQL GROUP BY](https://www.programiz.com/sql/group-by) - [@article@SQL GROUP BY](https://www.programiz.com/sql/group-by)
- [@video@Advanced Aggregate Functions in SQL](https://www.youtube.com/watch?v=nNrgRVIzeHg)

@ -1,7 +1,8 @@
# GROUP BY # GROUP BY
GROUP BY is an SQL clause used in SELECT statements to arrange identical data into groups. It's typically used with aggregate functions (like COUNT, SUM, AVG) to perform calculations on each group of rows. GROUP BY collects data across multiple records and groups the results by one or more columns, allowing for analysis of data at a higher level of granularity. This clause is fundamental for generating summary reports, performing data analysis, and creating meaningful aggregations of data in relational databases. `GROUP BY` is an SQL clause used in `SELECT` statements to arrange identical data into groups. It's typically used with aggregate functions (like `COUNT`, `SUM`, `AVG`) to perform calculations on each group of rows. `GROUP BY` collects data across multiple records and groups the results by one or more columns, allowing for analysis of data at a higher level of granularity. This clause is fundamental for generating summary reports, performing data analysis, and creating meaningful aggregations of data in relational databases.
Learn more from the following resources: Learn more from the following resources:
- [@article@SQL GROUP BY](https://www.programiz.com/sql/group-by) - [@article@SQL GROUP BY](https://www.programiz.com/sql/group-by)
- [@video@Advanced Aggregate Functions in SQL](https://www.youtube.com/watch?v=nNrgRVIzeHg)

@ -8,4 +8,5 @@ Also note, `HAVING` applies to summarized group records, whereas `WHERE` applies
Learn more from the following resources: Learn more from the following resources:
- [@article@SQL HAVING Clause](https://www.programiz.com/sql/having) - [@article@SQL HAVING Clause](https://www.programiz.com/sql/having)
- [@video@HAVING Clause](https://www.youtube.com/watch?v=tYBOMw7Ob8E)

@ -1,9 +1,12 @@
# HAVING # HAVING
`HAVING` is a clause in SQL that allows you to filter result sets in a `GROUP BY` clause. It is used to mention conditions on the groups being selected. In other words, `HAVING` is mainly used with the `GROUP BY` clause to filter the results that a `GROUP BY` returns. The `HAVING` clause is used in combination with the `GROUP BY` clause to filter the results of `GROUP BY`. It is used to mention conditions on the group functions, like `SUM`, `COUNT`, `AVG`, `MAX` or `MIN`.
It’s similar to a `WHERE` clause, but operates on the results of a grouping. The `WHERE` clause places conditions on the selected columns, whereas the `HAVING` clause places conditions on groups created by the `GROUP BY` clause. It's important to note that where `WHERE` clause introduces conditions on individual rows, `HAVING` introduces conditions on groups created by the `GROUP BY` clause.
Also note, `HAVING` applies to summarized group records, whereas `WHERE` applies to individual records.
Learn more from the following resources: Learn more from the following resources:
- [@article@SQL HAVING Clause](https://www.programiz.com/sql/having) - [@article@SQL HAVING Clause](https://www.programiz.com/sql/having)
- [@video@HAVING Clause](https://www.youtube.com/watch?v=tYBOMw7Ob8E)

@ -4,4 +4,5 @@ Indexes in SQL are database objects that improve the speed of data retrieval ope
Learn more from the following resources: Learn more from the following resources:
- [@article@Create SQL Index Statement](https://www.w3schools.com/sql/sql_create_index.asp) - [@article@Create SQL Index Statement](https://www.w3schools.com/sql/sql_create_index.asp)
- [@video@SQL Indexing Best Practices](https://www.youtube.com/watch?v=BIlFTFrEFOI)

@ -4,4 +4,5 @@ The "INSERT" statement is used to add new rows of data to a table in a database.
Learn more from the following resources: Learn more from the following resources:
- [@article@SQL INSERT](https://www.w3schools.com/sql/sql_insert.asp) - [@article@SQL INSERT](https://www.w3schools.com/sql/sql_insert.asp)
- [@video@SQL INSERT Statement](https://www.youtube.com/watch?v=Yp1MKeIG-M4)

@ -1 +1,8 @@
# Insert # Insert
The "INSERT" statement is used to add new rows of data to a table in a database. There are two main forms of the INSERT command: `INSERT INTO` which, if columns are not named, expects a full set of columns, and `INSERT INTO table_name (column1, column2, ...)` where only named columns will be filled with data.
Learn more from the following resources:
- [@article@SQL INSERT](https://www.w3schools.com/sql/sql_insert.asp)
- [@video@SQL INSERT Statement](https://www.youtube.com/watch?v=Yp1MKeIG-M4)

@ -4,4 +4,5 @@ SQL `JOIN` queries combine rows from two or more tables based on a related colum
Learn more from the following resources: Learn more from the following resources:
- [@article@7 SQL JOIN Examples With Detailed Explanations](https://learnsql.com/blog/sql-join-examples-with-explanations/) - [@article@7 SQL JOIN Examples With Detailed Explanations](https://learnsql.com/blog/sql-join-examples-with-explanations/)
- [@video@Joins are easy](https://www.youtube.com/watch?v=G3lJAxg1cy8)

@ -11,3 +11,4 @@ SQL `JOINs` are clauses used to combine rows from two or more tables based on a
Learn more from the following resources: Learn more from the following resources:
- [@article@SQL JOINs Cheat Sheet](https://www.datacamp.com/cheat-sheet/sql-joins-cheat-sheet) - [@article@SQL JOINs Cheat Sheet](https://www.datacamp.com/cheat-sheet/sql-joins-cheat-sheet)
- [@video@SQL JOINs Tutorial for beginners](https://www.youtube.com/watch?v=0OQJDd3QqQM)

@ -4,4 +4,5 @@
Learn more from the following resources: Learn more from the following resources:
- [@article@Understanding the LAG function in SQL](https://www.datacamp.com/tutorial/sql-lag) - [@article@Understanding the LAG function in SQL](https://www.datacamp.com/tutorial/sql-lag)
- [@video@LAG and LEAD functions](https://www.youtube.com/watch?v=j2u52RQ0qlw)

@ -4,4 +4,5 @@
Learn more from the following resources: Learn more from the following resources:
- [@article@SQL LEAD](https://www.codecademy.com/resources/docs/sql/window-functions/lead) - [@article@SQL LEAD](https://www.codecademy.com/resources/docs/sql/window-functions/lead)
- [@video@LAG and LEAD Window Functions in SQL](https://www.youtube.com/watch?v=nHEEyX_yDvo)

@ -4,4 +4,5 @@ A `LEFT JOIN` in SQL returns all rows from the left (first) table and the matchi
Learn more from the following resources: Learn more from the following resources:
- [@article@SQL LEFT JOIN](https://www.w3schools.com/sql/sql_join_left.asp) - [@article@SQL LEFT JOIN](https://www.w3schools.com/sql/sql_join_left.asp)
- [@video@SQL LEFT JOIN - SQL Tutorial](https://www.youtube.com/watch?v=giKwmtsz1U8)

@ -4,4 +4,5 @@ The `LENGTH` function in SQL returns the number of characters in a string. It's
Learn more from the following resources: Learn more from the following resources:
- [@article@How to Check the Length of a String in SQL](https://learnsql.com/cookbook/how-to-check-the-length-of-a-string-in-sql/) - [@article@How to Check the Length of a String in SQL](https://learnsql.com/cookbook/how-to-check-the-length-of-a-string-in-sql/)
- [@article@MySQL Length Function](https://www.w3schools.com/sql/func_mysql_length.asp)

@ -4,4 +4,5 @@ The `LOWER` function in SQL converts all characters in a specified string to low
Learn more from the following resources: Learn more from the following resources:
- [@article@How to change text to lowercase in SQL](https://learnsql.com/cookbook/how-to-change-text-to-lowercase-in-sql/) - [@article@How to change text to lowercase in SQL](https://learnsql.com/cookbook/how-to-change-text-to-lowercase-in-sql/)
- [@article@LOWER Function](https://www.w3schools.com/sql/func_sqlserver_lower.asp)

@ -4,4 +4,5 @@ Managing indexes in SQL involves creating, modifying, and dropping indexes to op
Learn more from the following resources: Learn more from the following resources:
- [@article@SQL Server Indexes](https://www.sqlservercentral.com/articles/sql-server-indexes) - [@article@SQL Server Indexes](https://www.sqlservercentral.com/articles/sql-server-indexes)
- [@article@Optimize index maintenance](https://learn.microsoft.com/en-us/sql/relational-databases/indexes/reorganize-and-rebuild-indexes?view=sql-server-ver16)

@ -4,4 +4,5 @@
Learn more from the following resources: Learn more from the following resources:
- [@article@MAX](https://www.techonthenet.com/sql/max.php) - [@article@MAX](https://www.techonthenet.com/sql/max.php)
- [@video@Basic Aggregate Functions](https://www.youtube.com/watch?v=jcoJuc5e3RE)

@ -4,4 +4,5 @@
Learn more from the following resources: Learn more from the following resources:
- [@article@SQL MAX & MIN](https://www.programiz.com/sql/min-and-max) - [@article@SQL MAX & MIN](https://www.programiz.com/sql/min-and-max)
- [@video@COUNT, SUM, AVG, MIN, MAX (SQL) - Aggregating Data](https://www.youtube.com/watch?v=muwEdPsx534)

@ -4,4 +4,5 @@ The `MOD` function in SQL calculates the remainder when one number is divided by
Learn more from the following resources: Learn more from the following resources:
- [@article@MOD](https://www.w3schools.com/sql/func_mysql_mod.asp) - [@article@MOD](https://www.w3schools.com/sql/func_mysql_mod.asp)
- [@video@MOD Function in SQL](https://www.youtube.com/watch?v=f1Rqf7CwjE0)

@ -8,4 +8,5 @@ In SQL, you can modify a `VIEW` in two ways:
Learn more from the following resources: Learn more from the following resources:
- [@article@Modify Views in SQL Server](https://www.sqlshack.com/create-view-sql-modifying-views-in-sql-server/) - [@article@Modify Views in SQL Server](https://www.sqlshack.com/create-view-sql-modifying-views-in-sql-server/)
- [@video@SQL VIEWs in 4 Minutes](https://www.youtube.com/watch?v=vLLkNI-vkV8)

@ -6,4 +6,5 @@ Nested subqueries can get complicated quickly, but they are essential for perfor
Learn more from the following resources: Learn more from the following resources:
- [@article@Nested Subqueries](https://www.studysmarter.co.uk/explanations/computer-science/databases/nested-subqueries-in-sql/) - [@article@Nested Subqueries](https://www.studysmarter.co.uk/explanations/computer-science/databases/nested-subqueries-in-sql/)
- [@video@MySQL Subqueries](https://www.youtube.com/watch?v=i5acg3Hvu6g)

@ -6,4 +6,5 @@ For instance, if you're designing a table for employee data, you might want to e
Learn more from the following resources: Learn more from the following resources:
- [@article@SQL IS NULL and IS NOT NULL](https://www.programiz.com/sql/is-null-not-null) - [@article@SQL IS NULL and IS NOT NULL](https://www.programiz.com/sql/is-null-not-null)
- [@video@NOT NULL Constraint](https://www.youtube.com/watch?v=unzHhq82mKU)

@ -4,4 +4,5 @@
Learn more from the following resources: Learn more from the following resources:
- [@article@NULLIF](https://www.w3schools.com/sql/func_sqlserver_nullif.asp) - [@article@NULLIF](https://www.w3schools.com/sql/func_sqlserver_nullif.asp)
- [@video@What is NULLIF in SQL?](https://www.youtube.com/watch?v=Jaw53T__RRY)

@ -1,61 +1,8 @@
# Operators # Operators
SQL operators are used to perform operations like comparisons and arithmetic calculations. They are very crucial in SQL operators are symbols or keywords used to perform operations on data within a database. They are essential for constructing queries that filter, compare, and manipulate data. Common types of operators include arithmetic operators (e.g., `+`, `-`, `*`, `/`), which perform mathematical calculations; comparison operators (e.g., `=`, `!=`, `<`, `>`), used to compare values; logical operators (e.g., `AND`, `OR`, `NOT`), which combine multiple conditions in a query; and set operators (e.g., `UNION`, `INTERSECT`, `EXCEPT`), which combine results from multiple queries. These operators enable precise control over data retrieval and modification.
forming queries. SQL operators are divided into the following types:
1. **Arithmetic Operators**: These are used to perform mathematical operations. Here is a list of these operators: Learn more from the following resources:
- `+` : Addition - [@article@SQL Operators](https://www.w3schools.com/sql/sql_operators.asp)
- `-` : Subtraction - [@article@SQL Operators: 6 Different Types](https://www.dataquest.io/blog/sql-operators/)
- `*` : Multiplication
- `/` : Division
- `%` : Modulus
Example:
```sql
SELECT product, price, (price * 0.18) as tax
FROM products;
```
2. **Comparison Operators**: These are used in the where clause to compare one expression with another. Some of these
operators are:
- `=` : Equal
- `!=` or `<>` : Not equal
- `>` : Greater than
- `<` : Less than
- `>=`: Greater than or equal
- `<=`: Less than or equal
Example:
```sql
SELECT name, age
FROM students
WHERE age > 18;
```
3. **Logical Operators**: They are used to combine the result set of two different component conditions. These include:
- `AND`: Returns true if both components are true.
- `OR` : Returns true if any one of the component is true.
- `NOT`: Returns the opposite boolean value of the condition.
Example:
```sql
SELECT *
FROM employees
WHERE salary > 50000 AND age < 30;
```
4. **Bitwise Operators**: These perform bit-level operations on the inputs. Here is a list of these operators:
- `&` : Bitwise AND
- `|` : Bitwise OR
- `^` : Bitwise XOR
Bitwise operators are much less commonly used in SQL than the other types of operators.
Remember, the datatype of the result is dependent on the types of the operands.

@ -1,58 +1,8 @@
# Optimizing Joins # Optimizing Joins
Query optimization for joins is an essential aspect in improving the execution speed of your SQL commands and reduce the response time. Joins, particularly the ones involving multiple tables, can be quite costly in terms of database performance. Here are some methods to optimize joins in SQL: Optimizing joins in SQL involves techniques to improve the performance of queries that combine data from multiple tables. Key strategies include using appropriate join types (e.g., `INNER JOIN` for matching rows only, `LEFT JOIN` for all rows from one table), indexing the columns used in join conditions to speed up lookups, and minimizing the data processed by filtering results with `WHERE` clauses before the join. Additionally, reducing the number of joins, avoiding unnecessary columns in the `SELECT` statement, and ensuring that the join conditions are based on indexed and selective columns can significantly enhance query efficiency. Proper join order and using database-specific optimization hints are also important for performance tuning.
## 1. Minimize the Number of Tables in the Join Learn more from the following resources:
Try to keep the number of tables in each join operation as low as possible. Remove any tables which are not necessary to retrieve the requested data. - [@article@How to Optimize a SQL Query with Multiple Joins](https://dezbor.com/blog/optimize-sql-query-with-multiple-joins)
- [@video@Secret to optimizing SQL queries](https://www.youtube.com/watch?v=BHwzDmr6d7s)
```sql
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
```
## 2. Check the Order of Tables in the Join
The order in which tables are joined can have a considerable impact on the execution time. As a general rule, join the tables that have the most rows last. If you are joining more than two tables, and aren’t certain of the best order, you can try different orders to see which gives the best performance.
```sql
SELECT *
FROM Table1 -- smallest table
JOIN Table2 ON Table1.ID = Table2.ID -- larger table
JOIN Table3 ON Table1.ID = Table3.ID -- largest table
```
## 3. Always Use Indexes
Using indexes helps improve the speed at which SQL can execute a join. Indexes are particularly useful if your join involves columns that are often involved in where clauses or sort operations. SQL can utilize indexes to quickly locate the rows it needs, and this can drastically improve performance.
```sql
CREATE INDEX idx_columnname
ON table_name (column_name);
```
## 4. Use Subqueries
Sometimes, it would be faster to retrieve the data in multiple steps using subqueries. In the below example, instead of joining, we are retrieving IDs using a subquery and then fetching the data using those IDs.
```sql
SELECT column_name(s)
FROM table1
WHERE column_name IN (SELECT column_name FROM table2);
```
## 5. Use Explicit JOIN Syntax
Use of explicit syntax helps in better understanding of the relations between the tables, thus enabling the SQL execution engine to get optimized plans.
```sql
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID = Customers.CustomerID;
```
In conclusion, the optimization of joins is an art that requires some level of knowledge about database design and how SQL works under the hood. A performance-efficient SQL code needs thorough testing and trial-n-run for different scenarios.

@ -1,55 +1,8 @@
# ORDER BY # ORDER BY
The `ORDER BY` clause in SQL is used to sort the result-set from a SELECT statement in ascending or descending order. It sorts the records in ascending order by default. If you want to sort the records in descending order, you have to use the `DESC` keyword. The `ORDER BY` clause in SQL is used to sort the result set of a query by one or more columns. By default, the sorting is in ascending order, but you can specify descending order using the `DESC` keyword. The clause can sort by numeric, date, or text values, and multiple columns can be sorted by listing them in the `ORDER BY` clause, each with its own sorting direction. This clause is crucial for organizing data in a meaningful sequence, such as ordering by a timestamp to show the most recent records first, or alphabetically by name.
## Syntax for Ascending Order: Learn more from the following resources:
```sql
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC;
```
Here, `ASC` is used for ascending order. If you use `ORDER BY` without `ASC` or `DESC`, `ASC` is used by default.
## Syntax for Descending Order: - [@article@SQL ORDER BY Keyword](https://www.w3schools.com/sql/sql_orderby.asp)
```sql - [@video@SQL ORDER BY Sorting Clause](https://www.youtube.com/watch?v=h_HHTNjAgS8)
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... DESC;
```
Here, `DESC` is used for descending order.
## Usage Example
Consider the following `Customers` table:
| ID | NAME | AGE | ADDRESS | SALARY |
|----|-------|-----|-----------|--------|
| 1 | Ramesh| 32 | Ahmedabad | 2000.0 |
| 2 | Khilan| 25 | Delhi | 1500.0 |
| 3 | kaushik | 23 | Kota | 2000.0 |
| 4 | Chaitali | 25 | Mumbai | 6500.0 |
| 5 | Hardik | 27 | Bhopal | 8500.0 |
| 6 | Komal | 22 | MP | 4500.0 |
**Example 1 - Ascending Order:**
Sort the table by the `NAME` column in ascending order:
```sql
SELECT * FROM Customers
ORDER BY NAME ASC;
```
**Example 2 - Descending Order:**
Sort the table by the `SALARY` column in descending order:
```sql
SELECT * FROM Customers
ORDER BY SALARY DESC;
```
**Example 3 - Multiple Columns:**
You can also sort by multiple columns. Sort the table by the `AGE` column in ascending order and then `SALARY` in descending order:
```sql
SELECT * FROM Customers
ORDER BY AGE ASC, SALARY DESC;
```
In this instance, the `ORDER BY` clause first sorts the `Customers` table by the `AGE` column and then sorts the sorted result further by the `SALARY` column.

@ -1,67 +1,8 @@
# Performance Optimization # Performance Optimization
SQL performance optimization is crucial for accelerating SQL queries and improving overall database performance. Most importantly, it ensures smooth and efficient execution of SQL statements, which can result in better application performance and user experience. Performance optimization in SQL involves a set of practices aimed at improving the efficiency and speed of database queries and overall system performance. Key strategies include indexing critical columns to speed up data retrieval, optimizing query structure by simplifying or refactoring complex queries, and using techniques like query caching to reduce redundant database calls. Other practices include reducing the use of resource-intensive operations like `JOINs` and `GROUP BY`, selecting only necessary columns (`SELECT *` should be avoided), and leveraging database-specific features such as partitioning, query hints, and execution plan analysis. Regularly monitoring and analyzing query performance, along with maintaining database health through routine tasks like updating statistics and managing indexes, are also vital to sustaining high performance.
## 1. Indexes Learn more from the following resources:
Creating indexes is one of the prominent ways to optimize SQL performance. They accelerate lookup and retrieval of data from a database. - [@article@Performance Tuning SQL Queries](https://mode.com/sql-tutorial/sql-performance-tuning)
- [@article@SQL performance tuning](https://stackify.com/performance-tuning-in-sql-server-find-slow-queries/)
```sql
CREATE INDEX index_name
ON table_name (column1, column2, ...);
```
Remember, though indexes speed up data retrieval, they can slow down data modification such as `INSERT`, `UPDATE`, and `DELETE`.
## 2. Avoid SELECT *
Get only the required columns instead of fetching all columns using `SELECT *`. It reduces the amount of data that needs to be read from the disk.
```sql
SELECT required_column FROM table_name;
```
## 3. Use Join Instead of Multiple Queries
Using join clauses can combine rows from two or more tables in a single query based on a related column between them. This reduces the number of queries hitting the database, improving performance.
```sql
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
```
## 4. Use LIMIT
If only a certain number of rows are necessary, use the LIMIT keyword to restrict the number of rows returned by the query.
```sql
SELECT column FROM table LIMIT 10;
```
## 5. Avoid using LIKE Operator with Wildcards at the Start
Using wildcard at the start of a query (`LIKE '%search_term'`) can lead to full table scans.
```sql
SELECT column FROM table WHERE column LIKE 'search_term%';
```
## 6. Optimize Database Schema
Database schema involves how data is organized and should be optimized for better performance.
## 7. Use EXPLAIN
Many databases have 'explain plan' functionality that shows the plan of the database engine to execute the query.
```sql
EXPLAIN SELECT * FROM table_name WHERE column = 'value';
```
This can give insight into performance bottlenecks like full table scans, missing indices, etc.
## 8. Denormalization
In some cases, it might be beneficial to denormalize the database to a certain extent to reduce complex joins and queries. Keep in mind that this is usually the last resort and may not always yield the desired results.
Remember, each query and database is unique, so what might work in one scenario might not work in another. It is always crucial to test the queries in a controlled and isolated environment before pushing them into production.

@ -1,62 +1,8 @@
# Pivot and Unpivot Operations # Pivot and Unpivot Operations
## PIVOT Pivot and Unpivot operations in SQL are used to transform and reorganize data, making it easier to analyze in different formats. The `PIVOT` operation converts rows into columns, allowing you to summarize data and present it in a more readable, table-like format. For example, it can take sales data by month and convert the months into individual columns. Conversely, the `UNPIVOT` operation does the opposite—it converts columns back into rows, which is useful for normalizing data that was previously pivoted or to prepare data for certain types of analysis. These operations are particularly useful in reporting and data visualization scenarios, where different perspectives on the same data set are required.
The PIVOT operator is used in SQL to rotate the table data from rows to columns, essentially transforming the data into a matrix format. This operator allows you to create a crosstab view of the data, with selected columns as rows and others as columns, providing a summary view. Learn more from the following resources:
Here is a general example of the syntax: - [@article@SQL PIVOT](https://builtin.com/articles/sql-pivot)
- [@article@SQL UNPIVOT](https://duckdb.org/docs/sql/statements/unpivot.html)
```sql
SELECT ...
FROM ...
PIVOT (aggregate_function(column_to_aggregate)
FOR column_to_pivot
IN (list_of_values))
```
__Example__: Let's assume we have a 'Sales' table with 'Year', 'Quarter' and 'Amount' columns. If we want to turn 'Quarter' values into columns, we might use:
```sql
SELECT * FROM
(
SELECT Year, Quarter, Amount
FROM Sales
)
PIVOT
(
SUM(Amount)
FOR Quarter IN ('Q1' 'Q2' 'Q3' 'Q4')
)
```
This would give us each year as a row and each quarter as a column, with the total sales for each quarter in the cells.
## UNPIVOT
The UNPIVOT operator performs the reverse operation to PIVOT, rotating columns into rows. If the columns you're converting have a certain relationship, this can be factored into a single column instead.
Here is a general example of the syntax:
```sql
SELECT ...
FROM ...
UNPIVOT (column_for_values
FOR column_for_names IN (list_of_columns))
```
__Example__: Conversely, if we want to transform the quarter columns back into rows from the previous 'Sales' pivot table, we would use:
```sql
SELECT * FROM
(
SELECT Year, Q1, Q2, Q3, Q4
FROM Sales
)
UNPIVOT
(
Amount
FOR Quarter IN (Q1, Q2, Q3, Q4)
)
```
This would result in each combination of year and quarter as a row, with the amount sold in that quarter as the 'Amount' column. Keep in mind, the UNPIVOTed data isn't equivalent to the original data as the original data might have had multiple rows for each year/quarter.

@ -1,52 +1,8 @@
# Primary Key # Primary Key
A primary key is a special relational database table field (or combination of fields) designated to uniquely identify all table records. A primary key in SQL is a unique identifier for each record in a database table. It ensures that each row in the table is uniquely identifiable, meaning no two rows can have the same primary key value. A primary key is composed of one or more columns, and it must contain unique values without any `NULL` entries. The primary key enforces entity integrity by preventing duplicate records and ensuring that each record can be precisely located and referenced, often through foreign key relationships in other tables. Using a primary key is fundamental for establishing relationships between tables and maintaining the integrity of the data model.
A primary key's main features are: Learn more from the following resources:
- It must contain a unique value for each row of data. - [@article@SQL PRIMARY KEY Constraint](https://www.w3schools.com/sql/sql_primarykey.ASP)
- It cannot contain null values. - [@article@SQL Primary Key](https://www.tutorialspoint.com/sql/sql-primary-key.htm)
## Usage of Primary Key
You define a primary key for a table using the `PRIMARY KEY` constraint. A table can have only one primary key. You can define a primary key in SQL when you create or modify a table.
## Create Table With Primary Key
In SQL, you can create a table with a primary key by using `CREATE TABLE` syntax.
```sql
CREATE TABLE Employees (
ID INT PRIMARY KEY,
NAME TEXT,
AGE INT,
ADDRESS CHAR(50)
);
```
In this example, `ID` is the primary key which must consist of unique values and can't be null.
## Modify Table to Add Primary Key
If you want to add a primary key to an existing table, you can use `ALTER TABLE` syntax.
```sql
ALTER TABLE Employees
ADD PRIMARY KEY (ID);
```
This will add a primary key to `ID` column in the `Employees` table.
## Composite Primary Key
We can also use multiple columns to define a primary key. Such key is known as composite key.
```sql
CREATE TABLE Customers (
CustomerID INT,
StoreID INT,
CONSTRAINT pk_CustomerID_StoreID PRIMARY KEY (CustomerID,StoreID)
);
```
In this case, each combination of `CustomerID` and `StoreID` must be unique across the whole table.

@ -1,39 +1,8 @@
# Query Analysis Techniques # Query Analysis Techniques
Query analysis is a critical part of performance optimization in SQL. It involves critically examining your SQL queries to determine potential bottlenecks, unnecessary computations or data fetch operations, and areas where you can implement performance optimization techniques. Query analysis techniques in SQL involve examining and optimizing queries to improve performance and efficiency. Key techniques include using `EXPLAIN` or `EXPLAIN PLAN` commands to understand the query execution plan, which reveals how the database processes the query, including join methods, index usage, and data retrieval strategies. Analyzing `execution plans` helps identify bottlenecks such as full table scans or inefficient joins. Other techniques include `profiling queries` to measure execution time, `examining indexes` to ensure they are effectively supporting query operations, and `refactoring queries` by breaking down complex queries into simpler, more efficient components. Additionally, monitoring `database performance metrics` like CPU, memory usage, and disk I/O can provide insights into how queries impact overall system performance. Regularly applying these techniques allows for the identification and resolution of performance issues, leading to faster and more efficient database operations.
## Explain Plan Learn more from the following resources:
SQL provides an "EXPLAIN PLAN" statement that can be utilized to understand the execution plan of a query. This is used to analyze the performance of SQL commands before actually executing them. - [@article@EXPLAIN](https://docs.snowflake.com/en/sql-reference/sql/explain)
- [@article@EXPLAIN PLAN](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/EXPLAIN-PLAN.html)
When running the command, the output shows the steps involved in executing the query and an estimation of the cost involved with each step. The cost is a unitless value representing the resources required to perform the operation.
```sql
EXPLAIN PLAN FOR SELECT * FROM table_name;
```
## Index Usage
Using appropriate indexes is crucial for query performance. Unnecessary full table scans can be avoided if the correct indexes are present. Even though SQL will automatically determine the appropriate index to use, it can be helpful to manually specify which index to use for complex queries.
```sql
CREATE INDEX idx_column ON table_name(column_name);
```
## Join Optimization
The order in which tables are joined can have a large impact on query performance. In general, you should join tables in a way that results in the smallest result set as early as possible.
Look out for "Nested Loops" in your explain plan. These can be a cause of slow performance if a large number of rows are being processed.
```sql
SELECT *
FROM table1
INNER JOIN table2 ON table1.id = table2.id;
```
## Regular Performance Tests
Regular query performance testing can catch slow queries before they become a problem. Utilizing tools that can monitor and report query performance can help you keep an eye on your database's performance.
Also, continual analysis of the query performance should be done as your data grows. A query that performs well with a small dataset may not do so when the dataset grows.

@ -1,66 +1,8 @@
# Query Optimization # Query Optimization
Query optimization is a function of SQL that involves tuning and optimizing a SQL statement so that the system executes it in the fastest and most efficient way possible. It includes optimizing the costs of computation, communication, and disk I/O. Query optimization in SQL involves refining queries to enhance their execution speed and reduce resource consumption. Key strategies include indexing columns used in `WHERE`, `JOIN`, and `ORDER BY` clauses to accelerate data retrieval, minimizing data processed by limiting the number of columns selected and filtering rows early in the query. Using appropriate join types and arranging joins in the most efficient order are crucial. Avoiding inefficient patterns like `SELECT`, replacing subqueries with joins or common table expressions (CTEs), and leveraging query hints or execution plan analysis can also improve performance. Regularly updating statistics and ensuring that queries are structured to take advantage of database-specific optimizations are essential practices for maintaining optimal performance.
The primary approaches of query optimization involve the following: Learn more from the following resources:
## Rewriting Queries - [@video@SQL Query Optimization](https://www.youtube.com/watch?v=GA8SaXDLdsY)
- [@article@12 Ways to Optimize SQL Queries](https://www.developernation.net/blog/12-ways-to-optimize-sql-queries-in-database-management/)
This means changing the original SQL query to an equivalent one which requires fewer system resources. It's usually done automatically by the database system.
For instance, let's say we have a query as follows:
```sql
SELECT *
FROM Customers
WHERE state = 'New York' AND city = 'New York';
```
The above query can be rewritten using a subquery for better optimization:
```sql
SELECT *
FROM Customers
WHERE state = 'New York'
AND city IN (SELECT city
FROM Customers
WHERE city = 'New York');
```
## Choosing the right index
Indexes are used to find rows with specific column values quickly. Without an index, SQL has to begin with the first row and then read through the entire table to find the appropriate rows. The larger the table, the more costly the operation. Choosing a right and efficient index greatly influence on query performance.
For example,
```sql
CREATE INDEX index_name
ON table_name (column1, column2, ...);
```
## Fine-tuning Database Design
Improper database schema designs could result in poor query performances. While not strictly a part of query optimization, tuning the database design can speed up the query execution time drastically.
Changes such as the separation of specific data to different tables (Normalization), combining redundant data (Denormalization), or changing the way how tables are linked (Optimized Join Operations), can be implemented to optimize the schema.
## Use of SQL Clauses wisely
The usage of certain SQL clauses can help in query optimization like LIMIT, BETWEEN etc.
Example,
```sql
SELECT column1, column2
FROM table_name
WHERE condition
LIMIT 10;
```
## System Configuration
Many database systems allow you to configure system parameters that control its behavior during query execution. For instance, in MySQL, you can set parameters like `sort_buffer_size` or `join_buffer_size` to tweak how MySQL would use memory during sorting and joining operations.
In PostgreSQL, you can set `work_mem` to control how much memory is utilized during operations such as sorting and hashing.
Always remember the goal of query optimization is to lessen the system resources usage in terms of memory, CPU time, and thus improve the query performance.

@ -1,50 +1,8 @@
# rank # rank
`RANK()` is a window function in SQL that assigns a unique rank to each distinct row within a partition of a result set. The rank of the first row within each partition is one. The `RANK()` function adds the number of tied rows to the tied rank to calculate the next rank. So the ranks may not be consecutive numbers. The `RANK` function in SQL is a window function that assigns a rank to each row within a partition of a result set, based on the order specified by the `ORDER BY` clause. Unlike the `ROW_NUMBER` function, `RANK` allows for the possibility of ties—rows with equal values in the ordering column(s) receive the same rank, and the next rank is skipped accordingly. For example, if two rows share the same rank of 1, the next rank will be 3. This function is useful for scenarios where you need to identify relative positions within groups, such as ranking employees by salary within each department.
## Parameters of RANK Function Learn more from the following resources:
There are no arguments for the `RANK()` function. However, since it's a window function, the function operates on a set of rows (window) defined by the `OVER` clause, which is mandatory. - [@article@Overview of SQL RANK Functions](https://www.sqlshack.com/overview-of-sql-rank-functions/)
- [@video@RANK, DENSE_RANK, ROW_NUMBER SQL Analytical Functions Simplified](https://www.youtube.com/watch?v=xMWEVFC4FOk)
## Syntax
The syntax of `RANK` function is:
```sql
RANK () OVER (
[PARTITION BY column_1, column_2,…]
ORDER BY column_3,column_4,…
)
```
`PARTITION BY`: This clause divides the rows into multiple groups or partitions upon which the `RANK()` function is applied.
`ORDER BY`: This clause sorts the rows in each partition.
If `PARTITION BY` is not specified, the function treats all rows in the result set as a single partition.
## Examples
Here's an example query using the `RANK()` function:
```sql
SELECT
product_name,
brand,
RANK () OVER (
PARTITION BY brand
ORDER BY product_name ASC
) Product_rank
FROM
products;
```
In this example, it generates a list of products, grouped by brand, and ranked by product_name within each brand. The `product_name` with the smallest value (alphabetically first when sorting ASC) gets a rank of 1 within its partition.
## Important Notes
- `RANK()` function may return duplicate rankings if the column on which the function is applied contains duplicate values.
- The `RANK()` function will leave a gap and create a non-consecutive ranking if there are equal rankings (ties).
- `RANK()` function offers a very efficient way to solve top-N problems.
You might also be interested in looking at other similar ranking functions in SQL like `DENSE_RANK()`, `ROW_NUMBER()`, etc.

@ -24,4 +24,9 @@ Here are some of the limitations of using an RDBMS:
- **Handling of Unstructured Data**: RDBMSs are not suitable for handling unstructured data like multimedia files, social media posts, and sensor data, as their relational structure is optimized for structured data. - **Handling of Unstructured Data**: RDBMSs are not suitable for handling unstructured data like multimedia files, social media posts, and sensor data, as their relational structure is optimized for structured data.
- **Horizontal Scalability**: RDBMSs are not as easily horizontally scalable as NoSQL databases. Scaling horizontally, which involves adding more machines to the system, can be challenging in terms of cost and complexity. - **Horizontal Scalability**: RDBMSs are not as easily horizontally scalable as NoSQL databases. Scaling horizontally, which involves adding more machines to the system, can be challenging in terms of cost and complexity.
Learn more from the following resources:
- [@article@Advantages and Disadvantages of DBMS](https://www.javatpoint.com/advantages-and-disadvantages-of-dbms)
- [@article@ACID Transactions in Databases](https://www.databricks.com/glossary/acid-transactions)

@ -1,54 +1,8 @@
# Recursive Queries # Recursive Queries
Recursive queries are advanced SQL queries used for data analysis, especially when working with hierarchical or tree-structured data. These queries are implemented using Common Table Expressions (CTEs). CTEs have the same structure as a standard SELECT statement but are prefixed with `WITH`, followed by the CTE name and an optional list of columns. Recursive queries in SQL allow for the repeated execution of a query within itself, enabling the traversal of hierarchical or tree-like data structures. This powerful feature is particularly useful for handling nested relationships, such as organizational hierarchies, bill of materials, or network topologies. By using a combination of an anchor member (initial query) and a recursive member (the part that refers to itself), recursive queries can iterate through multiple levels of data, retrieving information that would be difficult or impossible to obtain with standard SQL constructs. This technique simplifies complex queries and improves performance when dealing with self-referential data.
CTEs can be recursive and non-recursive. The non-recursive CTE is a query that is executed once and then goes out of scope. Learn more from the following resources:
## Recursive CTE - [@article@Recursive Queries in SQL](https://codedamn.com/news/sql/recursive-queries-in-sql)
- [@article@Recursive SQL Expression Visually Explained](https://builtin.com/data-science/recursive-sql)
A recursive CTE is a CTE that references itself. Recursive CTEs have a minimum of two queries, an anchor member (runs only once), and a recursive member (runs repeatedly). Include a UNION ALL statement between these queries.
Here's a sample of a recursive CTE:
```sql
WITH RECURSIVE ancestors AS (
SELECT employee_id, manager_id, full_name
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.manager_id, e.full_name
FROM employees e
INNER JOIN ancestors a ON a.employee_id = e.manager_id
)
SELECT * FROM ancestors;
```
In this code snippet, the first query is the anchor member that fetches the employees with no manager. The second part is the recursive member, continuously fetching managers until none are left.
## Syntax of Recursive CTE
Here's the general structure of a recursive CTE:
```sql
WITH RECURSIVE cte_name (column_list) AS (
-- Anchor member
SELECT column_list
FROM table_name
WHERE condition
UNION ALL
-- Recursive member
SELECT column_list
FROM table_name
INNER JOIN cte_name ON condition
)
SELECT * FROM cte_name;
```
Note: some database systems such as MySQL, PostgreSQL, and SQLite use `WITH RECURSIVE` for recursive CTEs. Others like SQL Server, Oracle, and DB2 use just `WITH`.
Remember to be careful when setting the conditions for your recursive query to avoid infinite loops.

@ -1,57 +1,5 @@
# Reducing Subqueries # Reducing Subqueries
SQL subqueries allow you to nest a SELECT statement inside another query. However, while this can sometimes simplify the code, the drawback is they can result in long-running queries and reduced performance. Therefore, optimizing queries often involves reducing subqueries. Two common ways to achieve this include using JOINS and 'EXISTS' clause. Recursive queries in SQL allow for iterative processing of hierarchical or tree-structured data within a single query. They consist of an anchor member (the base case) and a recursive member that references the query itself, enabling the exploration of parent-child relationships, traversal of graphs, or generation of series data. This powerful feature is particularly useful for tasks like querying organizational hierarchies, bill of materials structures, or navigating complex relationships in data that would otherwise require multiple separate queries or procedural code.
1. **JOIN:** A JOIN clause combines rows from two or more tables based on a related column. In many cases, a JOIN can replace a subquery with equivalent logic, but with improved performance. Learn more from the following resources:
An example would be a scenario where you have two tables `Orders` and `Customers`, and you want to find orders made by a specific customer:
Subquery could be:
```sql
SELECT OrderNumber
FROM Orders
WHERE CustomerID IN (
SELECT CustomerID
FROM Customers
WHERE CustomerName = 'John Doe'
);
```
Equivalent JOIN:
```sql
SELECT o.OrderNumber
FROM Orders o
JOIN Customers c ON o.CustomerID = c.CustomerID
WHERE c.CustomerName = 'John Doe';
```
2. **EXISTS:** The EXISTS operator checks for the existence of rows returned by the subquery. Many times, a subquery can be replaced with an EXISTS clause which would greatly increase performance as EXISTS will stop processing once it hits a true condition and does not need to check all results like IN would.
Consider you want to find all customers who have placed at least one order:
Subquery might be:
```sql
SELECT *
FROM Customers
WHERE CustomerID IN (
SELECT CustomerID
FROM Orders
);
```
Equivalent EXISTS use case:
```sql
SELECT *
FROM Customers c
WHERE EXISTS (
SELECT 1
FROM Orders o
WHERE c.CustomerID = o.CustomerID
);
```
While it's important to minimize subqueries whenever possible, there may be cases where you cannot replace a subquery, especially when dealing with correlated subqueries or complex queries where rewriting might be nontrivial or not feasible.

@ -1,45 +1,8 @@
# REPLACE # REPLACE
You can use the `REPLACE()` function in SQL to substitute all occurrences of a specified string. The `REPLACE` function in SQL is used to substitute all occurrences of a specified substring within a string with a new substring. It takes three arguments: the original string, the substring to be replaced, and the substring to replace it with. If the specified substring is found in the original string, `REPLACE` returns the modified string with all instances of the old substring replaced by the new one. If the substring is not found, the original string is returned unchanged. This function is particularly useful for data cleaning tasks, such as correcting typos, standardizing formats, or replacing obsolete data.
**Synopsis** Learn more from the following resources:
`REPLACE(input_string, string_to_replace, replacement_string)` - [@article@SQL REPLACE Function](https://www.w3schools.com/sql/func_sqlserver_replace.asp)
- [@article@How to use the SQL REPLACE Function](https://www.datacamp.com/tutorial/sql-replace)
**Parameters**
- `input_string`: This is the original string where you want to replace some characters.
- `string_to_replace`: This is the string that will be searched for in the original string.
- `replacement_string`: This is the string that will replace the `string_to_replace` in the original string.
The `REPLACE()` function is handy when it comes to manipulating and modifying data in various ways, particularly when used in combination with other SQL data-manipulation functions.
**Examples**
Suppose we have the following table, `Employees`:
| EmpId | EmpName |
|-------|---------------------|
| 1 | John Doe |
| 2 | Jane Doe |
| 3 | Jim Smith Doe |
| 4 | Jennifer Doe Smith |
Here's how you can use the `REPLACE()` function:
```sql
SELECT EmpId, EmpName,
REPLACE(EmpName, 'Doe', 'Roe') as ModifiedName
FROM Employees;
```
After the execution of the above SQL, we will receive:
| EmpId | EmpName | ModifiedName |
|-------|--------------------|---------------------|
| 1 | John Doe | John Roe |
| 2 | Jane Doe | Jane Roe |
| 3 | Jim Smith Doe | Jim Smith Roe |
| 4 | Jennifer Doe Smith | Jennifer Roe Smith |
You can see that all occurrences of 'Doe' are replaced with 'Roe'.

@ -1,63 +1,8 @@
# RIGHT JOIN # RIGHT JOIN
The `RIGHT JOIN` keyword returns all records from the right table (table2), and the matched records from the left table (table1). If there is no match, the result is `NULL` on the left side. A `RIGHT JOIN` in SQL is a type of outer join that returns all rows from the right (second) table and the matching rows from the left (first) table. If there's no match in the left table, `NULL` values are returned for the left table's columns. This join type is less commonly used than LEFT JOIN but is particularly useful when you want to ensure all records from the second table are included in the result set, regardless of whether they have corresponding matches in the first table. `RIGHT JOIN` is often used to identify missing relationships or to include all possible values from a lookup table.
## Syntax Learn more from the following resources:
Below is the common syntax used for writing a `RIGHT JOIN`: - [@article@SQL RIGHT JOIN](https://www.w3schools.com/sql/sql_join_right.asp)
- [@article@SQL RIGHT JOIN With Examples](https://www.programiz.com/sql/right-join)
```sql
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
```
## Example
Consider two tables:
**Table "Orders":**
| OrderID | CustomerID | OrderDate |
|--|--|--|
| 1 | 3 | 2017/11/11 |
| 2 | 1 | 2017/10/23 |
| 3 | 2 | 2017/9/15 |
| 4 | 4 | 2017/9/03 |
**Table "Customers":**
| CustomerID | CustomerName | ContactName | Country |
|--|--|--|--|
| 1 | Alfreds Futterkiste | Maria Anders | Germany |
| 2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Mexico |
| 3 | Antonio Moreno Taquería | Antonio Moreno | Mexico |
| 5 | Berglunds snabbköp | Christina Berglund | Sweden |
Now, we want to select all customers and any matching records in orders table. If there is no match, the result is null in order table:
```sql
SELECT
Customers.CustomerName,
Orders.OrderID
FROM
Orders
RIGHT JOIN
Customers
ON
Orders.CustomerID = Customers.CustomerID;
```
**Result:**
| CustomerName | OrderID |
|--|--|
| Alfreds Futterkiste | 2 |
| Ana Trujillo Emparedados y helados | 3 |
| Antonio Moreno Taquería | 1 |
| Berglunds snabbköp | NULL |
| Around the Horn | NULL |
| Bottom-Dollar Markets | NULL |
As you can see, the `RIGHT JOIN` keyword returned all the records from the Customers table and all matched records from the Orders table. For those customers who have no orders (like "Berglunds snabbköp"), the result is `NULL`.

@ -1,49 +1,8 @@
# ROLLBACK # ROLLBACK
The `ROLLBACK` command is a transactional control language (TCL) instruction that undoes an unsuccessful or unsatisfactory running transaction. This process also applies to SQL Server where all individual statements in SQL Server are treated as a single atomic transaction. `ROLLBACK` is a SQL command used to undo transactions that have not yet been committed to the database. It reverses all changes made within the current transaction, restoring the database to its state before the transaction began. This command is crucial for maintaining data integrity, especially when errors occur during a transaction or when implementing conditional logic in database operations. `ROLLBACK` is an essential part of the ACID (Atomicity, Consistency, Isolation, Durability) properties of database transactions, ensuring that either all changes in a transaction are applied, or none are, thus preserving data consistency.
When a `ROLLBACK` command is issued, all the operations (such as Insert, Delete, Update, etc.) are undone and the database is restored to its initial state before the transaction started. Learn more from the following resources:
## When to use `ROLLBACK` - [@video@How to undo a mistake a in SQL: Rollback and Commit](https://www.youtube.com/watch?v=jomsdMLiIZM)
- [@article@Difference between COMMIT and ROLLBACK in SQL](https://byjus.com/gate/difference-between-commit-and-rollback-in-sql/)
1. If the transaction is unacceptable or unsuccessful.
2. If you want to revert the unwanted changes.
Here is a basic example:
```sql
BEGIN TRANSACTION;
-- This would delete all rows from the table.
DELETE FROM Employee;
-- Oh no! That's not what I wanted. Let's roll that back.
ROLLBACK;
```
In this example, the `ROLLBACK` command would restore all deleted data into the `Employee` table.
SQL also allows the usage of `SAVEPOINT`s along with the `ROLLBACK` command, which allows rolling back to a specific point in a transaction, instead of rolling back the entire transaction.
Here is an example of using `SAVEPOINT`s:
```sql
BEGIN TRANSACTION;
-- Adding new employee.
INSERT INTO Employee(ID, Name) VALUES(1, 'John');
-- Create a savepoint to be able to roll back to this point.
SAVEPOINT SP1;
-- Oh no! I made a mistake creating this employee. Let's roll back to the savepoint.
ROLLBACK TO SAVEPOINT SP1;
-- Now I can try again.
INSERT INTO Employee(ID, Name) VALUES(1, 'Jack');
-- Commit the changes.
COMMIT;
```
In this example, `ROLLBACK TO SAVEPOINT SP1` would undo the first insert into the `Employee` table while preserving the state of the database as it was at the savepoint `SP1`. So, the second insert command would properly add 'Jack' in place of 'John'.

@ -1,45 +1,8 @@
# ROUND # ROUND
The `ROUND` function in SQL is used to round a numeric field to the nearest specified decimal or integer. The `ROUND` function in SQL is used to round a numeric value to a specified number of decimal places. It takes two arguments: the number to be rounded and the number of decimal places to round to. If the second argument is omitted, the function rounds the number to the nearest whole number. For positive values of the second argument, the number is rounded to the specified decimal places; for negative values, it rounds to the nearest ten, hundred, thousand, etc. The `ROUND` function is useful for formatting numerical data for reporting or ensuring consistent precision in calculations.
Most usually, `ROUND` accepts two arguments. The first one is the value that needs to be rounded, and the second is the number of decimal places to which the first argument will be rounded off. When dealing with decimals, SQL will round up when the number after the decimal point is 5 or higher, whereas it will round down if it's less than 5. Learn more from the following resources:
## Syntax - [@article@SQL ROUND](https://www.w3schools.com/sql/func_sqlserver_round.asp)
- [@article@What is the SQL ROUND Function and how does it work?](https://www.datacamp.com/tutorial/mastering-sql-round)
The basic syntax for `ROUND` can be described as follows:
```sql
ROUND ( numeric_expression, length [ , function ] )
```
- `numeric_expression`: A floating point number to round.
- `length`: The precision to which `numeric_expression` is to be rounded. When `length` is a positive number, rounding affects the right side of the decimal point. If `length` is negative, rounding affects the left side of the decimal point.
- `function`: Optional parameter to determine the operation to perform. If this is omitted or 0, the `numeric_expression` is rounded. If this is 1, the `numeric_expression` is truncated.
## Example 1:
Round off a decimal to the nearest whole number.
```sql
SELECT ROUND(125.215);
```
This will result in `125`.
## Example 2:
Round off a number to a specified decimal place.
```sql
SELECT ROUND(125.215, 1);
```
This will result in `125.2` as the second decimal place (5) is less than 5.
## Example 3:
Round off the left side of the decimal.
```sql
SELECT ROUND(125.215, -2);
```
This will result in `100` as rounding now affects digits before the decimal point.
Whenever you need to round off numeric data in SQL, the `ROUND` function is a valuable tool to have in your kit. It proficiently handles both positive and negative rounding, and its simple syntax makes it extremely user-friendly.

@ -1,43 +1,8 @@
# Row # Row
In SQL, a "row" refers to a record in a table. Each row in a table represents a set of related data, and every row in the table has the same structure. In SQL, a row (also called a record or tuple) represents a single, implicitly structured data item in a table. Each row contains a set of related data elements corresponding to the table's columns. Rows are fundamental to the relational database model, allowing for the organized storage and retrieval of information. Operations like INSERT, UPDATE, and DELETE typically work at the row level.
For instance, in a table named "customers", a row may represent one customer, with columns containing information like ID, name, address, email, etc. Learn more from the following resources:
Here is a conceptual SQL table: - [@article@Row - Database](https://en.wikipedia.org/wiki/Row_(database))
- [@article@Database Row: Definition, Examples](https://www.devx.com/terms/database-row/)
| ID | NAME | ADDRESS | EMAIL |
|----|------|---------|-------|
| 1 | John | NY | john@example.com |
| 2 | Jane | LA | jane@example.com |
| 3 | Jim | Chicago | jim@example.com |
Each of these line of data is referred to as a 'row' in the SQL table.
To select a row, you would use a `SELECT` statement. Here's an example of how you might select a row:
```sql
SELECT *
FROM customers
WHERE ID = 1;
```
This would output:
| ID | Name | ADDRESS | Email |
|---|------|---------|--------|
| 1 | John | NY | john@example.com |
The `*` in the statement refers to all columns. If you want to only select specific columns, you can replace `*` with the column name(s):
```sql
SELECT NAME, EMAIL
FROM customers
WHERE ID = 1;
```
In this case, the output would be:
| Name | Email |
|-----|--------|
| John | john@example.com |

@ -1,43 +1,8 @@
# Row_number # Row_number
**ROW_NUMBER()** is a SQL window function that assigns a unique number to each row in the result set. ROW_NUMBER() is a SQL window function that assigns a unique, sequential integer to each row within a partition of a result set. It's useful for creating row identifiers, implementing pagination, or finding the nth highest/lowest value in a group. The numbering starts at 1 for each partition and continues sequentially, allowing for versatile data analysis and manipulation tasks.
Syntax: Learn more from the following resources:
```sql - [@article@SQL ROW_NUMBER](https://www.sqltutorial.org/sql-window-functions/sql-row_number/)
ROW_NUMBER() OVER ( - [@article@How to Use ROW_NUMBER OVER() in SQL to Rank Data](https://learnsql.com/blog/row-number-over-in-sql/)
[ORDER BY column_name]
)
```
## Features:
- Numbers are assigned based on the `ORDER BY` clause of `ROW_NUMBER()`.
- In case of identical values in the `ORDER BY` clause, the function assigns numbers arbitrarily.
- In other words, the sequence of numbers generated by `ROW_NUMBER()` is not guaranteed to be the same for the same set of data.
## Examples:
**Example 1:** Basic usage of ROW_NUMBER() on a single column
```sql
SELECT
name,
ROW_NUMBER() OVER (ORDER BY name) row_number
FROM
employees;
```
In this example, `ROW_NUMBER()` is used to assign a unique number to each row in the employees table, ordered by the employee names alphabetically.
**Example 2:** Using ROW_NUMBER() to rank rows in each partition
```sql
SELECT
department_id,
first_name,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC) row_number
FROM
employees;
```
In this example, `ROW_NUMBER()` is used to rank employee salaries within each department (i.e., partitioned by `department_id`). In each department, employees with higher salaries are assigned lower row numbers.

@ -1,58 +1,8 @@
# SAVEPOINT # SAVEPOINT
A savepoint is a way of implementing subtransactions (nested transactions) within a relational database management system by indicating a particular point within a transaction that a user can "roll back" to in case of failure. The main property of a savepoint is that it enables you to create a rollback segment within a transaction. This allows you to revert the changes made to the database after the Savepoint without having to discard the entire transaction. A `SAVEPOINT` in SQL is a point within a transaction that can be referenced later. It allows for more granular control over transactions by creating intermediate points to which you can roll back without affecting the entire transaction. This is particularly useful in complex transactions where you might want to undo part of the work without discarding all changes. `SAVEPOINT` enhances transaction management flexibility.
A Savepoint might be used in instances where if a particular operation fails, you would like to revert the database to the state it was in before the operation was attempted, but you do not want to give up on the entire transaction. Learn more from the following resources:
## Savepoint Syntax - [@article@SQL SAVEPOINT](https://www.ibm.com/docs/pl/informix-servers/12.10?topic=statements-savepoint-statement)
- [@video@DBMS - Save Point](https://www.youtube.com/watch?v=30ldSUkswGM)
The general syntax for `SAVEPOINT`:
```sql
SAVEPOINT savepoint_name;
```
## Use of Savepoint
Here is the basic usage of savepoint:
```sql
START TRANSACTION;
INSERT INTO Table1 (Column1) VALUES ('Value1');
SAVEPOINT SP1;
INSERT INTO Table1 (Column1) VALUES ('Value2');
ROLLBACK TO SP1;
COMMIT;
```
In this example, an initial `INSERT` statement is performed before a Savepoint named `SP1` is created. Another `INSERT` statement is called and then `ROLLBACK TO SP1` is executed. This means all changes between the creation of `SP1` and `ROLLBACK TO SP1` are reverted. After that, 'COMMIT' is used to permanently store the changes made by the first `INSERT` statement.
## Release Savepoint
The `RELEASE SAVEPOINT` deletes a savepoint within a transaction.
Here’s the syntax:
```sql
RELEASE SAVEPOINT savepoint_name;
```
The action of releasing a savepoint removes the named savepoint from the set of savepoints of the current transaction. No changes are undone.
## Remove Savepoint
The `ROLLBACK TO SAVEPOINT` removes a savepoint within a transaction.
Here’s the syntax:
```sql
ROLLBACK TRANSACTION TO savepoint_name;
```
This statement rolls back a transaction to the named savepoint without terminating the transaction.
Please note, savepoint names are not case sensitive and must obey the syntax rules of the server.

@ -1,74 +1,8 @@
# Scalar # Scalar
In SQL, a scalar type is a type that holds a single value as opposed to composite types that hold multiple values. In simpler terms, scalar types represent a single unit of data. A scalar value is a single data item, as opposed to a set or array of values. Scalar subqueries are queries that return exactly one column and one row, often used in `SELECT` statements, `WHERE` clauses, or as part of expressions. Scalar functions in SQL return a single value based on input parameters. Understanding scalar concepts is crucial for writing efficient and precise SQL queries.
Some common examples of scalar types in SQL include: Learn more from the following resources:
- Integers (`INT`) - [@video@Using Scalar SQL to boost performance](https://www.youtube.com/watch?v=v8X5FGzzc9A)
- Floating-point numbers (`FLOAT`) - [@article@Creating SQL Scalar Functions](https://www.ibm.com/docs/en/db2/11.5?topic=functions-creating-sql-scalar)
- Strings (`VARCHAR`, `CHAR`)
- Date and Time (`DATE`, `TIME`)
- Boolean (`BOOL`)
## Examples
Here is how you can define different scalar types in SQL:
## Integers
An integer can be defined using the INT type. Here is an example of how to declare an integer:
```sql
CREATE TABLE Employees (
EmployeeID INT,
FirstName VARCHAR(50),
LastName VARCHAR(50)
);
```
## Floating-Point Numbers
Floating-point numbers can be defined using the FLOAT or REAL type. Here is an example of how to declare a floating-point number:
```sql
CREATE TABLE Products (
ProductID INT,
Price FLOAT
);
```
## Strings
Strings can be defined using the CHAR, VARCHAR, or TEXT type. Here is an example of how to declare a string:
```sql
CREATE TABLE Employees (
EmployeeID INT,
FirstName VARCHAR(50),
LastName VARCHAR(50)
);
```
## Date and Time
The DATE, TIME or DATETIME type can be used to define dates and times:
```sql
CREATE TABLE Orders (
OrderID INT,
OrderDate DATE
);
```
## Boolean
Booleans can be declared using the BOOL or BOOLEAN type. They hold either `TRUE` or `FALSE`.
```sql
CREATE TABLE Employees (
EmployeeID INT,
IsActive BOOL
);
```
Remember, the way these types are declared might slightly differ based on the SQL dialect you are using. It's crucial to refer to the specific documentation of the SQL flavor you're working with for the precise syntax and behavior.

@ -1,77 +1,8 @@
# SELECT # SELECT
The `SELECT` statement in SQL is majorly used for fetching data from the database. It is one of the most essential elements of SQL. SELECT is one of the most fundamental SQL commands, used to retrieve data from one or more tables in a database. It allows you to specify which columns to fetch, apply filtering conditions, sort results, and perform various operations on the data. The SELECT statement is versatile, supporting joins, subqueries, aggregations, and more, making it essential for data querying and analysis in relational databases.
## Syntax Learn more from the following resources:
Here's how your `SELECT` command will look like: - [@article@SQL_Select](https://www.w3schools.com/sql/sql_select.asp)
```sql
SELECT column1, column2, ...
FROM table_name;
```
If you want to select all the columns of a table, you can use `*` like this:
```sql
SELECT * FROM table_name;
```
## Example
For instance, consider we have a table `EMPLOYEES` with columns `name`, `designation`, and `salary`. We can use `SELECT` in the following way:
```sql
SELECT name, designation FROM EMPLOYEES;
```
This will retrieve all the names and designations of all employees from the table `EMPLOYEES`.
## SELECT DISTINCT
The `SELECT DISTINCT` statement is used to return only distinct (different) values. The DISTINCT keyword eliminates duplicate records from the results.
Here's how you can use it:
```sql
SELECT DISTINCT column1, column2, ...
FROM table_name;
```
For example, if we want to select all unique designations from the `EMPLOYEES` table, the query will look like this:
```sql
SELECT DISTINCT designation FROM EMPLOYEES;
```
## SELECT WHERE
`SELECT` statement combined with `WHERE` gives us the ability to filter records based on a condition.
Syntax:
```sql
SELECT column1, column2, ...
FROM table_name
WHERE condition;
```
For example, to select employees with salary more than 50000, you can use this query:
```sql
SELECT * FROM EMPLOYEES WHERE salary > 50000;
```
## SELECT ORDER BY
Using `SELECT` statement in conjunction with `ORDER BY`, we can sort the result-set in ascending or descending order.
Syntax:
```sql
SELECT column1, column2, ...
FROM table_name
ORDER BY column ASC|DESC;
```
For example, to select all employees and order them by their name in ascending fashion:
```sql
SELECT * FROM EMPLOYEES ORDER BY name ASC;
```
Remember that the default sort order is ascending if the ASC|DESC parameter is not defined.

@ -1,10 +1,6 @@
# SELECT statement # SELECT statement
The SELECT statement in SQL is used to retrieve data from a database. It allows you to specify the columns you want to fetch from a particular table or a combination of tables. Here’s a basic syntax of a SELECT statement: SELECT is one of the most fundamental SQL commands, used to retrieve data from one or more tables in a database. It allows you to specify which columns to fetch, apply filtering conditions, sort results, and perform various operations on the data. The SELECT statement is versatile, supporting joins, subqueries, aggregations, and more, making it essential for data querying and analysis in relational databases.
'''sql
SELECT * FROM employees;
'''
Learn more from the following resources: Learn more from the following resources:

@ -1,27 +1,3 @@
# Selective Projection # Selective Projection
Selective projection in SQL is a concept related to retrieving only specific columns from a table rather than retrieving all columns. It's one of the most basic ways to optimize your queries in SQL and make them more efficient. Selective projection in SQL refers to the practice of choosing only specific columns (attributes) from a table or query result, rather than selecting all available columns. This technique is crucial for optimizing query performance and reducing unnecessary data transfer. By using SELECT with explicitly named columns instead of `SELECT *`, developers can improve query efficiency and clarity, especially when dealing with large tables or complex joins.
In SQL, a projection refers to the operation in which we choose certain columns (instead of all columns) from the table for our query results. If a table has numerous columns, and we only need data from a few of them, it's more efficient to only select those specific columns in the SQL query. This reduces the amount of data that needs to be scanned and fetched from the database, thereby improving performance.
## Examples
Let's take an example where you have a "students" table with the following columns: Id, Name, Age, Gender, Department, and City. If you only need Name and Department information, you should use a selective projection to specify only these columns in your SELECT statement:
```sql
SELECT Name, Department
FROM students
```
This query returns just the Name and Department columns, rather than all fields in the students table.
In contrast, if you used a `SELECT *` statement:
```sql
SELECT *
FROM students
```
This would return all columns from the "students" table which can be inefficient if you don't need all that data.
Selective projection can greatly optimize your SQL queries by minimizing the amount of data handled. It's especially beneficial when tables have large amounts of data and many columns, but only a subset of information is required.

@ -4,41 +4,7 @@ A `SELF JOIN` is a standard SQL operation where a table is joined to itself. Thi
It's important to note that, since it's a join operation on the same table, alias(es) for table(s) must be used to avoid confusion during the join operation. It's important to note that, since it's a join operation on the same table, alias(es) for table(s) must be used to avoid confusion during the join operation.
## Syntax of a Self Join Learn more from the following resources:
Here is the basic syntax for a `SELF JOIN` statement: - [@article@Understanding the Self Joins in SQL](https://www.dbvis.com/thetable/understanding-self-joins-in-sql/)
- [@article@SQL self joins](https://www.w3schools.com/sql/sql_join_self.asp)
```sql
SELECT a.column_name, b.column_name
FROM table_name AS a, table_name AS b
WHERE a.common_field = b.common_field;
```
In this query:
- `table_name`: is the name of the table to join to itself.
- `a` and `b`: are different aliases for the same table.
- `column_name`: specify the columns that should be returned as a result of the SQL `SELF JOIN` statement.
- `WHERE a.common_field = b.common_field`: is the condition for the join.
## Example of a Self Join
Let us consider a `EMPLOYEES` table with the following structure:
| EmployeeID | Name | ManagerID |
|------------|-------|-----------|
| 1 | Sam | NULL |
| 2 | Alex | 1 |
| 3 | John | 1 |
| 4 | Sophia| 2 |
| 5 | Emma | 2 |
If you want to find out all the employees and who their manager is, you can do so using a `SELF JOIN`:
```sql
SELECT a.Name AS Employee, b.Name AS Manager
FROM EMPLOYEES a, EMPLOYEES b
WHERE a.ManagerID = b.EmployeeID;
```
This query will return the name of each employee along with the name of their respective manager.

@ -1,60 +1,8 @@
# SQL keywords # SQL keywords
SQL employs a number of standard command keywords that are integral to interact with databases. Keywords in SQL provide SQL keywords are reserved words that have special meanings within SQL statements. These include commands (like `SELECT`, `INSERT`, `UPDATE`), clauses (such as `WHERE`, `GROUP BY`, `HAVING`), and other syntax elements that form the structure of SQL queries. Understanding SQL keywords is fundamental to writing correct and effective database queries. Keywords are typically case-insensitive but are often written in uppercase by convention for better readability.
instructions as to what action should be performed.
Here are some of the primary SQL keywords: Learn more from the following resources:
**SELECT**: This keyword retrieves data from a database. For example, - [@article@SQL Keywords Reference](https://www.w3schools.com/sql/sql_ref_keywords.asp)
- [@article@SQL Keywords, Operators and Statements](https://blog.hubspot.com/website/sql-keywords-operators-statements)
```sql
SELECT * FROM Customers;
```
In the above statement `*` indicates that all records should be retrieved from the `Customers` table.
**FROM**: Used in conjunction with `SELECT` to specify the table from which to fetch data.
**WHERE**: Used to filter records. Incorporating a WHERE clause, you might specify conditions that must be met. For
example,
```sql
SELECT * FROM Customers WHERE Country='Germany';
```
**INSERT INTO**: This command is used to insert new data into a database.
```sql
INSERT INTO Customers (CustomerID, CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway');
```
**UPDATE**: This keyword updates existing data within a table. For example,
```sql
UPDATE Customers SET ContactName='Alfred Schmidt', City='Frankfurt' WHERE CustomerID=1;
```
**DELETE**: This command removes one or more records from a table. For example,
```sql
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
```
**CREATE DATABASE**: As implied by its name, this keyword creates a new database.
```sql
CREATE DATABASE mydatabase;
```
**ALTER DATABASE**, **DROP DATABASE**, **CREATE TABLE**, **ALTER TABLE**, **DROP TABLE**: These keywords are used to
modify databases and tables.
Remember that SQL is not case sensitive, meaning keywords can be written in lower case. The convention is to write them
in ALL CAPS for readability. There are many more keywords in SQL, but these are some of the most common.
Learn more about SQL from the following resources:
- [@article@SQL Tutorial - Mode](https://mode.com/sql-tutorial/)
- [@article@SQL Tutorial](https://www.sqltutorial.org/)
- [@article@SQL Tutorial - W3Schools](https://www.w3schools.com/sql/default.asp)

@ -1,46 +1,8 @@
# SQL vs NoSQL # SQL vs NoSQL
When discussing databases, it's essential to understand the difference between SQL and NoSQL databases, as each has its own set of advantages and limitations. In this section, we'll briefly compare and contrast the two, so you can determine which one suits your needs better. SQL (relational) and NoSQL (non-relational) databases represent two different approaches to data storage and retrieval. SQL databases use structured schemas and tables, emphasizing data integrity and complex queries through joins. NoSQL databases offer more flexibility in data structures, often sacrificing some consistency for scalability and performance. The choice between SQL and NoSQL depends on factors like data structure, scalability needs, consistency requirements, and the nature of the application.
## SQL Databases Learn more from the following resources:
SQL (Structured Query Language) databases are also known as relational databases. They have a predefined schema, and data is stored in tables consisting of rows and columns. SQL databases follow the ACID (Atomicity, Consistency, Isolation, Durability) properties to ensure reliable transactions. Some popular SQL databases include MySQL, PostgreSQL, and Microsoft SQL Server. - [@article@Understanding SQL vs NoSQL Databases](https://www.mongodb.com/resources/basics/databases/nosql-explained/nosql-vs-sql)
- [@video@SQL vs NoSQL Databases in 4 mins](https://www.youtube.com/watch?v=_Ss42Vb1SU4)
**Advantages of SQL databases:**
- **Predefined schema**: Ideal for applications with a fixed structure.
- **ACID transactions**: Ensures data consistency and reliability.
- **Support for complex queries**: Rich SQL queries can handle complex data relationships and aggregation operations.
- **Scalability**: Vertical scaling by adding more resources to the server (e.g., RAM, CPU).
**Limitations of SQL databases:**
- **Rigid schema**: Data structure updates are time-consuming and can lead to downtime.
- **Scaling**: Difficulties in horizontal scaling and sharding of data across multiple servers.
- **Not well-suited for hierarchical data**: Requires multiple tables and JOINs to model tree-like structures.
## NoSQL Databases
NoSQL (Not only SQL) databases refer to non-relational databases, which don't follow a fixed schema for data storage. Instead, they use a flexible and semi-structured format like JSON documents, key-value pairs, or graphs. MongoDB, Cassandra, Redis, and Couchbase are some popular NoSQL databases.
**Advantages of NoSQL databases:**
- **Flexible schema**: Easily adapts to changes without disrupting the application.
- **Scalability**: Horizontal scaling by partitioning data across multiple servers (sharding).
- **Fast**: Designed for faster read and writes, often with a simpler query language.
- **Handling large volumes of data**: Better suited to managing big data and real-time applications.
- **Support for various data structures**: Different NoSQL databases cater to various needs, like document, graph, or key-value stores.
**Limitations of NoSQL databases:**
- **Limited query capabilities**: Some NoSQL databases lack complex query and aggregation support or use specific query languages.
- **Weaker consistency**: Many NoSQL databases follow the BASE (Basically Available, Soft state, Eventual consistency) properties that provide weaker consistency guarantees than ACID-compliant databases.
## MongoDB: A NoSQL Database
This guide focuses on MongoDB, a popular NoSQL database that uses a document-based data model. MongoDB has been designed with flexibility, performance, and scalability in mind. With its JSON-like data format (BSON) and powerful querying capabilities, MongoDB is an excellent choice for modern applications dealing with diverse and large-scale data.
- [@article@SQL vs NoSQL: The Differences](https://www.sitepoint.com/sql-vs-nosql-differences/)
- [@article@SQL vs. NoSQL Databases: What’s the Difference?](https://www.ibm.com/blog/sql-vs-nosql/)
- [@article@NoSQL vs. SQL Databases](https://www.mongodb.com/nosql-explained/nosql-vs-sql)
- [@feed@Explore top posts about NoSQL](https://app.daily.dev/tags/nosql?ref=roadmapsh)

@ -1,60 +1,7 @@
# Stored Procedures and Functions # Stored Procedures and Functions
A SQL stored procedure is a set of SQL code that can be saved and reused. In other words, it's a precompiled object because it's compiled at a time when it's created on the database. Stored procedures can take parameters, process the tasks or query the database, and return a result. Stored procedures and functions are precompiled database objects that encapsulate a set of SQL statements and logic. Stored procedures can perform complex operations and are typically used for data manipulation, while functions are designed to compute and return values. Both improve performance by reducing network traffic and allowing code reuse. They also enhance security by providing a layer of abstraction between the application and the database.
Here's a basic example: Learn more from the following resources:
```sql - [@article@Stored Procedure vs Functions](https://www.shiksha.com/online-courses/articles/stored-procedure-vs-function-what-are-the-differences/)
CREATE PROCEDURE getEmployeesBySalary
@minSalary int
AS
BEGIN
SELECT firstName, lastName
FROM Employees
WHERE salary > @minSalary
END
GO
```
To call this stored procedure, we would use:
```sql
EXEC getEmployeesBySalary 50000
```
## Functions
A SQL function is a set of SQL statements that perform a specific task. Functions must return a value or result. We can use these functions in SELECT, INSERT, DELETE, UPDATE statements.
There are two types of functions in SQL:
- **Scalar functions**, which return a single value and can be used where single expressions are used. For instance:
```sql
CREATE FUNCTION addNumbers(@a int, @b int)
RETURNS int
AS
BEGIN
RETURN @a + @b
END
```
- **Table-valued functions**, which return a table. They can be used in JOIN clauses as if they were a normal table. For example:
```sql
CREATE FUNCTION getBooks (@authorID INT)
RETURNS TABLE
AS
RETURN (
SELECT books.title, books.publicationYear
FROM books
WHERE books.authorID = @authorID
)
```
To call this function:
```sql
SELECT title, publicationYear
FROM getBooks(3)
```

@ -1,60 +1,8 @@
# Sub Queries # Sub Queries
In SQL, a subquery is a query embedded within another SQL query. You can alternately call it a nested or an inner query. The containing query is often referred to as the outer query. Subqueries are utilized to retrieve data that will be used in the main query as a condition to further restrict the data to be retrieved. Subqueries, also known as nested queries or inner queries, are SQL queries embedded within another query. They can be used in various parts of SQL statements, such as SELECT, FROM, WHERE, and HAVING clauses. Subqueries allow for complex data retrieval and manipulation by breaking down complex queries into more manageable parts. They're particularly useful for creating dynamic criteria, performing calculations, or comparing sets of results.
Subqueries can be used in various parts of a query, including: Learn more from the following resources:
- **SELECT** statement - [@article@SQL Sub Queries](https://www.tutorialspoint.com/sql/sql-sub-queries.htm)
- **FROM** clause - [@video@Advanced SQL Tutorial | Subqueries](https://www.youtube.com/watch?v=m1KcNV-Zhmc)
- **WHERE** clause
- **GROUP BY** clause
- **HAVING** clause
## Syntax
In general, the syntax can be written as:
```sql
SELECT column_name [, column_name]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name]
FROM table1 [, table2 ]
[WHERE])
```
## Types of Subqueries
1. **Scalar Subquery**: It returns single value.
```sql
SELECT name
FROM student
WHERE roll_id = (SELECT roll_id FROM student WHERE name='John');
```
2. **Row subquery**: It returns a single row or multiple rows of two or more values.
```sql
SELECT * FROM student
WHERE (roll_id, age)=(SELECT MIN(roll_id),MIN(age) FROM student);
```
3. **Column subquery**: It returns single column value with multiple rows and one column.
```sql
SELECT name, age FROM student
WHERE name in (SELECT name FROM student);
```
4. **Table subquery**: It returns more than one row and more than one column.
```sql
SELECT name, age
FROM student
WHERE (name, age) IN (SELECT name, age FROM student);
```
## General Note
Subqueries can be either correlated or uncorrelated. A correlated subquery is a subquery that uses values from the outer query. Conversely, an uncorrelated subquery is a subquery that can be run independently of the outer query.

@ -1,61 +1,8 @@
# SUBSTRING # SUBSTRING
The SQL `SUBSTRING` function is used to extract a part of a string, where you can specify the start position and the length of the text. This function can be very beneficial when you only need a specific part of a string. SUBSTRING is a SQL function used to extract a portion of a string. It allows you to specify the starting position and length of the substring you want to extract. This function is valuable for data manipulation, parsing, and formatting tasks. The exact syntax may vary slightly between database systems, but the core functionality remains consistent, making it a versatile tool for working with string data in databases.
## Syntax Learn more from the following resources:
The standardized SQL syntax for `SUBSTRING` is as follows: - [@video@Advanced SQL Tutorial | String Functions + Use Cases](https://www.youtube.com/watch?v=GQj6_6V_jVA)
- [@article@SQL SUBSTRING](https://www.w3schools.com/sql/func_sqlserver_substring.asp)
```sql
SUBSTRING(string, start, length)
```
Where:
- `string` is the source string from which you want to extract.
- `start` is the position to start extraction from. The first position in the string is always 1.
- `length` is the number of characters to extract.
## Usage
For instance, if you want to extract the first 5 characters from the string 'Hello World':
```sql
SELECT SUBSTRING('Hello World', 1, 5) as ExtractedString;
```
Result:
```sql
| ExtractedString |
| --------------- |
| Hello |
```
You can also use `SUBSTRING` on table columns, like so:
```sql
SELECT SUBSTRING(column_name, start, length) FROM table_name;
```
## SUBSTRING with FROM and FOR
In some database systems (like PostgreSQL and SQL Server), the `SUBSTRING` function uses a different syntax:
```sql
SUBSTRING(string FROM start FOR length)
```
This format functions the same way as the previously mentioned syntax.
For example:
```sql
SELECT SUBSTRING('Hello World' FROM 1 FOR 5) as ExtractedString;
```
This would yield the same result as the previous example - 'Hello'.
## Note
SQL is case-insensitive, meaning `SUBSTRING`, `substring`, and `Substring` will all function the same way.

@ -1,58 +1,8 @@
# SUM # SUM
The `SUM()` function in SQL is used to calculate the sum of a column. This function allows you to add up a column of numbers in an SQL table. SUM is an aggregate function in SQL used to calculate the total of a set of values. It's commonly used with numeric columns in combination with GROUP BY clauses to compute totals for different categories or groups within the data. SUM is essential for financial calculations, statistical analysis, and generating summary reports from database tables. It ignores NULL values and can be used in conjunction with other aggregate functions for complex data analysis.
The syntax for SUM is as follows: Learn more from the following resources:
```sql - [@article@SQL SUM Function](https://www.w3schools.com/sql/sql_sum.asp)
SELECT SUM(column_name) FROM table_name; - [@article@SQL SUM](https://www.studysmarter.co.uk/explanations/computer-science/databases/sql-sum/)
```
Where `column_name` is the name of the column you want to calculate the sum of, and `table_name` is the name of the table where the column is.
For example, consider the following `ORDER` table:
```
| OrderID | Company | Quantity |
|------------|---------|----------|
| 1 | A | 30 |
| 2 | B | 15 |
| 3 | A | 20 |
```
If you want to find the total quantity, you can use `SUM()`:
```sql
SELECT SUM(Quantity) AS TotalQuantity FROM Order;
```
Output will be:
```
| TotalQuantity |
|---------------|
| 65 |
```
**Note:** The `SUM()` function skips NULL values.
One of the common use cases of `SUM()` function is in conjunction with `GROUP BY` to get the sum for each group of rows.
Example:
```sql
SELECT Company, SUM(Quantity) AS TotalQuantity
FROM Order
GROUP BY Company;
```
This will give us the sum of `Quantity` for each `Company` in the `Order` table.
```
| Company | TotalQuantity |
|-----------|----------------|
| A | 50 |
| B | 15 |
```
Notably, in all databases, including MySQL, PostgreSQL, and SQLite, the `SUM()` function operates the same way.

@ -1,48 +1,8 @@
# Table # Table
In SQL, a table is a collection of related data held in a structured format within a database. It consists of rows (records) and columns (fields). A table is a fundamental structure for organizing data in a relational database. It consists of rows (records) and columns (fields), representing a collection of related data entries. Tables define the schema of the data, including data types and constraints. They are the primary objects for storing and retrieving data in SQL databases, and understanding table structure is crucial for effective database design and querying.
A table is defined by its name and the nature of data it will hold, i.e., each field has a name and a specific data type. Learn more from the following resources:
## Table Creation - [@article@Table (Database)](https://en.wikipedia.org/wiki/Table_(database))
- [@article@Introduction to Tables](https://support.microsoft.com/en-gb/office/introduction-to-tables-78ff21ea-2f76-4fb0-8af6-c318d1ee0ea7)
You can create a table using the `CREATE TABLE` SQL statement. The syntax is as follows:
```sql
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
```
Here, `table_name` is the name of the table, `column1`, `column2`... are the names of the columns, and `datatype` specifies the type of data the column can hold (e.g., varchar, integer, date, etc.).
## Table Manipulation
Once a table has been created, the `INSERT INTO` statement is used to insert new rows of data into the table.
```sql
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...);
```
The `SELECT` statement is used to select data from the table.
```sql
SELECT column1, column2,...
FROM table_name;
```
The `UPDATE` statement is used to modify existing records.
```sql
UPDATE table_name
SET column1 = value1, column2 = value2,...
WHERE condition;
```
And, finally, the `DELETE` statement is used to delete existing records.
```sql
DELETE FROM table_name WHERE condition;
```
These basic operations allow for full manipulation of tables in SQL, letting users to manage their data effectively.

@ -1,65 +1,6 @@
# TIME # TIME
In SQL, TIME data type is used to store time values in the database. It allows you to store hours, minutes, and seconds. The format of a TIME is 'HH:MI:SS'. The TIME data type in SQL is used to store time values, typically in the format of hours, minutes, and seconds. It's useful for recording specific times of day without date information. SQL provides various functions for manipulating and comparing TIME values, allowing for time-based calculations and queries. The exact range and precision of TIME can vary between different database management systems.
## Syntax Learn more from the following resources:
Here is the basic syntax to create a field with TIME data type in SQL:
```sql
CREATE TABLE table_name (
column_name TIME
);
```
You can store data using the following syntax:
```sql
INSERT INTO table_name (column_name) values ('17:34:20');
```
## Range
The time range in SQL is '00:00:00' to '23:59:59'.
## Fetching Data
To fetch the data you can use the SELECT statement. For example:
```sql
SELECT column_name FROM table_name;
```
It will return the time values from the table.
## Functions
SQL provides several functions to work with the TIME data type. Some of them include:
## CURTIME()
Return the current time.
```sql
SELECT CURTIME();
```
## ADDTIME()
Add time values.
```sql
SELECT ADDTIME('2007-12-31 23:59:59','1 1:1:1');
```
## TIMEDIFF()
Subtract time values.
```sql
SELECT TIMEDIFF('2000:01:01 00:00:00', '2000:01:01 00:01:01');
```
## Conversion
Conversion of TIME data type is also possible in SQL. It can be converted into other data types, like INT, and vice versa. Here is a conversion example of TIME to INT:
```sql
SELECT TIME_TO_SEC('22:23:00');
```
This was a brief summary about "TIME" in SQL.

@ -4,42 +4,7 @@ SQL `TIMESTAMP` is a data type that allows you to store both date and time. It i
Depending on the SQL platform, the format and storage size can slightly vary. For instance, MySQL uses the 'YYYY-MM-DD HH:MI:SS' format and in PostgreSQL, it's stored as a 'YYYY-MM-DD HH:MI:SS' format but it additionally can store microseconds. Depending on the SQL platform, the format and storage size can slightly vary. For instance, MySQL uses the 'YYYY-MM-DD HH:MI:SS' format and in PostgreSQL, it's stored as a 'YYYY-MM-DD HH:MI:SS' format but it additionally can store microseconds.
Here is how you can define a column with a `TIMESTAMP` type in an SQL table: Learn more from the following resources:
```sql - [@article@MYSQL TIMESTAMP function](https://www.w3schools.com/mysql/func_mysql_timestamp.asp)
CREATE TABLE table_name ( - [@article@Different SQL TimeStamp functions in SQL Server](https://www.sqlshack.com/different-sql-timestamp-functions-in-sql-server/)
column1 TIMESTAMP,
column2 VARCHAR(100),
...
);
```
A common use-case of `TIMESTAMP` is to have an automatically updated timestamp each time the row is updated. This can be achieved by setting the `DEFAULT` constraint to `CURRENT_TIMESTAMP`:
```sql
CREATE TABLE table_name (
column1 TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
column2 VARCHAR(100),
...
);
```
In MySQL, `ON UPDATE CURRENT_TIMESTAMP` can be used to automatically update the `TIMESTAMP` field to the current date and time whenever there is any change in other fields of the row.
```sql
CREATE TABLE table_name (
column1 TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
column2 VARCHAR(100),
...
);
```
You can also insert or update records with a specific timestamp:
```sql
INSERT INTO table_name (column1, column2) VALUES ('2019-06-10 10:20:30', 'example data');
UPDATE table_name SET column1 = '2020-07-20 15:30:45' WHERE column2 = 'example data';
```
Remember that the format of the date and time you enter must correspond to the format used by the SQL platform you are using.

@ -1,45 +1,8 @@
# Transaction Isolation Levels # Transaction Isolation Levels
SQL supports four transaction isolation levels, each differing in how it deals with concurrency and locks to protect the integrity of the data. Each level makes different trade-offs between consistency and performance. Here is a brief of these isolation levels with relevant SQL statements. Transaction isolation levels in SQL define the degree to which the operations in one transaction are visible to other concurrent transactions. There are typically four standard levels: Read Uncommitted, Read Committed, Repeatable Read, and Serializable. Each level provides different trade-offs between data consistency and concurrency. Understanding and correctly setting isolation levels is crucial for maintaining data integrity and optimizing performance in multi-user database environments.
1. **READ UNCOMMITTED** Learn more from the following resources:
This is the lowest level of isolation. One transaction may read not yet committed changes made by other transaction, also known as "Dirty Reads". Here's an example of how to set this level:
```sql - [@article@Everything you always wanted to know about SQL isolation levels](https://www.cockroachlabs.com/blog/sql-isolation-levels-explained/)
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; - [@article@Isolation Levels in SQL Server](https://www.sqlservercentral.com/articles/isolation-levels-in-sql-server)
BEGIN TRANSACTION;
-- Execute your SQL commands here
COMMIT;
```
2. **READ COMMITTED**
A transaction only sees data changes committed before it started, averting "Dirty Reads". However, it may experience "Non-repeatable Reads", i.e. if a transaction reads the same row multiple times, it might get a different result each time. Here's how to set this level:
```sql
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
BEGIN TRANSACTION;
-- Execute your SQL commands here
COMMIT;
```
3. **REPEATABLE READ**
Here, once a transaction reads a row, any other transaction's writes (changes) onto those rows are blocked until the first transaction is finished, preventing "Non-repeatable Reads". However, "Phantom Reads" may still occur. Here's how to set this level:
```sql
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
BEGIN TRANSACTION;
-- Execute your SQL commands here
COMMIT;
```
4. **SERIALIZABLE**
This is the highest level of isolation. It avoids "Dirty Reads", "Non-repeatable Reads" and "Phantom Reads". This is done by fully isolating one transaction from others: read and write locks are acquired on data that are used in a query, preventing other transactions from accessing the respective data. Here's how to set this level:
```sql
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
-- Execute your SQL commands here
COMMIT;
```
Remember, higher levels of isolation usually provide more consistency but can potentially decrease performance due to increased waiting times for locks.

@ -1,52 +1,8 @@
# Transactions # Transactions
A `transaction` in SQL is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program. Transactions in SQL are units of work that group one or more database operations into a single, atomic unit. They ensure data integrity by following the ACID properties: Atomicity (all or nothing), Consistency (database remains in a valid state), Isolation (transactions don't interfere with each other), and Durability (committed changes are permanent). Transactions are essential for maintaining data consistency in complex operations and handling concurrent access to the database.
Transactions are used to ensure data integrity and to handle database errors while processing. SQL transactions are controlled by the following commands: Learn more from the following resources:
- `BEGIN TRANSACTION` - [@articles@Transactions](https://www.tutorialspoint.com/sql/sql-transactions.htm)
- `COMMIT` - [@article@A Guide to ACID Properties in Database Management Systems](https://www.mongodb.com/resources/basics/databases/acid-transactions)
- `ROLLBACK`
## BEGIN TRANSACTION
This command is used to start a new transaction.
```sql
BEGIN TRANSACTION;
```
## COMMIT
The `COMMIT` command is the transactional command used to save changes invoked by a transaction to the database.
```sql
COMMIT;
```
When you commit the transaction, the changes are permanently saved in the database.
## ROLLBACK
The `ROLLBACK` command is the transactional command used to undo transactions that have not already been saved to the database.
```sql
ROLLBACK;
```
When you roll back a transaction, all changes made since the last commit in the database are undone, and the database is rolled back to the state it was in at the last commit.
## Transaction Example
```sql
BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance - 100 WHERE id = 1;
UPDATE Accounts SET Balance = Balance + 100 WHERE id = 2;
IF @@ERROR = 0
COMMIT;
ELSE
ROLLBACK;
```
In this example, we are transferring 100 units from account 1 to account 2 inside a transaction. If any errors occurred during any of the update statements (captured by `@@ERROR`), the transaction is rolled back, otherwise, it is committed.
Remember that for the transaction to be successful, all commands must execute successfully. If any command fails, the transaction fails, the database state is left unchanged and an error is returned.

@ -4,36 +4,7 @@ The `TRUNCATE TABLE` statement is a Data Definition Language (DDL) operation tha
It effectively eliminates all records in a table, but not the table itself. Unlike the `DELETE` statement, `TRUNCATE TABLE` does not generate individual row delete statements, so the usual overhead for logging or locking does not apply. It effectively eliminates all records in a table, but not the table itself. Unlike the `DELETE` statement, `TRUNCATE TABLE` does not generate individual row delete statements, so the usual overhead for logging or locking does not apply.
## Syntax Learn more from the following resources:
In SQL, the `TRUNCATE TABLE` statement is quite simple: - [@article@TRUNCATE TABLE](https://www.tutorialspoint.com/sql/sql-truncate-table.htm)
- [@video@SQL Tutorial - TRUNCATE TABLE](https://www.youtube.com/watch?v=zJidbjOQlJM)
```sql
TRUNCATE TABLE table_name;
```
In this command, "table_name" refers to the name of the table you wish to clear.
## Example
If you have a table named `Orders` and you want to delete all its records, you would use:
```sql
TRUNCATE TABLE Orders;
```
After executing this statement, the `Orders` table would still exist, but it would be empty.
Remember, while `TRUNCATE TABLE` is faster and uses fewer system and transaction log resources than `DELETE`, it does not invoke triggers and cannot be rolled back, so use with caution.
## Limitations
Truncate preserves the structure of the table for future use. But you can't truncate a table that:
- Is referenced by a FOREIGN KEY constraint. (You can truncate a table that has a foreign key that references itself.)
- Participates in an indexed view.
- Is published by using transactional replication or merge replication.
If you try to truncate a table with a foreign key constraint, SQL Server will prevent you from doing so and you will have to use the `DELETE` statement instead.
For partitioned tables, `TRUNCATE TABLE` removes all rows from all partitions. The operation is not allowed if the table contains any LOB columns - `varchar(max), nvarchar(max), varbinary(max), text, ntext, image, xml`, or if the table contains any filestream columns or spatial geo, geography, geometry, and hierarchyid data type columns, or any columns of CLR user-defined data types.

@ -1,54 +1,7 @@
# Unique # Unique
The `UNIQUE` constraint ensures that all values in a column are different; that is, each value in the column should occur only once. `UNIQUE` is a constraint in SQL used to ensure that all values in a column or a set of columns are distinct. When applied to a column or a combination of columns, it prevents duplicate values from being inserted into the table. This constraint is crucial for maintaining data integrity, especially for fields like email addresses, usernames, or product codes where uniqueness is required. `UNIQUE` constraints can be applied during table creation or added later, and they automatically create an index on the specified column(s) for improved query performance. Unlike `PRIMARY KEY` constraints, `UNIQUE` columns can contain `NULL` values (unless explicitly disallowed), and a table can have multiple `UNIQUE` constraints.
Both the `UNIQUE` and `PRIMARY KEY` constraints provide a guarantee for uniqueness for a column or set of columns. However, a primary key cannot contain `NULL` since it uniquely identifies each row, and each table can have only one primary key. On the other hand, a `UNIQUE` constraint allows for one `NULL` value, and a table can have multiple `UNIQUE` constraints. Learn more from the following resources:
## Syntax - [@article@SQL UNIQUE Constraint](https://www.w3schools.com/sql/sql_unique.asp)
```sql
CREATE TABLE table_name (
column1 data_type UNIQUE,
column2 data_type,
column3 data_type,
....
);
```
Here, `UNIQUE` is the constraint's name, whereas `column1` and `data_type` refer to the column and data type for which we're setting the constraint, respectively.
## Example
Suppose, for instance, we are creating a table named "Employees". We want the "Email" column to contain only unique values to avoid any duplication in email addresses.
Here's how we can impose a `UNIQUE` constraint on the "Email" column:
```sql
CREATE TABLE Employees (
ID int NOT NULL,
Name varchar (255) NOT NULL,
Email varchar (255) UNIQUE
);
```
In this SQL command, we are telling the SQL server that the "Email" column cannot have the same value in two or more rows.
## Adding a Unique Constraint to an Existing Table
To add a `UNIQUE` constraint to an existing table, you would use the `ALTER TABLE` command. Here is the syntax:
```sql
ALTER TABLE table_name
ADD UNIQUE (column1, column2, ...);
```
Here, `table_name` is the name of the table on which we're defining the constraint, and `column1`, `column2`, etc., are the names of the columns included in the constraint.
## Dropping a Unique Constraint
The `ALTER TABLE` command is also used to drop a `UNIQUE` constraint. The syntax to drop a `UNIQUE` constraint is:
```sql
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
```
Here, `constraint_name` is the name of the `UNIQUE` constraint that you want to drop.

@ -1,53 +1,8 @@
# UPDATE # UPDATE
The `UPDATE` command in SQL is used to modify the existing records in a table. This command is useful when you need to update existing data within a database. The UPDATE statement in SQL is used to modify existing records in a table. It allows you to change the values of one or more columns based on specified conditions. The basic syntax includes specifying the table name, the columns to be updated with their new values, and optionally, a WHERE clause to filter which rows should be affected. UPDATE can be used in conjunction with subqueries, joins, and CTEs (Common Table Expressions) for more complex data modifications. It's important to use UPDATE carefully, especially with the WHERE clause, to avoid unintended changes to data. In transactional databases, UPDATE operations can be rolled back if they're part of a transaction that hasn't been committed.
Here are important points to remember before updating records in SQL: Learn more from the following resources:
- The `WHERE` clause in the `UPDATE` statement specifies which records to modify. If you omit the `WHERE` clause, all records in the table will be updated! - [@article@SQL UPDATE Statement](https://www.w3schools.com/sql/sql_update.asp)
- [@article@Efficient column updates in SQL](https://www.atlassian.com/data/sql/how-to-update-a-column-based-on-a-filter-of-another-column)
- Be careful when updating records in SQL. If you inadvertently run an `UPDATE` statement without a `WHERE` clause, you will rewrite all the data in the table.
## SQL UPDATE Syntax
Here is a basic syntax of SQL UPDATE command:
```sql
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
```
In this syntax:
- `table_name`: Specifies the table where you want to update records.
- `SET`: This keyword is used to set the column values.
- `column1, column2... columnN`: These are the columns of the table that you want to change.
- `value1, value2... valueN`: These are the new values that you want to assign for your columns.
- `WHERE`: This clause specifies which records need to be updated. It selects records based on one or more conditions.
## SQL UPDATE Example
Let's assume we have the following `Students` table:
| StudentID | FirstName | LastName | Age |
|-----------|-----------|----------|-----|
| 1 | John | Doe | 20 |
| 2 | Jane | Smith | 22 |
| 3 | Bob | Johnson | 23 |
And we want to update the `Age` of the student with `StudentID` as 2. We can use the `UPDATE` command as follows:
```sql
UPDATE Students
SET Age = 23
WHERE StudentID = 2;
```
After executing the above SQL command, the `Age` of the student with `StudentID` 2 will be updated to 23.
| StudentID | FirstName | LastName | Age |
|-----------|-----------|----------|-----|
| 1 | John | Doe | 20 |
| 2 | Jane | Smith | 23 |
| 3 | Bob | Johnson | 23 |

@ -1,18 +1,8 @@
# UPDATE # UPDATE
The `UPDATE` statement is used to modify existing data in a given table. <br/> The UPDATE statement in SQL is used to modify existing records in a table. It allows you to change the values of one or more columns based on specified conditions. The basic syntax includes specifying the table name, the columns to be updated with their new values, and optionally, a WHERE clause to filter which rows should be affected. UPDATE can be used in conjunction with subqueries, joins, and CTEs (Common Table Expressions) for more complex data modifications. It's important to use UPDATE carefully, especially with the WHERE clause, to avoid unintended changes to data. In transactional databases, UPDATE operations can be rolled back if they're part of a transaction that hasn't been committed.
It can be done so with the query
Learn more from the following resources:
```
UPDATE table_name - [@article@SQL UPDATE Statement](https://www.w3schools.com/sql/sql_update.asp)
SET column1 = value1, column2 = value2, ... - [@article@Efficient column updates in SQL](https://www.atlassian.com/data/sql/how-to-update-a-column-based-on-a-filter-of-another-column)
WHERE condition;
```
- _Keep in mind that **SET** and **WHERE** are also commands to assign a new value(SET) only if the condition is met(WHERE)_
Omitting the `WHERE` clause will update **all** rows in the table.
Visit the following resources to learn more:
- [@article@W3Schools SQL UPDATE Statement Doc](https://www.w3schools.com/sql/sql_update.asp)

@ -1,35 +1,8 @@
# UPPER # UPPER
`UPPER()` is a built-in string function in SQL. As the name suggests, it is used to convert all letters in a specified string to uppercase. If the string already consists of all uppercase characters, the function will return the original string. UPPER() is a string function in SQL used to convert all characters in a specified string to uppercase. This function is particularly useful for data normalization, case-insensitive comparisons, or formatting output. UPPER() typically works on alphabetic characters and leaves non-alphabetic characters unchanged. It's often used in SELECT statements to display data, in WHERE clauses for case-insensitive searches, or in data manipulation operations. Most SQL databases also provide a complementary LOWER() function for converting to lowercase. When working with international character sets, it's important to be aware of potential locale-specific behavior of UPPER().
Syntax for this function is: Learn more from the following resources:
```sql - [@article@SQL Server UPPER Function](https://www.w3schools.com/sql/func_sqlserver_upper.asp)
UPPER(string) - [@article@How to Convert a String to Uppercase in SQL](https://learnsql.com/cookbook/how-to-convert-a-string-to-uppercase-in-sql/)
```
Here 'string' can be a string value or a column of a table of string(s) type.
Let's assume a table 'students' with column 'name' as below:
| name |
|------------|
| John Doe |
| Jane Smith |
| Kelly Will |
If we want all the names in uppercase, we'll use `UPPER()` function as:
```sql
SELECT UPPER(name) as 'Upper Case Name' FROM students;
```
And we will get:
| Upper Case Name |
|----------------|
| JOHN DOE |
| JANE SMITH |
| KELLY WILL |
So, `UPPER()` function helps us to bring an entire string to uppercase for easier comparison and sorting.

@ -1,41 +1,8 @@
# Using Indexes # Using Indexes
Indexes in SQL are used as a way to quicken the rate of retrieval operations on a database table. Much like the index in a book, SQL indexes allow the database program to find the data without needing to go through every row in a table and thus improves performance. Indexes in SQL are database objects that improve the speed of data retrieval operations on database tables. They work similarly to an index in a book, allowing the database engine to quickly locate data without scanning the entire table. Proper use of indexes can significantly enhance query performance, especially for large tables. However, they come with trade-offs: while they speed up reads, they can slow down write operations (INSERT, UPDATE, DELETE) as the index also needs to be updated. Common types include B-tree indexes (default in most systems), bitmap indexes, and full-text indexes. Understanding when and how to create indexes is crucial for database optimization. This involves analyzing query patterns, understanding the data distribution, and balancing the needs of different types of operations on the database.
## Types of Indexes: Learn more from the following resources:
1. **Single-Column Indexes:** - [@article@What is an index in SQL?](https://stackoverflow.com/questions/2955459/what-is-an-index-in-sql)
- [@video@SQL Indexes - Definition, Examples, and Tips](https://www.youtube.com/watch?v=NZgfYbAmge8)
These are created based on only one table column. The syntax for creating a single column index is as follows:
```
CREATE INDEX index_name
ON table_name (column1);
```
2. **Unique Indexes:**
They ensure the data contained in a column or a combination of two or more columns is unique. Syntax to create unique index is as follows:
```
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2...);
```
3. **Composite Indexes:**
These are based on two or more columns of a table. It's important to note that, the order of columns in the definition of an index is important. Syntax to create a Composite Indexes is as follows:
```
CREATE INDEX index_name
ON table_name (column1, column2);
```
4. **Implicit Indexes:**
These are indexes that are automatically created by the database server when an object is defined. For example, when a primary key is defined.
## How Indexes Work
SQL indexes work by storing a part of a table's data in a place where it can be accessed extremely swiftly. The index holds the column value, and the location of the record itself. This is similar to how an index in a book stores the word, and the page number on which the word can be found.
## Considerations
While they do provide a significant advantage, they also require additional storage and can slow down the rate of updates and inserts into a database. As such, indexes should be used judiciously, taking into consideration the nature of the data in the table and the kinds of queries that will be used.

@ -1,54 +1,14 @@
# Views # Views
SQL views are virtual tables that do not store data directly. They are essentially a saved SQL query and can pull data from multiple tables or just present the data from one table in a different way. Views in SQL are virtual tables based on the result set of an SQL statement. They act as a saved query that can be treated like a table, offering several benefits:
## Creating Views - Simplifying complex queries by encapsulating joins and subqueries
- Providing an additional security layer by restricting access to underlying tables
- Presenting data in a more relevant format for specific users or applications
You can create a view using the `CREATE VIEW` statement. In the following example, a new view named `CustomerView` is created which contains customer's ID, name, and address from the `Customers` table: Views can be simple (based on a single table) or complex (involving multiple tables, subqueries, or functions). Some databases support updatable views, allowing modifications to the underlying data through the view. Materialized views, available in some systems, store the query results, improving performance for frequently accessed data at the cost of additional storage and maintenance overhead.
```sql Learn more from the following resources:
CREATE VIEW CustomerView AS
SELECT CustomerID, Name, Address
FROM Customers;
```
## Querying Views - [@video@SQL Views Tutorial](https://www.youtube.com/watch?v=cLSxasHg9WY)
- [@article@Views in SQL](https://www.datacamp.com/tutorial/views-in-sql)
After a view has been created, it can be used in the `FROM` clause of a `SELECT` statement, as if it's an actual table. For instance, to select all from `CustomerView`:
```sql
SELECT *
FROM CustomerView;
```
## Updating Views
The `CREATE OR REPLACE VIEW` statement is used to update a view. Consider the `CustomerView` we created earlier. If we want to include the customer's phone, we can update it as follows:
```sql
CREATE OR REPLACE VIEW CustomerView AS
SELECT CustomerID, Name, Address, Phone
FROM Customers;
```
## Dropping Views
To delete a view, use the `DROP VIEW` statement:
```sql
DROP VIEW CustomerView;
```
Keep in mind that not all database systems support the `CREATE OR REPLACE VIEW` statement. Also, the updatability of a view depends on whether it includes functions, expressions, or multiple tables. Some databases might not let you update a view at all.
## Restrictions
There are a few restrictions to bear in mind when working with views. SQL views can't:
- Contain a `ORDER BY` clause in the view definition
- Be indexed
- Have triggers or default values
Each database may have its own specific limitations and capabilities with using views, so always refer to the official documentation for more information.
Note: The above examples use a hypothetical `Customers` table. Replace this with your actual table name when trying these in your environment.

@ -1,54 +1,16 @@
# What Are Relational Databases? # What Are Relational Databases?
A **relational database** is a type of database that stores and organizes data in a structured way. It uses a structure Relational databases are a type of database management system (DBMS) that stores and provides access to data points that are related to one another. Based on the relational model introduced by E.F. Codd in 1970, they use a structure that allows data to be organized into tables with rows and columns. Key features include:
that allows data to be identified and accessed in relation to other data in the database. Data in a relational database
is stored in various data tables, each of which has a unique key identifying every row.
- Use of SQL (Structured Query Language) for querying and managing data
- Support for ACID transactions (Atomicity, Consistency, Isolation, Durability)
- Enforcement of data integrity through constraints (e.g., primary keys, foreign keys)
- bility to establish relationships between tables, enabling complex queries and data retrieval
- Scalability and support for multi-user environments
Examples of popular relational database systems include MySQL, PostgreSQL, Oracle, and Microsoft SQL Server. They are widely used in various applications, from small-scale projects to large enterprise systems, due to their reliability, consistency, and powerful querying capabilities.
Relational databases are made up of a set of tables with data that fits into a predefined category. Each table has at Learn more from the following resources:
least one data category in a column, and each row contains a certain data instance for the categories defined in the
columns.
For example, consider an 'Employees' table: - [@video@What is a relational database?](https://www.youtube.com/watch?v=OqjJjpjDRLc)
- [@article@What is a relational database - AWS](https://aws.amazon.com/relational-database/)
| EmployeeId | FirstName | LastName | Email |
|------------|-----------|----------|-----------------------|
| 1 | John | Doe | john.doe@example.com |
| 2 | Jane | Doe | jane.doe@example.com |
| 3 | Bob | Smith | bob.smith@example.com |
In this table, 'EmployeeId', 'FirstName', 'LastName' and 'Email' are categories, and each row represents a specific
employee.
## Relationships
The term "relational database" comes from the concept of a relation—a set of tuples that the database organizes into
rows and columns. Each row in a table represents a relationship among a set of values.
Relational databases use `keys` to create links between tables. A `primary key` is a unique identifier for a row of
data. A `foreign key` is a column or combination of columns used to establish and enforce a link between the data in two
tables.
Consider an additional 'Orders' table:
| OrderId | EmployeeId | Product |
|---------|------------|----------|
| 1 | 3 | Apples |
| 2 | 1 | Bananas |
| 3 | 2 | Cherries |
In the 'Orders' table, 'EmployeeId' serves as the foreign key creating a relationship between 'Orders' and 'Employees'.
This allows queries that involve data in both tables, like "Find all orders placed by John Doe".
```sql
SELECT Orders.OrderId, Orders.Product, Employees.FirstName, Employees.LastName
FROM Orders
INNER JOIN Employees ON Orders.EmployeeId = Employees.EmployeeId;
```
The above SQL code is an example of how to retrieve data from a relational database using a `JOIN` clause to combine
rows from two or more tables.
Overall, relational databases provide a powerful mechanism for defining relationships within data and enabling efficient
data retrieval.

@ -4,26 +4,7 @@ SQL provides a WHERE clause that is basically used to filter the records. If the
The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE, DELETE statement, etc., which we will learn in subsequent chapters. The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE, DELETE statement, etc., which we will learn in subsequent chapters.
An example of its implementation is: Learn more from the following resources:
```sql - [@video@How to filter with the WHERE clause in SQL](https://www.youtube.com/watch?v=4Uv0o8IBqw0)
SELECT * FROM Students WHERE Age>10; - [@article@WHERE Clause](https://www.w3schools.com/sql/sql_where.asp)
```
In this example, the statement selects all fields from the 'Students' table where the 'Age' field value is greater than 10.
WHERE clause can be combined with AND, OR, and NOT operators. Here's an example:
```sql
SELECT * FROM Students WHERE Age > 10 AND Gender = 'Female';
```
In this example, the statement selects all fields from 'Students' table where the 'Age' field value is greater than 10 and the 'Gender' is Female.
The syntax generally looks like this:
```sql
SELECT column1, column2, ...
FROM table_name
WHERE condition;
```

@ -4,41 +4,7 @@ SQL Window functions enable you perform calculations on a set of rows related to
These are termed so because they perform a calculation across a set of rows which are related to the current row - somewhat like a sliding window. These are termed so because they perform a calculation across a set of rows which are related to the current row - somewhat like a sliding window.
There are four types of window functions in SQL: Learn more from the following resources:
- **Aggregate functions:** These functions compute a single output value for a group of input values (like averages, sums). - [@article@SQL Window Functions](https://mode.com/sql-tutorial/sql-window-functions)
- [@video@SQL Window Functions in 10 Minutes](https://www.youtube.com/watch?v=y1KCM8vbYe4)
```sql
SELECT department, salary,
AVG(salary) OVER (PARTITION BY department) as avg_departmental_salary
FROM employee;
```
- **Ranking functions:** These functions allocate a unique rank to each row within each window partition.
```sql
SELECT department, salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) as salary_rank
FROM employee;
```
- **Value functions:** These functions provide information about the window partition or the row's position within it, for example - `FIRST_VALUE`, `LAST_VALUE`, `NTH_VALUE`.
```sql
SELECT department, salary,
FIRST_VALUE(salary) OVER (PARTITION BY department ORDER BY salary DESC) as highest_salary
FROM employee;
```
- **Offset functions:** The offset functions provide a way of accessing data from another row in the same result set without joining the table to itself. They can answer questions concerning the value on the row before or after the current row, for example - `LEAD`, `LAG`.
```sql
SELECT department, salary,
LAG(salary) OVER (PARTITION BY department ORDER BY salary) as previous_salary,
LEAD(salary) OVER (PARTITION BY department ORDER BY salary) as next_salary
FROM employee;
```
In using window functions, the `OVER` clause defines the windows or group of rows for function to consider, `PARTITION BY` breaks up the window by a specific column(s), and `ORDER BY` orders rows within the window.
It's important to note that SQL window functions do not cause rows to become grouped into a single output row like aggregate methods do. Therefore, they do not reduce the number of rows returned by the query, each row maintains its individual identity.
Loading…
Cancel
Save