├── .github └── ISSUE_TEMPLATE │ └── issue_report.md ├── .gitignore ├── 1-setup ├── docker-setup │ ├── README.md │ ├── adminer-gui │ │ └── docker-compose.yml │ ├── docker-compose.yml │ ├── mysql │ │ ├── Dockerfile │ │ └── docker-compose.yml │ ├── postgresql │ │ ├── Dockerfile │ │ └── docker-compose.yml │ └── sqlserver │ │ ├── Dockerfile │ │ └── docker-compose.yml ├── manual-setup │ ├── mysql-setup.md │ ├── postgresql-setup.md │ └── sqlserver-setup.md └── schema │ ├── full │ ├── University-DB-ER-model.drawio │ ├── University-DB-ER-model.drawio.png │ ├── populate-university-db.sql │ ├── university-mysql.sql │ ├── university-postgresql.sql │ └── university-sqlserver.sql │ └── simple │ ├── University-DB-ER-model.drawio │ ├── University-DB-ER-model.drawio.png │ ├── populate-university-db.sql │ ├── university-mysql.sql │ ├── university-postgresql.sql │ └── university-sqlserver.sql ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── data-manipulation ├── README.md ├── merging-two-rows │ ├── common-table-expression.sql │ ├── updating-with-coalesce.sql │ └── using-insert-into-and-delete.sql ├── remove-duplicates │ ├── identifying-duplicates.sql │ ├── remove-duplicates-postgresql.sql │ ├── remove-duplicates-sqlserver.sql │ ├── remove-duplicates.sql │ ├── removing-duplicate-row-without-unique-identifier-setup.sql │ ├── using-internal-ctid.sql │ └── using-temporary-table.sql ├── sql-max-value-row-group │ ├── set_up_Schema.sql │ ├── using_CTEs.sql │ ├── using_WindowFunctions.sql │ └── using_subqueries.sql ├── store-decimal-values │ ├── create-order-schema.sql │ ├── insert-value-within-decimal-range.sql │ ├── value-exceed-total-digit-integer.sql │ └── values-exceeding-decimal-scale.sql ├── window-functions-where-clause │ └── window-functions-in-where-clause.sql └── window_functions │ ├── ranking-rows-per-group.sql │ └── top-rows-per-group.sql ├── deleting ├── Deleting-Rows-Using-LEFT-JOIN-SQL │ ├── LEFT-JOIN-basic usage.sql │ ├── MySQL-SQL Server-DELETE-LEFT-JOIN.sql │ ├── MySQL-check-rows.sql │ ├── PostgreSQL-DELETE-LEFT-JOIN.sql │ └── PostgreSQL-check-rows.sql ├── delete-inner-join │ ├── delete-row-inner-join-alias.sql │ └── delete-row-inner-join.sql ├── delete-orphan-records │ ├── delete-orphan-records-left-join.sql │ ├── delete-orphan-records-not-exists.sql │ ├── delete-orphan-records-not-in.sql │ └── identify-orphan-records.sql ├── delete-records-except-top-or-bottom-N │ ├── user-defined-variable-in-mysql.sql │ ├── using-CTE-sql-server.sql │ ├── using-CTE.sql │ ├── using-subqueries.sql │ └── using-window-func.sql └── delete-select-where │ ├── MySQL Alias.sql │ ├── MySQL Temporary Table.sql │ ├── PostgreSQL.sql │ └── SQL Server.sql ├── expressions-operators ├── Extracting-the-First-N-Characters-of-a-Value-in-SQL │ ├── Extracting_the_First_N_Characters_Based_on_Conditions.sql │ ├── Handling_Null_Values.sql │ ├── Using_LEFT().sql │ └── Using_SUBSTRING().sql ├── remove-first-N-char-column │ ├── copy-column.sql │ ├── right-queries.sql │ └── substring-queries.sql ├── rolling-average │ ├── rolling-average-mssql.sql │ ├── rolling-average-mysql.sql │ ├── rolling-average-postgresql.sql │ └── rolling-average.sql ├── sum-two-columns-sql-query │ ├── create-nullable-table.sql │ ├── create-table.sql │ ├── sum-columns-sep-sum-function.sql │ ├── sum-columns-together-sum-function.sql │ ├── sum-nullable-cols-using-sum-function.sql │ ├── sum-two-nullable-cols-using-sum-function-as-window-function.sql │ ├── sum-using-coalesce.sql │ ├── sum-using-column-expression.sql │ └── sum-using-window-function.sql └── using-greater-than-in-a-SQL-CASE-Statement │ ├── using-greater-than-in-a-SQL-Case-Statement-mysql.sql │ ├── using-greater-than-in-a-SQL-Case-Statement-postgresql.sql │ └── using-greater-than-in-a-SQL-Case-Statement-sqlserver.sql ├── inserting ├── insert-from-select │ ├── insert-from-select.sql │ └── sql-insert-multiple-rows │ │ ├── insert-multiple-rows-PostgreSQL.sql │ │ └── insert-multiple-rows.sql └── insert-if-not-exists │ ├── insert-if-not-exists-mysql.sql │ ├── insert-if-not-exists-postgresql.sql │ └── insert-if-not-exists-sqlserver.sql ├── procedures-and-functions ├── README.md ├── functions-vs-stored-procedure │ ├── example-usage-function.sql │ └── example-usage-stored-procedure.sql ├── stored-procedure-vs-view │ ├── stored-procedure-example.sql │ └── view-example.sql └── stored-procedures │ ├── avg-gpa-procedure.sql │ ├── dynamic-procedure.sql │ ├── if-else-procedure.sql │ └── inout-procedure.sql ├── querying (GET) ├── Sort-by-a-List-of-Strings-in-SQL │ ├── Sort-by-a-strings-of-list-in-MySQL.sql │ ├── Sort-by-a-strings-of-list-in-PostgreSQL.sql │ └── Sort-by-a-strings-of-list-in-SQL-Server.sql ├── count │ ├── conditional-count-mysql.sql │ ├── conditional-count-pg.sql │ ├── conditional-count.sql │ └── conditionl-count-mssql.sql ├── having-vs-where │ ├── having-clause-example.sql │ └── where-clause-example.sql ├── null-empty-filter │ ├── null-empty-mssql.sql │ ├── null-empty-mysql.sql │ └── null-empty.sql ├── on-vs-where │ ├── filter-with-where.sql │ ├── inner-join-examples.sql │ └── left-join-example.sql ├── querying-for-specific-values-in-integer-column │ ├── basic-queries.sql │ ├── dynamic-queries-mysql.sql │ ├── dynamic-queries-postgresql.sql │ ├── dynamic-queries-sqlserver.sql │ └── dynamic-queries.sql └── sql-retrieve-random │ ├── sql-random-mssql.sql │ ├── sql-random-mysql.sql │ └── sql-random-postgres.sql ├── schema-management ├── change-column-type │ ├── alter-ms.sql │ ├── alter-mysql.sql │ └── alter-pg.sql ├── differences-json-and-jsonb │ ├── example-json.sql │ └── example-jsonb.sql ├── drop-all-tables │ ├── mssql_drop_tables_script.sql │ ├── mysql_drop_tables_script.sql │ └── postgres_drop_tables_script.sql ├── remove-primarykey-mysql │ ├── add-duplicate-id.sql │ ├── add-null-value.sql │ ├── add-second-pk-failed.sql │ ├── alter-table-add-pk.sql │ ├── alter-table-column-nullable.sql │ ├── alter-table-drop-pk.sql │ ├── create-department-duplicate.sql │ ├── describe-table.sql │ ├── drop-pk-in-transaction.sql │ ├── list-table-constraints.sql │ ├── set-var.sql │ └── show-var-sql_require_primary_key.sql ├── represent-inheritance-database │ ├── Class-Table-Inheritance.sql │ ├── Concrete-Table-Inheritance.sql │ └── Single-Table-Inheritance.sql └── table-existence │ ├── table-existence-mssql.sql │ ├── table-existence-mysql.sql │ └── table-existence-pg.sql ├── sql-constraints ├── drop-not-null │ ├── drop-null-mysql.sql │ ├── drop-null-pg.sql │ ├── drop-null-sqlserver.sql │ └── reset.sql ├── list-table-foreign-keys │ ├── Information-schema-postgres.sql │ ├── Information-schema-sql-server.sql │ ├── information-schema-mysql.sql │ ├── pg_constraint-Catalog-sql-server.sql │ ├── show-create-table-mysql.sql │ └── stored-procedure-sql-server.sql └── sql-alter-constraint │ ├── alter_constraint_mysql.sql │ ├── alter_constraint_postgres.sql │ └── alter_constraint_sqlserver2022.sql ├── sql-generation └── generate-insert-from-excel │ ├── manual-method.sql │ ├── new-data-insert.sql │ ├── student-records.xlsx │ ├── using-excel-formula.sql │ └── using-vba.sql ├── sql-queries-10 ├── backup-single-table-and-database │ ├── copying table-temporary-database.sql │ ├── implementation-mysql.sh │ ├── implementation-postgres.sh │ ├── using-mssql-scripter.sh │ └── using-sqlpackage.sh ├── checking-database-connectivity │ ├── mysql.env │ ├── postgresql.env │ ├── test-db-connect.sh │ ├── test-mysql-connect.sh │ ├── test_mysql_connect.py │ └── test_pg_connect.py ├── generate-all-indexes-in-database │ ├── implementation-in-mysql_extended.sql │ ├── implementation-in-mysql_original.sql │ ├── implementation-in-postgres_extended.sql │ ├── implementation-in-postgres_original.sql │ └── implementation-in-sqlserver.sql ├── get-table-sizes-mysql │ ├── create-myisam-tables.sql │ ├── select-query-information-schema-innodb.sql │ ├── select-query-information-schema-myisam.sql │ ├── show-table-status.sql │ └── sql-query-aggregate-table-sizes.sql ├── how-to-upsert-in-PostgreSQL │ ├── using-INSERT-…-ON-CONFLICT-pgsql.sql │ └── using-MERGE-pgsql.sql ├── integer-to-string │ └── postgresql-queries.sql ├── lateral-joins-vs-subqueries │ ├── example-usage-lateral-join.sql │ └── example-usage-subqueries.sql ├── not-equals-operator │ └── not-equals.sql ├── optimize-all-tables-mysql │ ├── create-myisam-tables.sql │ ├── optimize-all-tables-with-mysqlcheck.cmd │ └── optimize-all-tables-with-optimize-table-sql-stmt.sql ├── update-multiple-different-rows │ └── update-multiple-different-rows.sql └── where-1-equals-0 │ ├── all-dbs.sql │ ├── mysql.sql │ └── pg-mssql.sql ├── sql-queries-11 ├── Save_PostgreSQL_Result_to_File │ └── Save_PostgreSQL_Result_to_File.sql ├── as-alias │ └── as-alias.sql ├── duplicate-insert-row-same-table-with-auto-increment │ ├── create-table.sql │ ├── duplicate-entry-example.sql │ ├── find-auto-increment-column.sql │ ├── insert-select-example.sql │ └── insert-select-using-specific-id.sql └── sum-distinct-rows │ ├── distinct-within-subquery.sql │ ├── sum-with-cte.sql │ └── union-within-subquery.sql ├── sql-queries-2 ├── README.md ├── char-types │ └── char-types-mssql.sql ├── join-vs-union │ ├── join-example.sql │ └── union-example.sql ├── security │ └── list-grants │ │ ├── mssql.sql │ │ ├── mysql.sql │ │ └── postgres.sql ├── select-record │ ├── except-mssql.sql │ ├── left-join-with-null.sql │ ├── not-exists.sql │ └── not-in.sql ├── self-Join-table-twice │ ├── self-join-find-duplicates.sql │ ├── self-join-query-data.sql │ └── simple-self-join.sql ├── set-and-alter-default │ ├── alter-default-mysql.sql │ ├── alter-default-postgresql.sql │ ├── alter-default-sqlserver.sql │ └── set-default.sql ├── sql-count-diff │ └── count-diff.sql ├── sql-distinct │ └── distinct-values.sql └── sql-multiple-counts-with-single-query │ ├── using-case-in-sum.sql │ ├── using-if-in-count.sql │ └── using-subqueries.sql ├── sql-queries-3 ├── README.md ├── concatenate-null │ ├── select-concat-coalesce-null.sql │ ├── select-concat-null.sql │ ├── select-concat-ws-null.sql │ └── select-or-operator-null.sql ├── group-by-on-multiple-columns │ ├── basic-usage-example.sql │ ├── multiple-columns-example.sql │ ├── using-having-on-multiple-columns-example.sql │ ├── using-join-on-multiple-columns-example.sql │ ├── using-nested-on-multiple-columns-example.sql │ └── using-order-by-on-multiple-columns-example.sql ├── join-vs-subquery │ ├── join-example.sql │ ├── subquery-join-example.sql │ ├── subquery-nested-example.sql │ ├── subquery-select-example.sql │ └── subquery-where-example.sql ├── order-number-strings │ ├── ordering-mssql.sql │ ├── ordering-mysql.sql │ ├── ordering-pg.sql │ └── setup.sql ├── parameterizing-sql-in-clause │ ├── in-operator-example.sql │ ├── mysql-find-in-set-example.sql │ ├── mysql-prepared-statement-example.sql │ ├── postgres-function-example.sql │ ├── postgres-prepared-statement-example.sql │ ├── sql-server-string-split-example.sql │ ├── sql-server-user-defined-table-type-example.sql │ └── sql-sever-dynamic-example.sql ├── sql-distinct │ └── distinct-values.sql ├── sql-if-within-where │ ├── case-in-where.sql │ ├── where-with-IIF.sql │ ├── where-with-boolean-operators.sql │ └── where-with-choose.sql └── sql-innerjoin │ └── innerjoin-on.sql ├── sql-queries-4 ├── README.md ├── autocommit-mysql │ ├── commit-and-chain-implicit-transaction.sql │ ├── commit-implicit-transaction.sql │ ├── commit-release.sql │ ├── implicit-commit.sql │ ├── implicit-transaction.sql │ └── rollback.sql ├── commit-rollback-savepoint │ ├── clean.sql │ ├── commit-and-chain.sql │ ├── commit-release.sql │ ├── commit.sql │ ├── implicit-commit.sql │ ├── rollback-transaction.sql │ └── savepoint.sql ├── different-join-order │ ├── inner_join.sql │ ├── left_join_multiple_tables.sql │ └── left_join_two_tables.sql ├── escape-single-quote │ └── escape-single-quote.sql ├── groupby-vs-distinct │ ├── distinct-examples.sql │ └── groupby-example.sql ├── not-equal-to-with-where-clause │ ├── alternative-not-equal-to-operator.sql │ ├── basic-where-syntax.sql │ ├── combining-not-equal-to-with-other-conditions.sql │ ├── handling-null-values.sql │ ├── simple-not-equal-to-queries.sql │ └── standard-not-equal-to-operator.sql ├── orderby-in-clause │ ├── select-case-orderby.sql │ ├── select-cte-orderby.sql │ ├── select-field-orderby.sql │ └── select-temp-orderby.sql ├── physical-vs-logical-deletion │ ├── cascading-deletion-challenges.sql │ ├── manual-deletion.sql │ ├── physical-deletion.sql │ ├── using-deleted_at Column.sql │ └── using-is_deleted Column.sql ├── retrieve-size-table │ ├── using pg_table_size-function-postgres.sql │ ├── using-custom-query-postgres.sql │ ├── using-information-schema-mysql.sql │ ├── using-information-schema-postgres.sql │ ├── using-show-table-status-mysql.sql │ ├── using-sp_spaceused-sql-server.sql │ └── using-sys.dm_db_partition_stats-sql-server.sql ├── trimming-strings-sql │ ├── Create-ventures-schema.sql │ ├── apply-trim-function-columns.sql │ ├── using-LTRIM.sql │ ├── using-RTRIM.sql │ └── using-TRIM.sql └── which-sql-require-commit-mysql │ ├── create-temporary-table.sql │ ├── delete.sql │ ├── insert.sql │ ├── replace.sql │ ├── select.sql │ └── update.sql ├── sql-queries-5 ├── README.md ├── String Concatenation and Aggregation in SQL │ └── ifnull.sql ├── diff-setautocommit=1-starttransaction-mysql │ ├── autocommit-enabled.sql │ ├── set-autocommit.sql │ └── start-transaction.sql ├── export-sql-schema-without-data │ ├── customize-export-mysql.sh │ ├── customize-export-postgresql.sh │ ├── export-entire-database-mysql.sh │ ├── export-entire-database-postgresql.sh │ ├── export-specific-schemas-postgresql.sh │ └── export-specific-table-mysql.sh ├── mysql-dump-by-query │ └── mysql-dump-by-query.sql ├── removing-leading-zeros-in-sql │ ├── altering-student-table-MySQL-PostgreSQL.sql │ ├── altering-student-table-SQL-Server.sql │ ├── example-formatted-data.sql │ ├── trimming-with-MySQL.sql │ ├── trimming-with-PostgreSQL.sql │ ├── trimming-with-SQL-Server.sql │ ├── using-CAST-function-MySQL.sql │ ├── using-CAST-function-PostgreSQL.sql │ ├── using-CAST-function-SQL-Server.sql │ ├── using-CONVERT-function-with-MySQL.sql │ ├── using-CONVERT-function-with-PosgreSQL.sql │ └── using-CONVERT-function-with-SQL-Server.sql ├── select-butoom-N-row-in-sql │ ├── using-orderby-and-limit-postgresql.sql │ ├── using-orderby-and-offset-fetch-clause-sqlserver.sql │ ├── using-rownumber-window-function-postgresql.sql │ ├── using-rownumber-window-function-sqlserver.sql │ └── using-subqueries-with-orderby-mysql.sql ├── split-column-values-into-multiple-columns │ ├── split-column-values-into-multiple-columns-mysql.sql │ ├── split-column-values-into-multiple-columns-postgresql.sql │ └── split-column-values-into-multiple-columns-sqlserver.sql └── turning-off-autocommit-mysql-client │ ├── README │ ├── batch-dml-explicit-transaction.sql │ ├── batch-dml-implicit-transaction.sql │ ├── persist-global-autocommit-off-setting.sql │ ├── select-autocommit-global.sql │ ├── select-autocommit-session.sql │ ├── turn-off-autocommit-lock-unlock-tables.sql │ ├── turn-off-autocommit-session-level.sql │ ├── turn-off-autocommit-transaction-level.sql │ ├── turn-off-global-autocommit.sql │ └── turn-on-autocommit.sql ├── sql-queries-6 ├── README ├── README.md ├── SUM-groupby-id │ ├── complex-aggregation-example.sql │ ├── filter-group-result.sql │ ├── grouping-data.sql │ └── handling-null-values.sql ├── add-foreign-key-existing-table │ ├── add-foreign-key-mssql.sql │ ├── add-foreign-key-mysql.sql │ └── add-foreign-key-postgresql.sql ├── check-indexes-in-sql │ ├── using-SHOW-INDEX-mysql.sql │ ├── using-di-command-pg.sql │ ├── using-information_schema.STATISTICS-mysql.sql │ ├── using-pg_catalog.pg_index-system-table.sql │ ├── using-pg_indexes-system-catalog-pg.sql │ ├── using-sp_helpindex-sqlserver.sql │ ├── using-sys.index_columns.sql │ └── using-sys.indexes-sqlserver.sql ├── range-values │ ├── mssql.sql │ ├── mysql.sql │ └── postgres.sql ├── run-select-without-locking-mysql │ ├── autocommit-on-select-without-locks.sql │ ├── innodb-status.sql │ ├── plain-select.sql │ ├── select-expressions-only.sql │ ├── select-for-share.sql │ ├── select-for-update.sql │ ├── select-sub-query.sql │ ├── set-transaction-read-only.sql │ └── update-query.sql ├── run-sql-queries-on-csv-file │ ├── data.csv │ ├── example2_csv.py │ ├── example_csv.py │ ├── import-data-to-sqlite.sh │ ├── install-duckdb.sh │ ├── install-pandas-and-pandasql.sh │ ├── install-sqlite.sh │ ├── run-sql-queries-noninteractively.sh │ ├── running-example2_csv.py.sh │ ├── running-example_csv.py.sh │ └── running-sql-queries-sqlite.sql ├── sql-max-value │ └── max-value.sql └── sql-paginate-count │ └── sql-paginate-count.sql ├── sql-queries-7 ├── Accessing-Query-Tables-within-subquery │ ├── correlated-subqueries.sql │ ├── correlated-subquery-cross-compatible-solution.sql │ ├── outer-query-reference.sql │ ├── outer-reference-FROM-clause-limitation.sql │ ├── outer-reference-SELECT-clause.sql │ ├── outer-reference-WHERE-clause.sql │ ├── reference-outer-query-table-subquery.sql │ └── using-JOIN-and-GROUP BY- cross-compatible-solution.sql ├── README ├── create-json-format-group-concat-mysql │ ├── group-by-related-exception-fixed.sql │ ├── group-by-related-exception.sql │ ├── json-array-from-literal.sql │ ├── json-array-from-table-elaborate-example.sql │ ├── json-array-from-table-with-JSON_ARRAY-function.sql │ ├── json-array-from-table.sql │ ├── json-array-with-JSON_ARRAY-function.sql │ ├── json-object-from-literal.sql │ ├── json-object-from-table-with-JSON_OBJECT-function.sql │ ├── json-object-from-table.sql │ └── json-object-with-JSON_OBJECT-function.sql ├── escape-keyword │ ├── escape-mssql.sql │ ├── escape-mysql.sql │ └── escape-pg.sql ├── insert-column-in-existing-table │ ├── insert-column-at-a-specific-position.sql │ ├── insert-column-at-any-position-MySQL.sql │ ├── insert-column-at-end-of-table.sql │ └── insert-column-at-first-position-MySQL.sql ├── looping-through-records │ ├── using-cursor-mysql.sql │ ├── using-cursor-postgresql.sql │ ├── using-cursor-sqlserver.sql │ ├── using-temporary-table-mysql.sql │ ├── using-temporary-table-postgresql.sql │ ├── using-temporary-table-sqlserver.sql │ ├── using-while-loop-mysql.sql │ ├── using-while-loop-postgresql.sql │ └── using-while-loop-sqlserver.sql └── sum-with-conditions │ ├── basic-sum.sql │ ├── merging-where-groupby.sql │ ├── multiple-conditions.sql │ ├── sum-with-case.sql │ ├── sum-with-groupby.sql │ └── sum-with-where.sql ├── sql-queries-8 ├── Give-all-permission-to-a-user │ ├── implementation-in-mysql.sql │ ├── implementation-in-postgresql.sql │ └── implementation-in-sql-server.sql ├── Retrieving_Table_and_Index_Storage_Size_in_SQL │ ├── MySQL_Basic_Table_Storage_Information.sql │ ├── MySQL_Detailed_Index_Analysis.sql │ ├── Postgre_Table_Storage_Information.sql │ ├── Postgres_Index_Storage_Details.sql │ ├── SQLServer_Index_Storage_Analysis.sql │ └── SQLServer_Table_Storage_Information.sql ├── Set-Database-From-Single-User-Mode-to-Multi-User-Mode │ ├── Set-Database-From-Single-User-Mode-to-Multi-User-Mode-MySQL.sql │ ├── Set-Database-From-Single-User-Mode-to-Multi-User-Mode-PostgreSQL.sql │ └── Set-Database-From-Single-User-Mode-to-Multi-User-Mode-SQL-Server.sql ├── case-insensitive-searches │ ├── search-mssql.sql │ ├── search-mysql.sql │ ├── search-pg.sql │ ├── setup.sql │ └── standard.sql ├── collation │ ├── MSSQL │ │ ├── List_of_all_available_UFT-8_collations.sql │ │ ├── MSSQL_Database_Charset.sql │ │ ├── Support_UTF-8.sql │ │ └── Testing_MSSQL_Collations.sql │ ├── MySQL │ │ ├── Force_the_use_of_a_different_collation.sql │ │ ├── Identify_collations.sql │ │ ├── MySQL_Database_Charset.sql │ │ ├── Setting_Collation.sql │ │ └── Upgrade_to_utf8mb4.sql │ ├── PostgreSQL │ │ ├── Check_the_current_locale_settings.sql │ │ ├── List_all_the_collations.sql │ │ ├── PostgreSQL_Database_Charset.sql │ │ └── Sensitivity_in_Queries.sql │ └── addInternationalStudents.sql ├── reasons-the-DELETE-statement-in-SQL-can-be-very-slow │ ├── basic-delete.sql │ ├── creating-multiple-Indexes.sql │ ├── delete-with-foreign-key.sql │ ├── implementing-batch-delete-alternative.sql │ ├── implementing-batch-delete.sql │ ├── index-optimization-delete.sql │ ├── lock-behaviour.sql │ └── multiple-foreign-key-delete.sql ├── reset-autoincrement-mysql │ ├── alter-table-to-reset-autoincrement.sql │ ├── insert-to-reset-autoincrement.sql │ ├── sample-table.sql │ └── update-to-reset-autoincrement.sql ├── selecting-single-row-based-on-multiple-criteria-from-one-column │ ├── selecting-single-row-based-on-multiple-criteria-mssql.sql │ ├── selecting-single-row-based-on-multiple-criteria-mysql.sql │ └── selecting-single-row-based-on-multiple-criteria-pgsql.sql └── what-are-common-table-expressions │ ├── enhancing-query-readability.sql │ ├── groupingby-scalar-subselect.sql │ ├── recursive-cte-queries.sql │ ├── reference-resulting-table-mulltiple-times.sql │ └── substitute-for-view.sql ├── sql-queries-9 ├── README.md ├── calculate-percentage-sql-statement │ ├── basic-percentage-calculation.sql │ ├── calculate-percentage-between-columns.sql │ ├── dynamically-calculate-percentage-grades.sql │ └── sample-data.sql ├── delete-column-from-table │ ├── delete-column-from-table.sql │ ├── delete-columns-from-table-mssql.sql │ ├── delete-columns-from-table-mysql.sql │ └── delete-columns-from-table-pg.sql ├── keyword-search-sql │ ├── full-text-search-mysql.sql │ ├── full-text-search-postgresql.sql │ ├── full-text-search-sqlserver.sql │ └── using-like-operator.sql ├── limit-number-of-rows-after-ordering │ ├── limit-number-of-rows-after-ordering-mssql.sql │ ├── limit-number-of-rows-after-ordering-mysql.sql │ └── limit-number-of-rows-after-ordering-pgsql.sql ├── null-to-zero │ ├── ansi.sql │ ├── mssql.sql │ ├── mysql.sql │ └── setup.sql ├── pattern-matching-functions-in-PostgreSQL │ └── Pattern-Matching-Functions-in-PostgreSQL-postgresql.sql ├── sql-over-clause │ ├── over-clause-with-group-by.sql │ ├── over-clause-with-order-by.sql │ ├── over-clause-with-partition-by.sql │ └── over-clause-with-rows.sql └── using-LEFT-OUTER-JOIN-with-WHERE-clause │ ├── using-LEFT-OUTER-JOIN-with-WHERE-clause.sql │ └── using-LEFT-OUTER-JOIN.sql ├── sql-queries-create-table ├── README.md ├── sql-create-table-using-WITH │ ├── create-table-separately-with-clause-sql-server.sql │ ├── create-table-with-clause-mysql.sql │ ├── create-table-with-clause-postgresql.sql │ └── create-table-with-clause-sql-server.sql └── sql-move-table │ └── sql-insert-select.sql ├── sql-queries-dates-1 ├── current-date-rows │ ├── current-date-rows-mysql.sql │ ├── current-date-rows-pg.sql │ ├── current-date-rows-sqlserver.sql │ └── setup.sql └── select-date-without-time │ ├── cast()-function.sql │ ├── date()-function.sql │ └── date-format()-function.sql ├── sql-queries-dates ├── README.md ├── Selecting_Dates_Within_a_Range_Using_SQL_Queries │ ├── Basic Date Filtering.sql │ ├── Handling Time in Date Ranges.sql │ ├── Selecting Dates Within a Range.sql │ ├── Selecting Dates Within a Range_2.sql │ ├── Using Functions for Date Range Selection.sql │ ├── Using Functions for Date Range Selection_2.sql │ ├── Working with Different Date Formats.sql │ └── Working with Different Date Formats_2.sql ├── convert-month-number-to-name │ ├── using-case-statement.sql │ ├── using-custom-function.sql │ ├── using-datename.sql │ └── using-format.sql ├── current-date-and-time │ ├── current-date-and-time-mysql.sql │ ├── current-date-and-time-postgresql.sql │ └── current-date-and-time-sqlserver.sql ├── current-timestamp-sql-server │ └── current-timestamp-mssql.sql ├── day_of_the_week │ ├── day_of_the_week_mssql.sql │ ├── day_of_the_week_mysql.sql │ └── day_of_the_week_postgreSQL.sql ├── first-day-of-month │ ├── first-day-of-month-mysql.sql │ ├── first-day-of-month-postgresql.sql │ └── first-day-of-month-sqlserver.sql ├── group-year-month │ ├── grouping-mssql.sql │ ├── grouping-mysql.sql │ └── grouping-pg.sql └── interval-queries │ ├── interval-mssql.sql │ ├── interval-mysql.sql │ └── interval-pg.sql ├── sql-queries-exists ├── README.md └── record-existence │ ├── count.sql │ ├── exists.sql │ ├── select.sql │ └── top.sql ├── sql-queries-index ├── README.md ├── Relationship-between-primary-key-and-clustered-indexes │ └── Examples-clustered-indexes │ │ ├── Clustered-index-on-a-composite-key.sql │ │ ├── Custom-created-index.sql │ │ ├── Primary-key-clustered-index.sql │ │ └── Primary-key-with-Non-Clustered-Index.sql ├── composite-index-in-sql │ ├── analyze-composite-index-performance.sql │ ├── analyze-query-with-no-composite-index.sql │ ├── create-composite-index.sql │ └── drop-composite-index.sql ├── composite-vs-multi-col-indexes-sql │ ├── create-composite-indexes.sql │ ├── create-individual-indexes.sql │ ├── insert-dummy-data.sql │ └── query-students.sql ├── index-rebuild │ ├── automate_index_rebuild.sql │ ├── calculate-fragmentation_percent.sql │ ├── creating_db_role.sql │ ├── db_database.sql │ ├── rebuild_all_index_in_db.sql │ └── rebuild_index_on_table.sql ├── retrieve-table-primary-key │ ├── information_schema-postgres.sql │ ├── pg_constraint-system-catalog-postgres.sql │ ├── sys.key_constraints-system-catalog-sqlserver.sql │ ├── using-information-schema-sqlserver.sql │ ├── using-pg_indexes-postgres.sql │ ├── using-show-index-mysql.sql │ ├── using-show-keys-mysql.sql │ └── using-sp_help-stored-procedure-sqlserver.sql └── sql-ignore-index │ ├── mysql-analyze-query-plan.sql │ ├── mysql-ignore-index-IGNORE-INDEX-hint.sql │ ├── mysql-ignore-index-USE-INDEX-hint.sql │ ├── mysql-ignore-index-for-group-by.sql │ ├── mysql-ignore-index-for-join.sql │ ├── mysql-ignore-index-for-order-by.sql │ ├── mysql-optimizer-hint-no-index.sql │ ├── mysql-show-indexes.sql │ ├── sql-server-WITH-clause.sql │ ├── sql-server-ignore-index-by-exclusion.sql │ ├── sql-server-ignore-index-hint.sql │ └── sql-server-setup.sql ├── sql-queries-like ├── README.md └── equals-vs-like │ ├── Equals (=) String Comparison.sql │ ├── Equals (=) With Date and Time Data.sql │ ├── Equals (=) With Numeric Data.sql │ ├── LIKE Wildcard Characters.sql │ └── LIKE vs. Equals (=).sql ├── sql-queries ├── README.md ├── column-search │ ├── column-search-mssql.sql │ ├── column-search-pg.sql │ └── column-search.sql ├── identify-duplicate-values │ ├── functions-and-clauses.sql │ ├── identify-duplicate-rows.sql │ └── sample-dataset.sql ├── inner-join │ ├── inner-join-3-tables.sql │ ├── nested-subquerie-inner-join.sql │ └── sample-dataset.sql ├── list-tables │ ├── list-tables-mssql.sql │ ├── list-tables-mysql.sql │ ├── list-tables-pg.sql │ └── list-tables.sql ├── matching-multiple-patterns │ ├── matching-multiple-patterns-postgresql.sql │ ├── matching-multiple-patterns.sql │ └── migration-multiple-patterns-sqlserver.sql ├── prevent-division-by-zero │ ├── prevent-division-by-zero-sqlserver.sql │ └── prevent-division-by-zero.sql ├── sql-if-then │ ├── case-query.sql │ ├── choose-query-sql.sql │ ├── elt-query-mysql.sql │ ├── if-query-mysql.sql │ └── iif-query-sql.sql ├── sql-in-vs-exists │ ├── exists-operator-mysql.sql │ ├── in-operator-mysql.sql │ └── in-operator-subquery-mysql.sql └── sql-text-search │ ├── search-all.sql │ ├── search-mssql.sql │ ├── search-mysql.sql │ ├── search-pg.sql │ └── setup.sql ├── sql-subqueries ├── README.md ├── difference_between_CTE_and_Subquery │ ├── correlated_subquery.sql │ ├── cte_use_case.sql │ ├── multi_row_subquery.sql │ ├── recursive_cte_query.sql │ ├── scalar_subquery.sql │ └── subquery_use_case.sql ├── how-to-use-SELECT-with-multiple-subqueries-to-same-table-in-SQL │ ├── sample-problem-illustration.sql │ ├── solving-redundancy-inefficient-query-with-CTE.sql │ ├── solving-redundancy-inefficient-query-with-JOINs.sql │ ├── subqueries-in-FROM-clause.sql │ ├── subqueries-in-SELECT-clause.sql │ └── subqueries-in-WHERE-clause.sql └── subquery-vs-correlated-subquery │ ├── correlated subquery.sql │ └── subquery.sql ├── sql-syntax ├── CASE_Statement_With_SELECT │ ├── CASE_with_aggregate_function.sql │ ├── CASE_with_subqueries.sql │ ├── calculations_within_CASE_statement.sql │ ├── searched_CASE.sql │ └── simple_CASE.sql ├── Counting-Distinct-Values │ └── create-sql.sql └── escape-single-quote │ ├── escape-single-quote-mssql.sql │ ├── escape-single-quote-mysql.sql │ └── escape-single-quote-psql.sql ├── table-operations-2 ├── README.md ├── change-table-engine-in-mysql │ ├── changing-storage-engine.sql │ ├── checking-storage-engine.sql │ └── show-storage-engine.sql ├── comments-mysql │ └── comments.mysql ├── detect-locked-table-mysql │ ├── checking-lock-in-performance_schema.metadata_locks.sql │ ├── locking-table.sql │ ├── unlock-table.sql │ └── using-show-open-table.sql ├── find-storage-engine │ └── script.sql ├── mysql-images │ ├── images.sql │ └── images │ │ ├── cb_logo.png │ │ ├── cs_logo.png │ │ ├── ece_logo.png │ │ ├── john_pp.jpeg │ │ ├── ma_logo.png │ │ ├── philip_pp.jpeg │ │ ├── rita_pp.jpeg │ │ ├── samantha_pp.jpeg │ │ ├── ss_logo.png │ │ └── vikas_pp.jpeg ├── mysql-pattern-matching │ └── pattern-matching.sql ├── mysql-recursive-cte │ └── recursive.sql └── mysql-store-json │ ├── creating-table-example.sql │ ├── inserting-json-data.sql │ ├── retrieving-json-data.sql │ └── updating-json-data.sql ├── table-operations ├── Adding-Comment-to-Table-Columns-in-SQL │ ├── Adding-Comment-to-Table-Columns-in-MySQL.sql │ ├── Adding-Comment-to-Table-Columns-in-PostgreSQL.sql │ └── Adding-Comments-to-Table-Columns-in-SQLServer.sql ├── README.md ├── altering-column-definition │ ├── altering-columns-to-not-null-mssql.sql │ ├── altering-columns-to-not-null-mysql.sql │ └── altering-columns-to-not-null-postgres.sql ├── determine-database-version │ ├── mysql.sql │ ├── postgresql.sql │ └── sqlserver.sql ├── drop-table-if-exists │ ├── script-ms-sql.sql │ ├── script-mysql.sql │ └── script-postgresql.sql ├── insert-csv-file-into-sql-table │ ├── access-mysql-terminal.sh │ ├── implementation-in-postgres.sql │ ├── sample-data.sh │ ├── using-bulk-insert-comman.sql │ ├── using-load-data-infile-command-mysql.sql │ ├── using-mysqlimport-mysql.sql │ └── using-mysqlimport.sh ├── sql-alter-drop-if-exist │ ├── drop-conditional-alter-mysql.sql │ ├── drop-conditional-alter-psql.sql │ ├── drop-conditional-alter-sqlserver.sql │ ├── if-column-exist-mysql.sql │ ├── if-column-exist-psql.sql │ └── if-column-exist-sqlserver.sql ├── table-difference │ └── sql-except-join.sql └── temporary-table-select │ ├── extract_data_into_temp.sql │ ├── extract_data_into_temp_sqlserver.sql │ ├── temp_with_join_statement.sql │ └── temp_with_join_statement_SQLserver.sql └── updating ├── insert-or-update-if-exists ├── merge-sql-server.sql ├── on-conflict-postgresql.sql ├── on-duplicate-key-mysql.sql └── replace-mysql.sql ├── update-data-table ├── merge-into-pq.sql ├── merge-into.sql ├── sample-table.sql ├── update-with-join-mysql.sql ├── update-with-join.sql ├── update-with-subquery.sql ├── update-with-where-mysql.sql ├── update-with-where-pg.sql └── update-with-where.sql ├── update-replace ├── update-replace-basic.sql └── update-replace-where.sql └── updating-data-with-joins-in-sql ├── update-join-with-case.sql └── update-join-with-where.sql /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .vscode/ 3 | **/.DS_Store -------------------------------------------------------------------------------- /1-setup/docker-setup/adminer-gui/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | 3 | services: 4 | adminer: 5 | image: adminer 6 | ports: 7 | - 8080:8080 8 | 9 | -------------------------------------------------------------------------------- /1-setup/docker-setup/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | 3 | services: 4 | adminer: 5 | extends: 6 | file: ./adminer-gui/docker-compose.yml 7 | service: adminer 8 | 9 | mysql: 10 | extends: 11 | file: ./mysql/docker-compose.yml 12 | service: mysql 13 | 14 | postgres: 15 | extends: 16 | file: ./postgresql/docker-compose.yml 17 | service: postgres 18 | 19 | mssql: 20 | extends: 21 | file: ./sqlserver/docker-compose.yml 22 | service: mssql 23 | -------------------------------------------------------------------------------- /1-setup/docker-setup/mysql/Dockerfile: -------------------------------------------------------------------------------- 1 | # add more configurations here -------------------------------------------------------------------------------- /1-setup/docker-setup/postgresql/Dockerfile: -------------------------------------------------------------------------------- 1 | # add more configurations here -------------------------------------------------------------------------------- /1-setup/docker-setup/sqlserver/Dockerfile: -------------------------------------------------------------------------------- 1 | # add more configurations here -------------------------------------------------------------------------------- /1-setup/schema/full/University-DB-ER-model.drawio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/sql-tutorials/cd7dd50e082cddbf50c3be20089272a8bad142f0/1-setup/schema/full/University-DB-ER-model.drawio.png -------------------------------------------------------------------------------- /1-setup/schema/simple/University-DB-ER-model.drawio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/sql-tutorials/cd7dd50e082cddbf50c3be20089272a8bad142f0/1-setup/schema/simple/University-DB-ER-model.drawio.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This project contains SQL files that support the tutorials on https://www.baeldung.com/sql/ 2 | 3 | To setup the database on your local system, **go to the folder "1-setup"**. There are two methods you can use: 4 | - manual setup - go to the [manual-setup](1-setup/manual-setup) folder, and select the file for the respective database technology and follow the instructions there 5 | - docker setup - go to the [docker-setup](1-setup/docker-setup) folder and follow the instructions in the readme file 6 | -------------------------------------------------------------------------------- /data-manipulation/README.md: -------------------------------------------------------------------------------- 1 | ### Relevant Articles: 2 | - [Merging Two Rows in SQL](https://www.baeldung.com/sql/merge-two-records) 3 | - [How to Fetch Maximum Value for Each Group Using SQL](https://www.baeldung.com/sql/max-value-per-group) 4 | - [How to Remove Duplicate Rows in SQL](https://www.baeldung.com/sql/duplicate-removal) 5 | - [How to Restrict Results to Top N Rows per Group in SQL](https://www.baeldung.com/sql/top-n-rows-window-functions) 6 | 7 | -------------------------------------------------------------------------------- /data-manipulation/remove-duplicates/identifying-duplicates.sql: -------------------------------------------------------------------------------- 1 | SELECT semester, year, reg_datetime, course_id, student_id, COUNT(*) 2 | FROM modifiedregistration 3 | GROUP BY semester, year, reg_datetime, course_id, student_id 4 | HAVING COUNT(*) > 1; -------------------------------------------------------------------------------- /data-manipulation/remove-duplicates/using-internal-ctid.sql: -------------------------------------------------------------------------------- 1 | WITH duplicates AS ( 2 | SELECT ctid, 3 | ROW_NUMBER() OVER(PARTITION BY semester, year, reg_datetime, course_id, student_id ORDER BY semester) AS row_num 4 | FROM modifiedregistration 5 | ) 6 | DELETE FROM modifiedregistration 7 | WHERE ctid IN (SELECT ctid FROM duplicates WHERE row_num > 1); 8 | 9 | select * from modifiedregistration; -------------------------------------------------------------------------------- /data-manipulation/remove-duplicates/using-temporary-table.sql: -------------------------------------------------------------------------------- 1 | CREATE TEMPORARY TABLE unique_rows AS 2 | SELECT DISTINCT * 3 | FROM modifiedregistration; 4 | 5 | TRUNCATE TABLE modifiedregistration; 6 | 7 | INSERT INTO modifiedregistration 8 | SELECT * FROM unique_rows; 9 | 10 | SELECT * FROM modifiedregistration; -------------------------------------------------------------------------------- /data-manipulation/sql-max-value-row-group/using_CTEs.sql: -------------------------------------------------------------------------------- 1 | WITH MaxSalaries AS ( 2 | SELECT department, MAX(salary) AS max_salary 3 | FROM Employees 4 | GROUP BY department 5 | ) 6 | SELECT e.id, e.name, e.department, e.salary 7 | FROM Employees e 8 | JOIN MaxSalaries ms ON e.department = ms.department AND e.salary = ms.max_salary; 9 | -------------------------------------------------------------------------------- /data-manipulation/sql-max-value-row-group/using_WindowFunctions.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, department, salary 2 | FROM ( 3 | SELECT id, name, department, salary, 4 | ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn 5 | FROM Employees 6 | ) sub 7 | WHERE rn = 1; 8 | -------------------------------------------------------------------------------- /data-manipulation/sql-max-value-row-group/using_subqueries.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, department, salary 2 | FROM Employees e1 3 | WHERE salary = ( 4 | SELECT MAX(salary) 5 | FROM Employees e2 6 | WHERE e1.department = e2.department 7 | ); 8 | -------------------------------------------------------------------------------- /data-manipulation/store-decimal-values/create-order-schema.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE Orders ( 2 | order_id INT PRIMARY KEY, 3 | total_amount DECIMAL(12,2) 4 | ); -------------------------------------------------------------------------------- /data-manipulation/store-decimal-values/insert-value-within-decimal-range.sql: -------------------------------------------------------------------------------- 1 | -- Inserting a value within the range 2 | INSERT INTO Orders (order_id, total_amount) VALUES (1, 123456.78); 3 | 4 | -- Inserting a value exactly at the maximum limit 5 | INSERT INTO Orders (order_id, total_amount) VALUES (2, 9999999999.99); 6 | 7 | -- Display the order table data 8 | SELECT * FROM orders; -------------------------------------------------------------------------------- /data-manipulation/store-decimal-values/value-exceed-total-digit-integer.sql: -------------------------------------------------------------------------------- 1 | -- Attempting to insert a value that exceeds the total number of digits allowed 2 | INSERT INTO Orders (order_id, total_amount) VALUES (4, 10000000000000.00); 3 | 4 | -- Error output will look like this: 5 | -- ERROR: numeric field overflow 6 | --DETAIL: A field with precision 12, scale 2 must round to an absolute value less than 10^10. 7 | -------------------------------------------------------------------------------- /data-manipulation/store-decimal-values/values-exceeding-decimal-scale.sql: -------------------------------------------------------------------------------- 1 | -- inserted value exceeds the declared scale of the DECIMAL 2 | INSERT INTO Orders (order_id, total_amount) VALUES (3, 123.456); 3 | 4 | -- Output Order table 5 | SELECT * FROM orders; 6 | -------------------------------------------------------------------------------- /deleting/Deleting-Rows-Using-LEFT-JOIN-SQL/LEFT-JOIN-basic usage.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | s.id AS student_id, 3 | s.name AS student_name, 4 | r.course_id 5 | FROM student s 6 | LEFT JOIN registration r ON s.id = r.student_id; -------------------------------------------------------------------------------- /deleting/Deleting-Rows-Using-LEFT-JOIN-SQL/MySQL-SQL Server-DELETE-LEFT-JOIN.sql: -------------------------------------------------------------------------------- 1 | FROM Student s 2 | LEFT JOIN Registration r ON s.id = r.student_id 3 | WHERE r.student_id IS NULL; -------------------------------------------------------------------------------- /deleting/Deleting-Rows-Using-LEFT-JOIN-SQL/MySQL-check-rows.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Student s 3 | LEFT JOIN Registration r ON s.id = r.student_id 4 | WHERE r.student_id IS NULL; -------------------------------------------------------------------------------- /deleting/Deleting-Rows-Using-LEFT-JOIN-SQL/PostgreSQL-DELETE-LEFT-JOIN.sql: -------------------------------------------------------------------------------- 1 | DELETE FROM student 2 | WHERE id IN ( 3 | SELECT s.id 4 | FROM student s 5 | LEFT JOIN registration r ON s.id = r.student_id 6 | WHERE r.student_id IS NULL 7 | ); -------------------------------------------------------------------------------- /deleting/Deleting-Rows-Using-LEFT-JOIN-SQL/PostgreSQL-check-rows.sql: -------------------------------------------------------------------------------- 1 | SELECT s.id 2 | FROM student s 3 | LEFT JOIN registration r ON s.id = r.student_id 4 | WHERE r.student_id IS NULL; -------------------------------------------------------------------------------- /deleting/delete-inner-join/delete-row-inner-join-alias.sql: -------------------------------------------------------------------------------- 1 | DELETE s 2 | FROM Student AS s 3 | INNER JOIN Department AS d ON s.department_id = d.id 4 | WHERE d.name = 'Computer Science'; -------------------------------------------------------------------------------- /deleting/delete-inner-join/delete-row-inner-join.sql: -------------------------------------------------------------------------------- 1 | DELETE Student 2 | FROM Student 3 | INNER JOIN Department ON Student.department_id = Department.id 4 | WHERE Department.name = 'Computer Science'; -------------------------------------------------------------------------------- /deleting/delete-orphan-records/delete-orphan-records-left-join.sql: -------------------------------------------------------------------------------- 1 | DELETE FROM Registration 2 | WHERE student_id IN ( 3 | SELECT Registration.student_id 4 | FROM Registration 5 | LEFT JOIN Students ON Registration.student_id = Students.student_id 6 | WHERE Students.student_id IS NULL 7 | ); 8 | -------------------------------------------------------------------------------- /deleting/delete-orphan-records/delete-orphan-records-not-exists.sql: -------------------------------------------------------------------------------- 1 | DELETE FROM Registration 2 | WHERE NOT EXISTS ( 3 | SELECT 1 4 | FROM Students 5 | WHERE Students.student_id = Registration.student_id 6 | ); 7 | -------------------------------------------------------------------------------- /deleting/delete-orphan-records/delete-orphan-records-not-in.sql: -------------------------------------------------------------------------------- 1 | DELETE FROM Registration 2 | WHERE student_id NOT IN ( 3 | SELECT student_id 4 | FROM Students 5 | ); 6 | -------------------------------------------------------------------------------- /deleting/delete-orphan-records/identify-orphan-records.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Registration 3 | WHERE student_id NOT IN ( 4 | SELECT student_id 5 | FROM Students 6 | ); 7 | -------------------------------------------------------------------------------- /deleting/delete-records-except-top-or-bottom-N/using-CTE.sql: -------------------------------------------------------------------------------- 1 | WITH TopStudents AS ( 2 | SELECT id 3 | FROM Student 4 | ORDER BY id 5 | LIMIT 5 6 | ) 7 | DELETE FROM Student 8 | WHERE id NOT IN (SELECT id FROM TopStudents); 9 | 10 | SELECT * FROM Student; 11 | 12 | WITH BottomStudents AS ( 13 | SELECT id 14 | FROM Student 15 | ORDER BY id DESC 16 | LIMIT 5 17 | ) 18 | DELETE FROM Student 19 | WHERE id NOT IN (SELECT id FROM BottomStudents); 20 | 21 | SELECT * FROM Student; -------------------------------------------------------------------------------- /deleting/delete-records-except-top-or-bottom-N/using-subqueries.sql: -------------------------------------------------------------------------------- 1 | DELETE FROM Course 2 | WHERE id NOT IN ( 3 | SELECT id 4 | FROM Course 5 | ORDER BY id 6 | LIMIT 10 7 | ); 8 | 9 | DELETE FROM Course 10 | WHERE id NOT IN ( 11 | SELECT id 12 | FROM Course 13 | ORDER BY id DESC 14 | LIMIT 5 15 | ); -------------------------------------------------------------------------------- /deleting/delete-select-where/MySQL Alias.sql: -------------------------------------------------------------------------------- 1 | DELETE 2 | FROM Exam 3 | WHERE id IN 4 | (SELECT id 5 | FROM 6 | (SELECT id 7 | FROM Exam 8 | WHERE grade IS NULL) AS TEMP); 9 | -------------------------------------------------------------------------------- /deleting/delete-select-where/MySQL Temporary Table.sql: -------------------------------------------------------------------------------- 1 | -- Creating the temporary table 2 | CREATE TEMPORARY TABLE TempExamIds AS 3 | SELECT id 4 | FROM Exam 5 | WHERE grade IS NULL; 6 | 7 | -- Performing the DELETE operation 8 | DELETE 9 | FROM Exam 10 | WHERE id IN 11 | (SELECT id 12 | FROM TempExamIds); 13 | 14 | -- (Optional) Dropping the temporary table 15 | DROP TEMPORARY TABLE TempExamIds; 16 | -------------------------------------------------------------------------------- /deleting/delete-select-where/PostgreSQL.sql: -------------------------------------------------------------------------------- 1 | DELETE 2 | FROM Exam 3 | WHERE id IN 4 | (SELECT id 5 | FROM Exam 6 | WHERE grade IS NULL); 7 | -------------------------------------------------------------------------------- /deleting/delete-select-where/SQL Server.sql: -------------------------------------------------------------------------------- 1 | DELETE 2 | FROM Exam 3 | WHERE id IN 4 | (SELECT id 5 | FROM Exam 6 | WHERE grade IS NULL); 7 | -------------------------------------------------------------------------------- /expressions-operators/Extracting-the-First-N-Characters-of-a-Value-in-SQL/Extracting_the_First_N_Characters_Based_on_Conditions.sql: -------------------------------------------------------------------------------- 1 | SELECT id, LEFT(name, 3) AS name_start, department_id 2 | FROM Faculty 3 | WHERE department_id = ( 4 | SELECT id 5 | FROM Department 6 | WHERE name = 'Computer Science' 7 | ) 8 | LIMIT 5; 9 | -------------------------------------------------------------------------------- /expressions-operators/Extracting-the-First-N-Characters-of-a-Value-in-SQL/Handling_Null_Values.sql: -------------------------------------------------------------------------------- 1 | SELECT id, COALESCE(LEFT(name, 5), 'N/A') AS first_five_chars 2 | FROM Student 3 | LIMIT 5; 4 | -------------------------------------------------------------------------------- /expressions-operators/Extracting-the-First-N-Characters-of-a-Value-in-SQL/Using_LEFT().sql: -------------------------------------------------------------------------------- 1 | SELECT id, LEFT(textbook, 10) AS textbook_start 2 | FROM Course 3 | WHERE textbook IS NOT NULL 4 | LIMIT 5; 5 | -------------------------------------------------------------------------------- /expressions-operators/Extracting-the-First-N-Characters-of-a-Value-in-SQL/Using_SUBSTRING().sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, SUBSTRING(name, 1, 3) AS course_code 2 | FROM Course 3 | LIMIT 5; 4 | -------------------------------------------------------------------------------- /expressions-operators/remove-first-N-char-column/copy-column.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE Course ADD id_copy VARCHAR(10); 2 | UPDATE Course SET id_copy = id; 3 | SELECT id, id_copy, name FROM Course LIMIT 4; 4 | -------------------------------------------------------------------------------- /expressions-operators/remove-first-N-char-column/right-queries.sql: -------------------------------------------------------------------------------- 1 | SELECT RIGHT('websitebaeldung', 8); 2 | SELECT RIGHT(id_copy, LENGTH(id_copy) - 3) FROM Course; 3 | UPDATE Course SET id_copy = RIGHT(id_copy, LENGTH(id_copy) - 3); 4 | SELECT id, id_copy, name FROM Course; 5 | -------------------------------------------------------------------------------- /expressions-operators/remove-first-N-char-column/substring-queries.sql: -------------------------------------------------------------------------------- 1 | SELECT SUBSTRING(id_copy, 3, 3) from Course; 2 | UPDATE Course SET id_copy = SUBSTRING(id_copy, 3, 3); 3 | SELECT id, id_copy, name FROM Course; 4 | -------------------------------------------------------------------------------- /expressions-operators/rolling-average/rolling-average-mssql.sql: -------------------------------------------------------------------------------- 1 | CREATE VIEW v_DailyEnrollmentWithAvg 2 | WITH SCHEMABINDING AS 3 | SELECT date, total_registrations, AVG(total_registrations) OVER ( ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW ) 4 | AS rolling_avg_7_days 5 | FROM DailyEnrollment; 6 | GO CREATE UNIQUE CLUSTERED INDEX idx_DailyEnrollmentWithAvg ON v_DailyEnrollmentWithAvg (date); 7 | -------------------------------------------------------------------------------- /expressions-operators/rolling-average/rolling-average-mysql.sql: -------------------------------------------------------------------------------- 1 | CREATE EVENT update_rolling_avg 2 | ON SCHEDULE EVERY 1 DAY 3 | DO REPLACE INTO DailyEnrollmentRollingAvg 4 | SELECT date, total_registrations, AVG(total_registrations) OVER ( ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW ) 5 | AS rolling_avg_7_days 6 | FROM DailyEnrollment; 7 | -------------------------------------------------------------------------------- /expressions-operators/rolling-average/rolling-average-postgresql.sql: -------------------------------------------------------------------------------- 1 | CREATE MATERIALIZED VIEW RollingAvgEnrollment 2 | AS SELECT date, total_registrations, ROUND(AVG(total_registrations) OVER ( ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW ), 2) 3 | AS rolling_avg_7_days 4 | FROM DailyEnrollment 5 | ORDER BY date; 6 | -------------------------------------------------------------------------------- /expressions-operators/rolling-average/rolling-average.sql: -------------------------------------------------------------------------------- 1 | SELECT date, total_registrations, AVG(total_registrations) 2 | OVER ( ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW ) AS rolling_avg_7_days 3 | FROM DailyEnrollment 4 | ORDER BY date; 5 | -------------------------------------------------------------------------------- /expressions-operators/sum-two-columns-sql-query/create-nullable-table.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE magazine_nullable 2 | (publisher_id INT NOT NULL, 3 | magazine_name varchar(50), 4 | q1sales INT, 5 | q2sales INT); 6 | 7 | INSERT INTO magazine_nullable 8 | (publisher_id,magazine_name,q1sales,q2sales) 9 | VALUES(1,'magazine_1',NULL,30), 10 | (1,'magazine_2',100,NULL), 11 | (2,'magazine_3',50,NULL), 12 | (2,'magazine_4',NULL,20), 13 | (3,'magazine_5',NULL,50), 14 | (3,'magazine_6',NULL,25); 15 | -------------------------------------------------------------------------------- /expressions-operators/sum-two-columns-sql-query/create-table.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE magazine 2 | (publisher_id INT NOT NULL, 3 | magazine_name varchar(50), 4 | q1sales INT NOT NULL, 5 | q2sales INT NOT NULL); 6 | 7 | INSERT INTO magazine 8 | (publisher_id,magazine_name,q1sales,q2sales) 9 | VALUES(1,'magazine_1',60,30), 10 | (1,'magazine_2',100,25), 11 | (2,'magazine_3',50,25), 12 | (2,'magazine_4',75,20), 13 | (3,'magazine_5',10,50), 14 | (3,'magazine_6',25,25); 15 | 16 | SELECT * FROM magazine; 17 | -------------------------------------------------------------------------------- /expressions-operators/sum-two-columns-sql-query/sum-columns-sep-sum-function.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | publisher_id,magazine_name, 3 | SUM(q1sales) + SUM(q2sales) AS Q1Q2Sales 4 | FROM magazine 5 | GROUP BY publisher_id,magazine_name; 6 | -------------------------------------------------------------------------------- /expressions-operators/sum-two-columns-sql-query/sum-columns-together-sum-function.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | publisher_id, magazine_name, 3 | SUM(q1sales + q2sales) AS Q1_Q2_Sales 4 | FROM magazine 5 | GROUP BY publisher_id,magazine_name; 6 | -------------------------------------------------------------------------------- /expressions-operators/sum-two-columns-sql-query/sum-nullable-cols-using-sum-function.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | publisher_id, 3 | SUM(q1sales) + SUM(q2sales) AS Q1Q2Sales 4 | FROM magazine_nullable WHERE publisher_id<3 5 | GROUP BY publisher_id; 6 | -------------------------------------------------------------------------------- /expressions-operators/sum-two-columns-sql-query/sum-two-nullable-cols-using-sum-function-as-window-function.sql: -------------------------------------------------------------------------------- 1 | SELECT publisher_id,magazine_name, 2 | COALESCE(q1sales,0)+COALESCE(q2sales,0) AS magazine_sales, 3 | SUM(COALESCE(q1sales,0)+COALESCE(q2sales,0)) 4 | OVER(PARTITION BY publisher_id) AS publisher_sales, 5 | SUM(COALESCE(q1sales,0)+COALESCE(q2sales,0)) 6 | OVER() AS total_sales 7 | FROM magazine_nullable 8 | WINDOW w AS (PARTITION BY publisher_id ORDER BY publisher_id); 9 | -------------------------------------------------------------------------------- /expressions-operators/sum-two-columns-sql-query/sum-using-coalesce.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | publisher_id,magazine_name, 3 | SUM(COALESCE(q1sales,0)) + SUM(COALESCE(q2sales,0)) AS Q1Q2Sales 4 | FROM magazine_nullable 5 | GROUP BY publisher_id,magazine_name; 6 | -------------------------------------------------------------------------------- /expressions-operators/sum-two-columns-sql-query/sum-using-column-expression.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | publisher_id, magazine_name, 3 | q1sales+q2sales AS magazine_sales 4 | FROM magazine; 5 | -------------------------------------------------------------------------------- /expressions-operators/sum-two-columns-sql-query/sum-using-window-function.sql: -------------------------------------------------------------------------------- 1 | SELECT publisher_id, magazine_name, 2 | q1sales+q2sales AS magazine_sales, 3 | SUM(q1sales+q2sales) 4 | OVER(PARTITION BY publisher_id) AS publisher_sales, 5 | SUM(q1sales+q2sales) 6 | OVER() AS total_sales 7 | FROM magazine 8 | WINDOW w AS (PARTITION BY publisher_id ORDER BY publisher_id); 9 | -------------------------------------------------------------------------------- /inserting/insert-from-select/insert-from-select.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO registration_analytics(student_id, number_of_course_enrolled, year) 2 | SELECT student_id, COUNT(course_id) AS number_of_course_enrolled, year 3 | FROM registration 4 | GROUP BY course_id, student_id, year; -------------------------------------------------------------------------------- /inserting/insert-from-select/sql-insert-multiple-rows/insert-multiple-rows-PostgreSQL.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO Student (id, name, national_id) 2 | VALUES (1001, 'John Liu', 123345566) 3 | UNION ALL 4 | VALUES (1003, 'Rita Ora', 132345166) 5 | UNION ALL 6 | VALUES (1007, 'Philip Lose', 321345566) 7 | UNION ALL 8 | VALUES (1010, 'Samantha Prabhu', 3217165566) -------------------------------------------------------------------------------- /procedures-and-functions/README.md: -------------------------------------------------------------------------------- 1 | ## Relevant Articles: 2 | - [What Is a Stored Procedure and How Does It Work](https://www.baeldung.com/sql/stored-procedures-guide) 3 | - [Difference Between Stored Procedure and View](https://www.baeldung.com/sql/stored-procedure-vs-view) 4 | -------------------------------------------------------------------------------- /procedures-and-functions/functions-vs-stored-procedure/example-usage-function.sql: -------------------------------------------------------------------------------- 1 | CREATE OR REPLACE FUNCTION CalculateAge(birthDate DATE) 2 | RETURNS INT AS $$ 3 | BEGIN 4 | RETURN EXTRACT(YEAR FROM age(birthDate)); 5 | END; 6 | $$ LANGUAGE plpgsql; 7 | 8 | SELECT id, name, CalculateAge(birth_date) AS age 9 | FROM Student; -------------------------------------------------------------------------------- /procedures-and-functions/functions-vs-stored-procedure/example-usage-stored-procedure.sql: -------------------------------------------------------------------------------- 1 | CREATE OR REPLACE PROCEDURE UpdateGPA(student_id INT, new_gpa REAL) 2 | LANGUAGE plpgsql AS $$ 3 | BEGIN 4 | UPDATE Student 5 | SET gpa = new_gpa 6 | WHERE id = student_id; 7 | 8 | RAISE NOTICE 'GPA updated for Student ID: %', student_id; 9 | END; 10 | $$; 11 | 12 | SELECT * FROM student LIMIT 3; 13 | 14 | CALL UpdateGPA(1001, 3.9); 15 | 16 | SELECT id, name, gpa 17 | FROM Student 18 | WHERE id = 1001; -------------------------------------------------------------------------------- /procedures-and-functions/stored-procedure-vs-view/stored-procedure-example.sql: -------------------------------------------------------------------------------- 1 | CREATE OR REPLACE PROCEDURE UpdateStudentGPA( 2 | IN student_id INT, 3 | IN new_gpa REAL 4 | ) 5 | LANGUAGE plpgsql 6 | AS $$ 7 | BEGIN 8 | UPDATE Student 9 | SET gpa = new_gpa 10 | WHERE id = student_id; 11 | END; 12 | $$; 13 | 14 | CALL UpdateStudentGPA(1001, 4.5); 15 | 16 | SELECT id, name, gpa 17 | FROM Student 18 | WHERE id = 1001; -------------------------------------------------------------------------------- /procedures-and-functions/stored-procedure-vs-view/view-example.sql: -------------------------------------------------------------------------------- 1 | CREATE VIEW StudentGraduationGPA AS 2 | SELECT id, name, graduation_date, gpa 3 | FROM Student 4 | WHERE graduation_date IS NOT NULL; 5 | 6 | SELECT * FROM StudentGraduationGPA; 7 | 8 | -------------------------------------------------------------------------------- /procedures-and-functions/stored-procedures/dynamic-procedure.sql: -------------------------------------------------------------------------------- 1 | -- DELIMITER // 2 | 3 | -- CREATE PROCEDURE DynamicCourseQuery( 4 | -- IN where_clause VARCHAR(1000) 5 | -- ) 6 | -- BEGIN 7 | -- SET @sql = CONCAT('SELECT id, name, credits FROM Course WHERE ', where_clause); 8 | -- PREPARE stmt FROM @sql; 9 | -- EXECUTE stmt; 10 | -- DEALLOCATE PREPARE stmt; 11 | -- END // 12 | 13 | -- DELIMITER ; 14 | 15 | CALL DynamicCourseQuery('credits < 3 AND department_id = 1'); -------------------------------------------------------------------------------- /procedures-and-functions/stored-procedures/inout-procedure.sql: -------------------------------------------------------------------------------- 1 | DELIMITER // 2 | 3 | CREATE PROCEDURE IncrementAndReturn ( 4 | INOUT value INT 5 | ) 6 | BEGIN 7 | SET value = value + 1; 8 | END // 9 | 10 | DELIMITER ; 11 | 12 | SET @my_value = 5; 13 | CALL IncrementAndReturn(@my_value); 14 | SELECT @my_value; -------------------------------------------------------------------------------- /querying (GET)/Sort-by-a-List-of-Strings-in-SQL/Sort-by-a-strings-of-list-in-PostgreSQL.sql: -------------------------------------------------------------------------------- 1 | -- Sort a list of strings in ascending or descending order 2 | SELECT * 3 | FROM Department 4 | ORDER BY name DESC; 5 | 6 | -- Sort a list of strings in a specific predefined order 7 | SELECT name 8 | FROM Department 9 | ORDER BY ARRAY_POSITION(ARRAY['Computer Science', 'Mathematics', 'Civil Engineering'], name); 10 | -------------------------------------------------------------------------------- /querying (GET)/count/conditional-count-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | COUNT(IF(position = 'Assistant Professor', 1, NULL)) AS assistant_professors, 3 | COUNT(IF(position = 'Professor', 1, NULL)) AS professors 4 | FROM Faculty; 5 | 6 | SELECT 7 | SUM(position = 'Assistant Professor') AS assistant_professors, 8 | SUM(position = 'Professor') AS professors 9 | FROM Faculty; -------------------------------------------------------------------------------- /querying (GET)/count/conditional-count-pg.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | COUNT(*) FILTER (WHERE position = 'Assistant Professor') AS assistant_professors, 3 | COUNT(*) FILTER (WHERE position = 'Professor') AS professors 4 | FROM Faculty; -------------------------------------------------------------------------------- /querying (GET)/count/conditionl-count-mssql.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | COUNT(IIF(position = 'Assistant Professor', 1, NULL)) AS assistant_professors, 3 | COUNT(IIF(position = 'Professor', 1, NULL)) AS professors 4 | FROM Faculty; -------------------------------------------------------------------------------- /querying (GET)/having-vs-where/having-clause-example.sql: -------------------------------------------------------------------------------- 1 | SELECT name, graduation_date, AVG(gpa) AS average_gpa 2 | FROM Student 3 | GROUP BY name, graduation_date 4 | HAVING AVG(gpa) > 4.0; 5 | -------------------------------------------------------------------------------- /querying (GET)/having-vs-where/where-clause-example.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, gpa 2 | FROM Student 3 | WHERE gpa > 3.5; 4 | -------------------------------------------------------------------------------- /querying (GET)/null-empty-filter/null-empty-mssql.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name from Department WHERE ISNULL(code, '') = '' OR TRIM(code) = ''; -------------------------------------------------------------------------------- /querying (GET)/null-empty-filter/null-empty-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name from Department where ISNULL(code) OR TRIM(code) = ''; -------------------------------------------------------------------------------- /querying (GET)/on-vs-where/filter-with-where.sql: -------------------------------------------------------------------------------- 1 | SELECT Course.id, Course.name, Course.credits, Course.is_active, Department.name, Department.code 2 | FROM Course JOIN Department 3 | ON Course.department_id = Department.id 4 | WHERE Department.name = 'Computer Science'; 5 | 6 | -------------------------------------------------------------------------------- /querying (GET)/on-vs-where/inner-join-examples.sql: -------------------------------------------------------------------------------- 1 | SELECT Course.id, Course.name, Course.credits, Course.is_active, Department.name, Department.code 2 | FROM Course JOIN Department 3 | ON Course.department_id = Department.id; 4 | 5 | SELECT Course.id, Course.name, Course.credits, Course.is_active, Department.name, Department.code 6 | FROM Course JOIN Department 7 | WHERE Course.department_id = Department.id; 8 | -------------------------------------------------------------------------------- /querying (GET)/on-vs-where/left-join-example.sql: -------------------------------------------------------------------------------- 1 | SELECT Course.name, Department.name 2 | FROM Course 3 | LEFT JOIN Department 4 | ON Course.department_id = Department.id; 5 | -------------------------------------------------------------------------------- /querying (GET)/querying-for-specific-values-in-integer-column/dynamic-queries-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM table_name WHERE (@column_name_filter IS NULL OR column_name = @column_name_filter); 2 | -------------------------------------------------------------------------------- /querying (GET)/querying-for-specific-values-in-integer-column/dynamic-queries-postgresql.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM table_name 2 | WHERE column_name = CASE 3 | WHEN column_value IS NOT NULL THEN column_value -- Replace column_value with the desired filter value 4 | ELSE column_name 5 | END; 6 | -------------------------------------------------------------------------------- /querying (GET)/querying-for-specific-values-in-integer-column/dynamic-queries-sqlserver.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM table_name WHERE column_name = ISNULL(@column_name_filter, column_name); 2 | -------------------------------------------------------------------------------- /querying (GET)/querying-for-specific-values-in-integer-column/dynamic-queries.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM table_name WHERE column_name = COALESCE(@column_name_filter, column_name); 2 | -------------------------------------------------------------------------------- /querying (GET)/sql-retrieve-random/sql-random-mssql.sql: -------------------------------------------------------------------------------- 1 | SELECT TOP 1 * 2 | FROM Faculty 3 | ORDER BY NEWID(); 4 | -------------------------------------------------------------------------------- /querying (GET)/sql-retrieve-random/sql-random-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Faculty 3 | ORDER BY RAND() 4 | LIMIT 1; 5 | -------------------------------------------------------------------------------- /querying (GET)/sql-retrieve-random/sql-random-postgres.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Faculty 3 | ORDER BY RANDOM() 4 | LIMIT 1; 5 | 6 | SELECT * 7 | FROM Faculty 8 | ORDER BY RANDOM() 9 | LIMIT 2; 10 | 11 | SELECT * 12 | FROM Faculty 13 | ORDER BY RANDOM() 14 | LIMIT 3; 15 | -------------------------------------------------------------------------------- /schema-management/change-column-type/alter-ms.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE Course ALTER COLUMN credits DECIMAL; 2 | 3 | -- reset column type 4 | ALTER TABLE Course ALTER COLUMN credits INTEGER; -------------------------------------------------------------------------------- /schema-management/change-column-type/alter-mysql.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE Course MODIFY COLUMN credits DECIMAL(10,2); 2 | ALTER TABLE Course CHANGE COLUMN credits credits DECIMAL(10,2); 3 | 4 | -- RESET column 5 | ALTER TABLE Course MODIFY COLUMN credits INTEGER; -------------------------------------------------------------------------------- /schema-management/change-column-type/alter-pg.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE course ALTER COLUMN credits TYPE DECIMAL; 2 | ALTER TABLE course ALTER COLUMN credits TYPE VARCHAR; 3 | ALTER TABLE course ALTER COLUMN credits TYPE DECIMAL; -- Expected to give error 4 | ALTER TABLE course ALTER COLUMN credits TYPE DECIMAL USING credits::INTEGER; -- also resets type 5 | 6 | ALTER TABLE course 7 | ALTER COLUMN credits TYPE INTEGER 8 | USING regexp_replace(credits, '\D', '', 'g')::INTEGER; -- extract only numeric from a varchar column -------------------------------------------------------------------------------- /schema-management/differences-json-and-jsonb/example-json.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE users ( 2 | id SERIAL PRIMARY KEY, 3 | profile JSON 4 | ); 5 | 6 | INSERT INTO users (profile) 7 | VALUES ('{"name": "Alice", "age": 30, "preferences": {"theme": "dark", "notifications": true}}'); 8 | 9 | SELECT profile FROM users; 10 | 11 | SELECT profile->>'name' AS name FROM users; -------------------------------------------------------------------------------- /schema-management/differences-json-and-jsonb/example-jsonb.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE users_jsonb ( 2 | id SERIAL PRIMARY KEY, 3 | profile JSONB 4 | ); 5 | 6 | INSERT INTO users_jsonb (profile) 7 | VALUES ('{"name": "Alice", "age": 30, "preferences": {"theme": "dark", "notifications": true}}'); 8 | 9 | SELECT profile FROM users_jsonb; 10 | 11 | SELECT profile->>'name' AS name FROM users_jsonb; -------------------------------------------------------------------------------- /schema-management/drop-all-tables/mssql_drop_tables_script.sql: -------------------------------------------------------------------------------- 1 | DECLARE @sql NVARCHAR(MAX) = ''; 2 | SELECT @sql += 'DROP TABLE ' + QUOTENAME(table_schema) + '.' + QUOTENAME(table_name) + ';' + CHAR(13) 3 | FROM information_schema.tables 4 | WHERE table_type = 'base table' 5 | AND table_schema = 'vendor_a'; 6 | 7 | EXEC sp_executesql @sql; -------------------------------------------------------------------------------- /schema-management/drop-all-tables/postgres_drop_tables_script.sql: -------------------------------------------------------------------------------- 1 | DO $$ 2 | DECLARE 3 | drop_statement text; 4 | BEGIN 5 | FOR drop_statement IN 6 | SELECT 'DROP TABLE IF EXISTS "' || table_name || '" CASCADE;' 7 | FROM information_schema.tables 8 | WHERE table_schema = 'vendor_b' 9 | LOOP 10 | EXECUTE drop_statement; 11 | END LOOP; 12 | END $$; -------------------------------------------------------------------------------- /schema-management/remove-primarykey-mysql/add-duplicate-id.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO Department_Duplicate(id,name,code) 2 | VALUES(1,'Data Science','DS'); 3 | -------------------------------------------------------------------------------- /schema-management/remove-primarykey-mysql/add-null-value.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO Department_Duplicate(id,name,code) 2 | VALUES(NULL,'Data Science','DS'); 3 | -------------------------------------------------------------------------------- /schema-management/remove-primarykey-mysql/add-second-pk-failed.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE REGISTRATION 2 | ADD PRIMARY KEY (course_id); 3 | -------------------------------------------------------------------------------- /schema-management/remove-primarykey-mysql/alter-table-add-pk.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE REGISTRATION 2 | ADD PRIMARY KEY (id); 3 | -------------------------------------------------------------------------------- /schema-management/remove-primarykey-mysql/alter-table-column-nullable.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE Department_Duplicate 2 | MODIFY id INT NULL; 3 | 4 | ALTER TABLE REGISTRATION 5 | MODIFY id INT NULL; 6 | -------------------------------------------------------------------------------- /schema-management/remove-primarykey-mysql/alter-table-drop-pk.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE Department_Duplicate 2 | DROP PRIMARY KEY; 3 | 4 | ALTER TABLE REGISTRATION 5 | DROP PRIMARY KEY; 6 | -------------------------------------------------------------------------------- /schema-management/remove-primarykey-mysql/create-department-duplicate.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE Department_Duplicate( 2 | id INT PRIMARY KEY, 3 | name VARCHAR (50), 4 | code VARCHAR (4) 5 | ); 6 | 7 | INSERT INTO Department_Duplicate(id,name,code) 8 | VALUES(1,'Data Science','DS'); 9 | -------------------------------------------------------------------------------- /schema-management/remove-primarykey-mysql/describe-table.sql: -------------------------------------------------------------------------------- 1 | DESC REGISTRATION; 2 | 3 | DESC Department_Duplicate; 4 | -------------------------------------------------------------------------------- /schema-management/remove-primarykey-mysql/drop-pk-in-transaction.sql: -------------------------------------------------------------------------------- 1 | START TRANSACTION; 2 | 3 | ALTER TABLE REGISTRATION 4 | DROP PRIMARY KEY; 5 | 6 | ROLLBACK; 7 | -------------------------------------------------------------------------------- /schema-management/remove-primarykey-mysql/list-table-constraints.sql: -------------------------------------------------------------------------------- 1 | SELECT constraint_name, constraint_type 2 | FROM information_schema.table_constraints 3 | WHERE table_name = 'registration'; 4 | -------------------------------------------------------------------------------- /schema-management/remove-primarykey-mysql/set-var.sql: -------------------------------------------------------------------------------- 1 | SET SESSION sql_require_primary_key = 'ON' 2 | 3 | ALTER TABLE REGISTRATION 4 | DROP PRIMARY KEY; 5 | -------------------------------------------------------------------------------- /schema-management/remove-primarykey-mysql/show-var-sql_require_primary_key.sql: -------------------------------------------------------------------------------- 1 | SHOW VARIABLES LIKE 'sql_require_primary_key'; 2 | 3 | SHOW SESSION VARIABLES LIKE 'sql_require_primary_key'; 4 | -------------------------------------------------------------------------------- /schema-management/table-existence/table-existence-mssql.sql: -------------------------------------------------------------------------------- 1 | IF EXISTS ( 2 | SELECT 1 FROM information_schema.tables 3 | WHERE table_schema='dbo' 4 | AND table_name='student' 5 | ) SELECT 1 ELSE SELECT 0; 6 | 7 | IF EXISTS ( 8 | SELECT 1 FROM sys.tables 9 | WHERE SCHEMA_NAME(schema_id) = 'dbo' 10 | AND NAME='student' 11 | ) SELECT 1 ELSE SELECT 0; -------------------------------------------------------------------------------- /schema-management/table-existence/table-existence-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT EXISTS ( 2 | SELECT * FROM information_schema.tables 3 | WHERE TABLE_SCHEMA = 'University' 4 | AND TABLE_NAME = 'Student' 5 | ) AS table_exist; -------------------------------------------------------------------------------- /schema-management/table-existence/table-existence-pg.sql: -------------------------------------------------------------------------------- 1 | SELECT EXISTS ( 2 | SELECT FROM information_schema.tables 3 | WHERE table_schema = 'public' 4 | AND table_name = 'student' 5 | ); 6 | 7 | SELECT EXISTS ( 8 | SELECT 1 FROM pg_tables 9 | WHERE schemaname = 'public' 10 | AND tablename = 'student' 11 | ); 12 | SELECT COALESCE(to_regclass('public.test_test_id_seq1') IS NOT NULL, FALSE); -------------------------------------------------------------------------------- /sql-constraints/drop-not-null/drop-null-mysql.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE Student 2 | MODIFY COLUMN national_id BIGINT NULL; -------------------------------------------------------------------------------- /sql-constraints/drop-not-null/drop-null-pg.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE student 2 | ALTER COLUMN national_id 3 | DROP NOT NULL; -------------------------------------------------------------------------------- /sql-constraints/drop-not-null/drop-null-sqlserver.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE Student 2 | ALTER COLUMN national_id BIGINT NULL; -------------------------------------------------------------------------------- /sql-constraints/drop-not-null/reset.sql: -------------------------------------------------------------------------------- 1 | -- PostgreSQL 2 | ALTER TABLE student 3 | ALTER COLUMN national_id 4 | SET NOT NULL; 5 | 6 | -- MySQL 7 | ALTER TABLE student 8 | MODIFY COLUMN national_id BIGINT NOT NULL; 9 | 10 | -- SQL Server 11 | ALTER TABLE student 12 | ALTER COLUMN national_id BIGINT NOT NULL; 13 | -------------------------------------------------------------------------------- /sql-constraints/list-table-foreign-keys/information-schema-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | table_name AS foreign_key_table, 3 | column_name AS foreign_key_column, 4 | referenced_table_name AS referenced_table, 5 | referenced_column_name AS referenced_column 6 | FROM 7 | information_schema.key_column_usage 8 | WHERE 9 | constraint_schema = 'University' 10 | AND table_name = 'Registration' 11 | AND referenced_table_name IS NOT NULL; 12 | -------------------------------------------------------------------------------- /sql-constraints/list-table-foreign-keys/show-create-table-mysql.sql: -------------------------------------------------------------------------------- 1 | SHOW CREATE TABLE Registration; -------------------------------------------------------------------------------- /sql-constraints/list-table-foreign-keys/stored-procedure-sql-server.sql: -------------------------------------------------------------------------------- 1 | EXEC sp_fkeys @pktable_name = 'Registration'; -------------------------------------------------------------------------------- /sql-generation/generate-insert-from-excel/new-data-insert.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO Student (id, name, national_id, birth_date, enrollment_date, graduation_date, gpa) 2 | VALUES (7, ‘George Bailey’, 3125372499, ‘1997-08-14’, ‘2017-09-01’, ‘2021-06-15’, 3.41); 3 | -------------------------------------------------------------------------------- /sql-generation/generate-insert-from-excel/student-records.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/sql-tutorials/cd7dd50e082cddbf50c3be20089272a8bad142f0/sql-generation/generate-insert-from-excel/student-records.xlsx -------------------------------------------------------------------------------- /sql-generation/generate-insert-from-excel/using-excel-formula.sql: -------------------------------------------------------------------------------- 1 | ="INSERT INTO students (id, name, national_id, birth_date, enrollment_date, graduation_date, gpa) VALUES (" & A2 & ", '" & B2 & "', '" & C2 & "', '" & D2 & "', '" & E2 & "', '" & F2 & "', " & G2 & ");" 2 | -------------------------------------------------------------------------------- /sql-queries-10/backup-single-table-and-database/copying table-temporary-database.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE TempBackupDB; 2 | 3 | USE TempBackupDB; 4 | SELECT * INTO Students FROM university.dbo.Student; 5 | 6 | BACKUP DATABASE TempBackupDB TO DISK = 'C:\Backup\TempBackupDB.bak'; -------------------------------------------------------------------------------- /sql-queries-10/backup-single-table-and-database/implementation-mysql.sh: -------------------------------------------------------------------------------- 1 | mysqldump -h localhost -P 3306 -u user -p university student > student_backup.sql 2 | 3 | cat student_backup.sql -------------------------------------------------------------------------------- /sql-queries-10/backup-single-table-and-database/implementation-postgres.sh: -------------------------------------------------------------------------------- 1 | pg_dump -h localhost -p 5432 -U user -d university -t student -f student_backup.sql 2 | 3 | cat student_backup.sql -------------------------------------------------------------------------------- /sql-queries-10/backup-single-table-and-database/using-mssql-scripter.sh: -------------------------------------------------------------------------------- 1 | pip install mssql-scripter 2 | 3 | mssql-scripter -S localhost -d university -U user -P password --script-create --script-data --include-objects student --output-file student_backup.sql 4 | 5 | cat student_backup.sql -------------------------------------------------------------------------------- /sql-queries-10/backup-single-table-and-database/using-sqlpackage.sh: -------------------------------------------------------------------------------- 1 | sqlpackage /Action:Export /SourceServerName:localhost /SourceDatabaseName:university /SourceUser:user /SourcePassword:password /TargetFile:student_backup.bacpac /Table:student 2 | 3 | -------------------------------------------------------------------------------- /sql-queries-10/checking-database-connectivity/mysql.env: -------------------------------------------------------------------------------- 1 | MYSQL_HOST=localhost 2 | MYSQL_PORT=3306 3 | MYSQL_USER=root 4 | MYSQL_PASS=MySQL2024 5 | MYSQL_DB=University -------------------------------------------------------------------------------- /sql-queries-10/checking-database-connectivity/postgresql.env: -------------------------------------------------------------------------------- 1 | DB_HOST=localhost 2 | DB_PORT=5432 3 | DB_USER=user 4 | DB_PASS=Password2024 5 | DB_NAME=University -------------------------------------------------------------------------------- /sql-queries-10/generate-all-indexes-in-database/implementation-in-mysql_extended.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | TABLE_NAME, 3 | INDEX_NAME, 4 | COLUMN_NAME, 5 | NON_UNIQUE, 6 | INDEX_TYPE 7 | FROM 8 | information_schema.STATISTICS 9 | WHERE 10 | TABLE_SCHEMA = 'University' 11 | ORDER BY 12 | TABLE_NAME, 13 | INDEX_NAME, 14 | SEQ_IN_INDEX; -------------------------------------------------------------------------------- /sql-queries-10/generate-all-indexes-in-database/implementation-in-mysql_original.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | TABLE_NAME, 3 | INDEX_NAME, 4 | COLUMN_NAME 5 | FROM 6 | information_schema.STATISTICS 7 | WHERE 8 | TABLE_SCHEMA = 'University' 9 | ORDER BY 10 | TABLE_NAME, 11 | INDEX_NAME, 12 | SEQ_IN_INDEX; -------------------------------------------------------------------------------- /sql-queries-10/generate-all-indexes-in-database/implementation-in-postgres_original.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | schemaname, 3 | tablename, 4 | indexname, 5 | indexdef 6 | FROM 7 | pg_indexes 8 | WHERE 9 | schemaname = 'public' 10 | ORDER BY 11 | tablename, 12 | indexname; -------------------------------------------------------------------------------- /sql-queries-10/get-table-sizes-mysql/show-table-status.sql: -------------------------------------------------------------------------------- 1 | SHOW TABLE STATUS FROM `university` LIKE 'department'\G 2 | -------------------------------------------------------------------------------- /sql-queries-10/get-table-sizes-mysql/sql-query-aggregate-table-sizes.sql: -------------------------------------------------------------------------------- 1 | SELECT ENGINE, 2 | SUM(table_rows) 'Total Number Of ROWS', 3 | FORMAT_BYTES(SUM(data_length)) 'Total Table DATA', 4 | FORMAT_BYTES(SUM(index_length)) 'Total Index DATA', 5 | FORMAT_BYTES(SUM(data_length) + SUM(index_length)) 'Total Size' 6 | FROM information_schema.TABLES 7 | WHERE TABLE_SCHEMA IN ('university') 8 | GROUP BY engine 9 | ORDER BY SUM(DATA_length) DESC; 10 | -------------------------------------------------------------------------------- /sql-queries-10/not-equals-operator/not-equals.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Department 3 | WHERE code != 'CS'; 4 | 5 | SELECT * 6 | FROM Department 7 | WHERE code <> 'CS'; -------------------------------------------------------------------------------- /sql-queries-10/optimize-all-tables-mysql/optimize-all-tables-with-mysqlcheck.cmd: -------------------------------------------------------------------------------- 1 | $ mysqlcheck -u root -o University 2 | 3 | $ mysqlcheck -u root -o University_myisam 4 | 5 | $ mysqlcheck -u root -o --databases University University_myisam 6 | 7 | $ mysqlcheck -u root -o --all-databases 8 | -------------------------------------------------------------------------------- /sql-queries-10/optimize-all-tables-mysql/optimize-all-tables-with-optimize-table-sql-stmt.sql: -------------------------------------------------------------------------------- 1 | OPTIMIZE TABLE Course, Department, Exam, Faculty, Prerequisite, Program, 2 | Registration, Specification, Student, Teaching\G 3 | -------------------------------------------------------------------------------- /sql-queries-10/update-multiple-different-rows/update-multiple-different-rows.sql: -------------------------------------------------------------------------------- 1 | UPDATE users SET user_type = 'ADULT' WHERE age >= 18; 2 | UPDATE users SET user_type = 'JUNIOR' WHERE age < 18; 3 | 4 | UPDATE users SET user_type = 5 | (CASE 6 | WHEN age >= 18 THEN 'ADULT' 7 | WHEN age < 18 THEN 'JUNIOR' 8 | END); -------------------------------------------------------------------------------- /sql-queries-10/where-1-equals-0/all-dbs.sql: -------------------------------------------------------------------------------- 1 | SELECT name FROM Student WHERE 1=0; 2 | 3 | SELECT * FROM Student WHERE 1=0; 4 | 5 | DELETE FROM Student WHERE id > 100 AND 1 = 0; 6 | 7 | SELECT * FROM Student WHERE 1 = 0 8 | -- Dynamic conditions 9 | OR GPA < 2 10 | OR GPA IS NULL; -------------------------------------------------------------------------------- /sql-queries-10/where-1-equals-0/mysql.sql: -------------------------------------------------------------------------------- 1 | -- Works in MySQL 2 | CREATE TABLE StudentTemp AS SELECT * FROM Student WHERE 1=0; 3 | -------------------------------------------------------------------------------- /sql-queries-10/where-1-equals-0/pg-mssql.sql: -------------------------------------------------------------------------------- 1 | -- Works in SQL Server and Postgres 2 | SELECT * INTO StudentTemp FROM Student WHERE 1=0; 3 | -------------------------------------------------------------------------------- /sql-queries-11/Save_PostgreSQL_Result_to_File/Save_PostgreSQL_Result_to_File.sql: -------------------------------------------------------------------------------- 1 | --Using \o Command 2 | \o sql_result.txt 3 | SELECT * from Student; 4 | \o 5 | 6 | 7 | --Using Command Line Redirection 8 | psql -d university -c "SELECT * from Course;" > /var/lib/postgresql/course_data.txt 9 | 10 | 11 | --Using COPY TO SQL 12 | COPY Department TO '/var/lib/postgresql/res.csv' DELIMITER ',' CSV HEADER; 13 | -------------------------------------------------------------------------------- /sql-queries-11/duplicate-insert-row-same-table-with-auto-increment/create-table.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE department_copy 2 | TABLE department; 3 | 4 | DELETE 5 | FROM department_copy; 6 | 7 | ALTER TABLE department_copy 8 | MODIFY COLUMN id INT UNIQUE NULL AUTO_INCREMENT; 9 | -------------------------------------------------------------------------------- /sql-queries-11/duplicate-insert-row-same-table-with-auto-increment/duplicate-entry-example.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO department_copy (id, name, code) 2 | SELECT 1, name, code 3 | FROM department_copy 4 | WHERE id = 1; 5 | -------------------------------------------------------------------------------- /sql-queries-11/duplicate-insert-row-same-table-with-auto-increment/find-auto-increment-column.sql: -------------------------------------------------------------------------------- 1 | SELECT COLUMN_NAME 2 | FROM INFORMATION_SCHEMA.COLUMNS 3 | WHERE TABLE_NAME = 'department_copy' 4 | AND EXTRA LIKE '%auto_increment%'; 5 | -------------------------------------------------------------------------------- /sql-queries-11/duplicate-insert-row-same-table-with-auto-increment/insert-select-example.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO department_copy (name, code) 2 | SELECT name, code 3 | FROM department_copy 4 | WHERE id = 1; 5 | -------------------------------------------------------------------------------- /sql-queries-11/duplicate-insert-row-same-table-with-auto-increment/insert-select-using-specific-id.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO department_copy (id, name, code) 2 | SELECT 11, name, code 3 | FROM department_copy 4 | WHERE id = 1; 5 | -------------------------------------------------------------------------------- /sql-queries-11/sum-distinct-rows/distinct-within-subquery.sql: -------------------------------------------------------------------------------- 1 | SELECT SUM(credits) FROM (SELECT DISTINCT textbook, credits FROM Course) AS distinct_rows; 2 | SELECT SUM(credits) AS distinct_credits FROM (SELECT DISTINCT textbook, credits FROM Course) AS distinct_rows; 3 | -------------------------------------------------------------------------------- /sql-queries-11/sum-distinct-rows/sum-with-cte.sql: -------------------------------------------------------------------------------- 1 | WITH unique_textbooks AS (SELECT DISTINCT textbook, credits FROM Course) SELECT SUM(credits) FROM unique_textbooks; 2 | -------------------------------------------------------------------------------- /sql-queries-11/sum-distinct-rows/union-within-subquery.sql: -------------------------------------------------------------------------------- 1 | SELECT SUM(credits) AS distinct_credits FROM (SELECT textbook, credits FROM Course UNION SELECT textbook, credits FROM Course) AS combined; 2 | SELECT textbook, credits FROM Course UNION SELECT textbook, credits FROM Course; 3 | -------------------------------------------------------------------------------- /sql-queries-2/join-vs-union/join-example.sql: -------------------------------------------------------------------------------- 1 | SELECT Faculty.name AS FacultyName, Department.name AS DepartmentName 2 | FROM Faculty 3 | INNER JOIN Department ON Faculty.department_id = Department.id; -------------------------------------------------------------------------------- /sql-queries-2/join-vs-union/union-example.sql: -------------------------------------------------------------------------------- 1 | SELECT name AS Name FROM Department 2 | UNION 3 | SELECT name AS Name FROM Faculty; -------------------------------------------------------------------------------- /sql-queries-2/security/list-grants/mssql.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | dp.class_desc AS object_type, 3 | OBJECT_NAME(dp.major_id) AS object_name, 4 | USER_NAME(dp.grantee_principal_id) AS grantee, 5 | dp.permission_name, dp.state_desc 6 | FROM sys.database_permissions dp 7 | WHERE USER_NAME(dp.grantee_principal_id) IN ('demo_user', 'demo_read_only_user'); -------------------------------------------------------------------------------- /sql-queries-2/security/list-grants/mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | grantee, 3 | table_schema, 4 | table_name, 5 | privilege_type 6 | FROM information_schema.TABLE_PRIVILEGES 7 | WHERE grantee IN ("'demo_user'@'localhost'", "'demo_read_only_user'@'localhost'") -------------------------------------------------------------------------------- /sql-queries-2/security/list-grants/postgres.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | grantee, 3 | table_schema, 4 | table_name, 5 | privilege_type 6 | FROM information_schema.role_table_grants 7 | WHERE grantee IN ('demo_user', 'demo_read_only_user'); -------------------------------------------------------------------------------- /sql-queries-2/select-record/except-mssql.sql: -------------------------------------------------------------------------------- 1 | SELECT c.id, c.name, c.textbook, c.credits, c.is_active, c.department_id 2 | FROM Course c 3 | EXCEPT 4 | SELECT c.id, c.name, c.textbook, c.credits, c.is_active, c.department_id 5 | FROM Course c 6 | JOIN Registration r ON c.id = r.course_id; 7 | -------------------------------------------------------------------------------- /sql-queries-2/select-record/left-join-with-null.sql: -------------------------------------------------------------------------------- 1 | SELECT c.* 2 | FROM Course c 3 | LEFT JOIN Registration r ON c.id = r.course_id 4 | WHERE r.course_id IS NULL; 5 | -------------------------------------------------------------------------------- /sql-queries-2/select-record/not-exists.sql: -------------------------------------------------------------------------------- 1 | SELECT c.* 2 | FROM Course c 3 | WHERE NOT EXISTS ( 4 | SELECT 1 5 | FROM Registration r 6 | WHERE c.id = r.course_id 7 | ); 8 | -------------------------------------------------------------------------------- /sql-queries-2/select-record/not-in.sql: -------------------------------------------------------------------------------- 1 | SELECT c.id, c.name, c.textbook, c.credits, c.is_active, c.department_id 2 | FROM Course c 3 | WHERE c.id NOT IN ( 4 | SELECT r.course_id 5 | FROM Registration r 6 | ); 7 | -------------------------------------------------------------------------------- /sql-queries-2/self-Join-table-twice/self-join-find-duplicates.sql: -------------------------------------------------------------------------------- 1 | SELECT f1.id AS id1, 2 | f1.name AS name1, 3 | f1.national_id AS national_id1, 4 | f1.position AS position1, 5 | f2.id AS id2, 6 | f2.name AS name2, 7 | f2.national_id AS national_id2, 8 | f2.position AS position2 9 | FROM Faculty f1 10 | JOIN Faculty f2 ON f1.national_id = f2.national_id 11 | AND f1.id <> f2.id 12 | ORDER BY f1.national_id, 13 | f1.start_date; -------------------------------------------------------------------------------- /sql-queries-2/self-Join-table-twice/self-join-query-data.sql: -------------------------------------------------------------------------------- 1 | SELECT f1.name AS faculty_name, 2 | f1.position AS current_position, 3 | f1.start_date AS current_start_date, 4 | f1.end_date AS current_end_date, 5 | f2.position AS previous_position, 6 | f2.start_date AS previous_start_date, 7 | f2.end_date AS previous_end_date 8 | FROM Faculty f1 9 | LEFT JOIN Faculty f2 ON f1.national_id = f2.national_id 10 | AND f1.start_date > f2.end_date 11 | ORDER BY f1.name, 12 | f1.start_date; -------------------------------------------------------------------------------- /sql-queries-2/self-Join-table-twice/simple-self-join.sql: -------------------------------------------------------------------------------- 1 | SELECT x.name, x.position, x.national_id, y.name, y.position, y.national_id 2 | FROM Faculty x 3 | JOIN Faculty y ON x.id = y.id; -------------------------------------------------------------------------------- /sql-queries-2/set-and-alter-default/alter-default-mysql.sql: -------------------------------------------------------------------------------- 1 | -- Set the default value for a Column 2 | ALTER TABLE 3 | Course 4 | ALTER COLUMN 5 | is_active 6 | SET 7 | DEFAULT 'Yes'; 8 | 9 | -- Drop the default value for a Column 10 | ALTER TABLE 11 | Course 12 | ALTER COLUMN 13 | is_active DROP DEFAULT; -------------------------------------------------------------------------------- /sql-queries-2/set-and-alter-default/alter-default-postgresql.sql: -------------------------------------------------------------------------------- 1 | -- Set the default value for a Column 2 | ALTER TABLE 3 | Course 4 | ALTER COLUMN 5 | is_active 6 | SET 7 | DEFAULT 'Yes'; 8 | 9 | -- Drop the default value for a Column 10 | ALTER TABLE 11 | Course 12 | ALTER COLUMN 13 | is_active DROP DEFAULT; -------------------------------------------------------------------------------- /sql-queries-2/sql-count-diff/count-diff.sql: -------------------------------------------------------------------------------- 1 | select * 2 | FROM Department; 3 | 4 | select COUNT(*) 5 | FROM Department; 6 | 7 | select COUNT(id) 8 | FROM Department; 9 | 10 | select COUNT(name) 11 | FROM Department; 12 | 13 | select COUNT(DISTINCT id) 14 | FROM Department; 15 | 16 | select COUNT(DISTINCT name) 17 | FROM Department; 18 | -------------------------------------------------------------------------------- /sql-queries-2/sql-distinct/distinct-values.sql: -------------------------------------------------------------------------------- 1 | 2 | SELECT * 3 | FROM Employees; 4 | 5 | SELECT COUNT(DISTINCT department) AS uniq_dept 6 | FROM Employees; 7 | 8 | SELECT department, COUNT(*) 9 | FROM Employees 10 | GROUP BY department; 11 | 12 | SELECT department, COUNT(*) 13 | FROM Employees 14 | GROUP BY department 15 | ORDER BY count DESC; 16 | -------------------------------------------------------------------------------- /sql-queries-2/sql-multiple-counts-with-single-query/using-case-in-sum.sql: -------------------------------------------------------------------------------- 1 | -- Display first 10 records in the exam table 2 | SELECT * FROM Exam LIMIT 10; 3 | 4 | -- using CASE in SUM 5 | SELECT COUNT(*) as total, 6 | SUM(CASE WHEN semester = 'FALL' THEN 1 ELSE 0 END) AS fall_count, 7 | SUM(CASE WHEN semester = 'SPRING' THEN 1 ELSE 0 END) AS spring_count 8 | FROM Exam; -------------------------------------------------------------------------------- /sql-queries-2/sql-multiple-counts-with-single-query/using-if-in-count.sql: -------------------------------------------------------------------------------- 1 | -- using if in count 2 | SELECT COUNT(*) AS total, 3 | COUNT(IF(semester='FALL', 1, NULL)) AS fall_count, 4 | COUNT(IF(semester='SPRING', 1, NULL)) AS spring_count 5 | FROM Exam; -------------------------------------------------------------------------------- /sql-queries-2/sql-multiple-counts-with-single-query/using-subqueries.sql: -------------------------------------------------------------------------------- 1 | -- using subqueries for multiple counts 2 | SELECT COUNT(*) AS total_count, 3 | (SELECT COUNT(*) FROM Exam WHERE semester = 'FALL') AS fall_count, 4 | (SELECT COUNT(*) FROM Exam WHERE semester = 'SPRING') AS spring_count 5 | FROM Exam; -------------------------------------------------------------------------------- /sql-queries-3/concatenate-null/select-concat-coalesce-null.sql: -------------------------------------------------------------------------------- 1 | SELECT id, CONCAT(COALESCE(name, ''), ' (', COALESCE(code, 'NULL'), ')') AS department_info FROM Department; 2 | -------------------------------------------------------------------------------- /sql-queries-3/concatenate-null/select-concat-null.sql: -------------------------------------------------------------------------------- 1 | SELECT id, CONCAT(name, ' (', code, ')') AS department_info FROM Department; 2 | -------------------------------------------------------------------------------- /sql-queries-3/concatenate-null/select-concat-ws-null.sql: -------------------------------------------------------------------------------- 1 | SELECT id, CONCAT_WS(' ', name, CONCAT('(', code, ')')) AS department_info FROM Department; 2 | 3 | -------------------------------------------------------------------------------- /sql-queries-3/concatenate-null/select-or-operator-null.sql: -------------------------------------------------------------------------------- 1 | SELECT id, COALESCE(name, '') || ' (' || COALESCE(code, '') || ')' AS department_info FROM Department; 2 | 3 | -------------------------------------------------------------------------------- /sql-queries-3/group-by-on-multiple-columns/basic-usage-example.sql: -------------------------------------------------------------------------------- 1 | SELECT department_id, COUNT(*) AS program_count 2 | FROM Program 3 | GROUP BY department_id; -------------------------------------------------------------------------------- /sql-queries-3/group-by-on-multiple-columns/multiple-columns-example.sql: -------------------------------------------------------------------------------- 1 | SELECT department_id, type, COUNT(*) AS program_count 2 | FROM Program 3 | GROUP BY department_id, type; -------------------------------------------------------------------------------- /sql-queries-3/group-by-on-multiple-columns/using-having-on-multiple-columns-example.sql: -------------------------------------------------------------------------------- 1 | SELECT department_id, type, COUNT(*) AS program_count 2 | FROM Program 3 | GROUP BY department_id, type 4 | HAVING COUNT(*) > 1; -------------------------------------------------------------------------------- /sql-queries-3/group-by-on-multiple-columns/using-join-on-multiple-columns-example.sql: -------------------------------------------------------------------------------- 1 | SELECT d.name AS department_name, p.type, COUNT(*) AS program_count 2 | FROM Program p 3 | JOIN Department d ON p.department_id = d.id 4 | GROUP BY d.name, p.type; -------------------------------------------------------------------------------- /sql-queries-3/group-by-on-multiple-columns/using-nested-on-multiple-columns-example.sql: -------------------------------------------------------------------------------- 1 | SELECT department_name, type, program_count, MIN(start_date) AS earliest_start_date 2 | FROM ( 3 | SELECT d.name AS department_name, p.type, COUNT(*) AS program_count, p.start_date 4 | FROM Program p 5 | JOIN Department d ON p.department_id = d.id 6 | GROUP BY d.name, p.type, p.start_date 7 | ) AS subquery 8 | GROUP BY department_name, type, program_count; -------------------------------------------------------------------------------- /sql-queries-3/group-by-on-multiple-columns/using-order-by-on-multiple-columns-example.sql: -------------------------------------------------------------------------------- 1 | SELECT d.name AS department_name, p.type, COUNT(*) AS program_count 2 | FROM Program p 3 | JOIN Department d ON p.department_id = d.id 4 | GROUP BY d.name, p.type 5 | ORDER BY d.name DESC, program_count DESC; -------------------------------------------------------------------------------- /sql-queries-3/join-vs-subquery/join-example.sql: -------------------------------------------------------------------------------- 1 | SELECT f.id AS faculty_id, f.name AS faculty_name, d.name AS department_name 2 | FROM Faculty f 3 | FULL OUTER JOIN Department d ON f.department_id = d.id; -------------------------------------------------------------------------------- /sql-queries-3/join-vs-subquery/subquery-join-example.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | f.id AS faculty_id, 3 | f.name AS faculty_name, 4 | d.name AS department_name, 5 | dept_counts.faculty_count 6 | FROM 7 | Faculty f 8 | JOIN 9 | Department d ON f.department_id = d.id 10 | JOIN 11 | (SELECT department_id, COUNT(*) AS faculty_count FROM Faculty GROUP BY department_id) dept_counts 12 | ON f.department_id = dept_counts.department_id; 13 | -------------------------------------------------------------------------------- /sql-queries-3/join-vs-subquery/subquery-nested-example.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | d.name 3 | FROM 4 | Department d 5 | WHERE 6 | (SELECT COUNT(*) FROM Faculty f WHERE f.department_id = d.id) > 7 | (SELECT MIN(faculty_count) 8 | FROM (SELECT COUNT(*) AS faculty_count 9 | FROM Faculty 10 | GROUP BY department_id) AS subquery); 11 | -------------------------------------------------------------------------------- /sql-queries-3/join-vs-subquery/subquery-select-example.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | d.name AS department_name, 3 | (SELECT COUNT(*) FROM Faculty f WHERE f.department_id = d.id) AS faculty_count 4 | FROM 5 | Department d; -------------------------------------------------------------------------------- /sql-queries-3/join-vs-subquery/subquery-where-example.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | f.name 3 | FROM 4 | Faculty f 5 | WHERE 6 | f.department_id IN (SELECT d.id FROM Department d WHERE (SELECT COUNT(*) FROM Faculty f WHERE f.department_id = d.id) > 17); 7 | -------------------------------------------------------------------------------- /sql-queries-3/order-number-strings/ordering-mssql.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Exam ORDER BY CAST(attendance_points AS INT); 2 | 3 | SELECT * FROM Exam ORDER BY CONVERT(INT, attendance_points); 4 | 5 | SELECT * FROM Exam ORDER BY attendance_points+0; -------------------------------------------------------------------------------- /sql-queries-3/order-number-strings/ordering-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Exam ORDER BY attendance_points+0; 2 | 3 | SELECT * FROM Exam ORDER BY CONVERT(attendance_points, SIGNED); 4 | 5 | SELECT * FROM Exam ORDER BY CAST(attendance_points AS SIGNED); -------------------------------------------------------------------------------- /sql-queries-3/order-number-strings/ordering-pg.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Exam ORDER BY CAST(attendance_points AS INT); 2 | 3 | SELECT * FROM Exam ORDER BY attendance_points::INT; 4 | 5 | -------------------------------------------------------------------------------- /sql-queries-3/order-number-strings/setup.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE Exam ADD attendance_points VARCHAR(10); 2 | DELETE FROM Exam WHERE id > 4; 3 | UPDATE Exam SET attendance_points = '100' WHERE id=1; 4 | UPDATE Exam SET attendance_points = '-25' WHERE id=2; 5 | UPDATE Exam SET attendance_points = '45' WHERE id=3; 6 | UPDATE Exam SET attendance_points = '-99' WHERE id=4; 7 | 8 | SELECT id, attendance_points FROM Exam; -------------------------------------------------------------------------------- /sql-queries-3/parameterizing-sql-in-clause/in-operator-example.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Program 3 | WHERE department_id IN (1, 2, 3); -------------------------------------------------------------------------------- /sql-queries-3/parameterizing-sql-in-clause/mysql-find-in-set-example.sql: -------------------------------------------------------------------------------- 1 | SET @student_ids = '1001,1003,1007'; 2 | 3 | PREPARE find_students_by_ids FROM 4 | "SELECT * FROM Student WHERE FIND_IN_SET(id, ?)"; 5 | 6 | EXECUTE find_students_by_ids USING @student_ids; 7 | -------------------------------------------------------------------------------- /sql-queries-3/parameterizing-sql-in-clause/mysql-prepared-statement-example.sql: -------------------------------------------------------------------------------- 1 | SET @StudentIds = '1001,1003,1007'; 2 | SET @sql = CONCAT('SELECT * FROM Student WHERE id IN (', @StudentIds, ')'); 3 | PREPARE stmt FROM @sql; 4 | EXECUTE stmt; 5 | -------------------------------------------------------------------------------- /sql-queries-3/parameterizing-sql-in-clause/postgres-prepared-statement-example.sql: -------------------------------------------------------------------------------- 1 | PREPARE find_programs_by_departments (text) AS 2 | SELECT * 3 | FROM Program 4 | WHERE department_id IN (SELECT unnest(string_to_array($1, ','))::int); 5 | 6 | EXECUTE find_programs_by_departments ('1, 2, 3'); 7 | -------------------------------------------------------------------------------- /sql-queries-3/parameterizing-sql-in-clause/sql-server-string-split-example.sql: -------------------------------------------------------------------------------- 1 | CREATE PROCEDURE find_students_by_ids 2 | @StudentIds VARCHAR(MAX) 3 | AS 4 | BEGIN 5 | SELECT * 6 | FROM Student 7 | WHERE id IN (SELECT value FROM STRING_SPLIT(@StudentIds, ',')) 8 | END; 9 | 10 | EXEC find_students_by_ids '1001,1003,1007'; -------------------------------------------------------------------------------- /sql-queries-3/parameterizing-sql-in-clause/sql-sever-dynamic-example.sql: -------------------------------------------------------------------------------- 1 | CREATE PROCEDURE find_students_by_ids 2 | @StudentIds VARCHAR(MAX) 3 | AS 4 | BEGIN 5 | DECLARE @SQL NVARCHAR(MAX) 6 | SET @SQL = 'SELECT * FROM Student WHERE id IN (' + @StudentIds + ')' 7 | EXEC sp_executesql @SQL 8 | END; 9 | 10 | EXEC find_students_by_ids '1001,1003,1007'; 11 | -------------------------------------------------------------------------------- /sql-queries-3/sql-distinct/distinct-values.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Employees; 3 | 4 | SELECT COUNT(DISTINCT department) AS uniq_dept 5 | FROM Employees; 6 | 7 | SELECT department, COUNT(*) 8 | FROM Employees 9 | GROUP BY department; 10 | 11 | SELECT department, COUNT(*) 12 | FROM Employees 13 | GROUP BY department 14 | ORDER BY count DESC; 15 | -------------------------------------------------------------------------------- /sql-queries-3/sql-if-within-where/case-in-where.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name 2 | FROM department 3 | WHERE CASE 4 | WHEN code = 'CS' THEN 1 5 | WHEN code = 'EC' THEN 1 6 | ELSE 0 7 | END = 1; -------------------------------------------------------------------------------- /sql-queries-3/sql-if-within-where/where-with-IIF.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name 2 | FROM department 3 | WHERE IIF(code = 'CS' OR code = 'EC', 1, 0) = 1; -------------------------------------------------------------------------------- /sql-queries-3/sql-if-within-where/where-with-boolean-operators.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM exam 3 | WHERE (grade = 'A+' AND student_id = 1001) 4 | OR (grade = 'A' AND student_id = 2009); -------------------------------------------------------------------------------- /sql-queries-3/sql-if-within-where/where-with-choose.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM exam 3 | WHERE CHOOSE( 4 | CASE 5 | WHEN grade = 'A+' AND student_id = 1001 THEN 1 6 | WHEN grade = 'A' AND student_id = 2009 THEN 1 7 | ELSE 0 8 | END, 9 | 1, 0, 0, 0 10 | ) = 1; -------------------------------------------------------------------------------- /sql-queries-4/autocommit-mysql/commit-and-chain-implicit-transaction.sql: -------------------------------------------------------------------------------- 1 | SET autocommit=0; -- Turn off autocommit mode 2 | 3 | /* SQL 4 | Statements within an implicit transaction */ 5 | 6 | COMMIT AND CHAIN; --Commit implicit transaction and start a new one 7 | -------------------------------------------------------------------------------- /sql-queries-4/autocommit-mysql/commit-implicit-transaction.sql: -------------------------------------------------------------------------------- 1 | SET autocommit = 0; --Turn off the autocommit mode 2 | 3 | /* Add data within an implicit transaction */ 4 | INSERT 5 | INTO Department 6 | VALUES(6,'Data Science','DS'); 7 | 8 | INSERT 9 | INTO Department 10 | VALUES(7,'Electrical Engineering','EE'); 11 | 12 | COMMIT; -- Commit the implicit transaction 13 | -------------------------------------------------------------------------------- /sql-queries-4/autocommit-mysql/commit-release.sql: -------------------------------------------------------------------------------- 1 | SET autocommit=0; --Turn off autocommit mode 2 | 3 | /* SQL 4 | Statements within an implicit transaction */ 5 | 6 | COMMIT RELEASE; --Commit implicit transaction and disconnect user session 7 | -------------------------------------------------------------------------------- /sql-queries-4/autocommit-mysql/implicit-commit.sql: -------------------------------------------------------------------------------- 1 | SET autocommit = 0; --Turn off Autocommit mode 2 | 3 | /* Add data within an implicit transaction */ 4 | 5 | INSERT 6 | INTO Department 7 | VALUES(6,'Data Science','DS'); 8 | 9 | SET autocommit = 1; -- Turn on Autocommit mode 10 | -------------------------------------------------------------------------------- /sql-queries-4/autocommit-mysql/implicit-transaction.sql: -------------------------------------------------------------------------------- 1 | SET autocommit=0; -- Turn off autocommit mode 2 | 3 | /* Show variable value */ 4 | 5 | SHOW VARIABLES 6 | LIKE 'autocommit'; 7 | 8 | /* Start an implicit transaction with a simple query */ 9 | SELECT * 10 | FROM Department; 11 | -------------------------------------------------------------------------------- /sql-queries-4/autocommit-mysql/rollback.sql: -------------------------------------------------------------------------------- 1 | SET autocommit=0; --Turn off Autocommit mode 2 | 3 | /* Delete data in an implicit transaction */ 4 | 5 | DELETE 6 | FROM Department; 7 | 8 | ROLLBACK; --Roll back the implicit transaction 9 | -------------------------------------------------------------------------------- /sql-queries-4/commit-rollback-savepoint/clean.sql: -------------------------------------------------------------------------------- 1 | /* Delete the new data from the Department table */ 2 | DELETE 3 | FROM Department 4 | WHERE id > 5; 5 | -------------------------------------------------------------------------------- /sql-queries-4/commit-rollback-savepoint/commit-and-chain.sql: -------------------------------------------------------------------------------- 1 | START TRANSACTION; -- Start a new transaction 2 | //SQL Statements 3 | COMMIT AND CHAIN; -- Commit and chain a transaction 4 | SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- This statement generates an error message 5 | -------------------------------------------------------------------------------- /sql-queries-4/commit-rollback-savepoint/commit-release.sql: -------------------------------------------------------------------------------- 1 | START TRANSACTION; -- Start a transaction 2 | //SQL statements 3 | COMMIT RELEASE; -- Commit transaction and disconnect user session 4 | SELECT 1; -- Starts a new user session 5 | -------------------------------------------------------------------------------- /sql-queries-4/commit-rollback-savepoint/commit.sql: -------------------------------------------------------------------------------- 1 | START TRANSACTION; -- Start a transaction 2 | 3 | /* Add some data to the Department table */ 4 | INSERT 5 | INTO Department 6 | VALUES(6,'Data Science','DS'); 7 | INSERT 8 | INTO Department 9 | VALUES(7,'Electrical Engineering','EE'); 10 | 11 | COMMIT; -- Commit the transaction 12 | -------------------------------------------------------------------------------- /sql-queries-4/commit-rollback-savepoint/implicit-commit.sql: -------------------------------------------------------------------------------- 1 | START TRANSACTION; -- Start a new transaction 2 | 3 | /* Add some data to the Department table */ 4 | INSERT 5 | INTO Department 6 | VALUES(6,'Data Science','DS'); 7 | 8 | CREATE TABLE t(i INTEGER); -- This statement causes an implicit commit 9 | ROLLBACK; -- This statement has no effect 10 | -------------------------------------------------------------------------------- /sql-queries-4/commit-rollback-savepoint/rollback-transaction.sql: -------------------------------------------------------------------------------- 1 | START TRANSACTION; -- Start a transaction 2 | 3 | /* Delete Data from Department */ 4 | DELETE 5 | FROM Department; 6 | 7 | ROLLBACK; -- Rollback the transaction 8 | -------------------------------------------------------------------------------- /sql-queries-4/commit-rollback-savepoint/savepoint.sql: -------------------------------------------------------------------------------- 1 | START TRANSACTION; -- Start a new transaction 2 | 3 | /* Add data to Department table */ 4 | INSERT 5 | INTO Department 6 | VALUES(6,'Data Science','DS'); 7 | 8 | SAVEPOINT sp1; -- Create a savepoint 9 | 10 | /* Delete a row of data from the Department table */ 11 | DELETE 12 | FROM Department 13 | WHERE id=6; 14 | 15 | ROLLBACK TO SAVEPOINT sp1; -- Rollback transaction to the savepoint 16 | 17 | RELEASE SAVEPOINT sp1; -- Release the savepoint 18 | -------------------------------------------------------------------------------- /sql-queries-4/different-join-order/inner_join.sql: -------------------------------------------------------------------------------- 1 | SELECT t.role, t.semester, t.year, f.name, c.name, c.credits 2 | FROM Teaching t 3 | INNER JOIN Faculty f ON t.faculty_id = f.id 4 | INNER JOIN Course c ON t.course_id = c.id; 5 | 6 | SELECT t.role, t.semester, t.year, f.name, c.name, c.credits 7 | FROM Course c 8 | INNER JOIN Teaching t ON c.id = t.course_id 9 | INNER JOIN Faculty f ON t.faculty_id = f.id; 10 | -------------------------------------------------------------------------------- /sql-queries-4/different-join-order/left_join_multiple_tables.sql: -------------------------------------------------------------------------------- 1 | SELECT t.id, c.id, f.id 2 | FROM Teaching t 3 | LEFT JOIN Course c ON t.course_id = c.id 4 | LEFT JOIN Faculty f ON t.faculty_id = f.id AND c.department_id = f.department_id; 5 | 6 | SELECT t.id, c.id, f.id 7 | FROM Teaching t 8 | LEFT JOIN Faculty f ON t.course_id = f.id 9 | LEFT JOIN Course c ON t.course_id = c.id AND c.department_id = f.department_id; 10 | -------------------------------------------------------------------------------- /sql-queries-4/different-join-order/left_join_two_tables.sql: -------------------------------------------------------------------------------- 1 | SELECT d.name, f.name 2 | FROM Department d 3 | LEFT JOIN Faculty f ON d.id = f.department_id; 4 | 5 | SELECT f.name, d.name 6 | FROM Faculty f 7 | LEFT JOIN Department d ON f.department_id = d.id; 8 | -------------------------------------------------------------------------------- /sql-queries-4/groupby-vs-distinct/distinct-examples.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT EXTRACT(YEAR FROM enrollment_date) AS enrollment_year 2 | FROM Student; 3 | 4 | SELECT DISTINCT EXTRACT(YEAR FROM enrollment_date) AS enrollment_year, gpa 5 | FROM Student; -------------------------------------------------------------------------------- /sql-queries-4/groupby-vs-distinct/groupby-example.sql: -------------------------------------------------------------------------------- 1 | SELECT EXTRACT(YEAR FROM enrollment_date) AS enrollment_year, COUNT(id) AS student_count 2 | FROM Student 3 | GROUP BY EXTRACT(YEAR FROM enrollment_date); 4 | 5 | SELECT EXTRACT(YEAR FROM enrollment_date) AS enrollment_year, AVG(gpa) AS average_gpa 6 | FROM Student 7 | GROUP BY EXTRACT(YEAR FROM enrollment_date); -------------------------------------------------------------------------------- /sql-queries-4/not-equal-to-with-where-clause/alternative-not-equal-to-operator.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, department_id 2 | FROM Course 3 | WHERE department_id != 1; -------------------------------------------------------------------------------- /sql-queries-4/not-equal-to-with-where-clause/basic-where-syntax.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, enrollment_date 2 | FROM Student 3 | WHERE YEAR(enrollment_date) = 2020; 4 | -------------------------------------------------------------------------------- /sql-queries-4/not-equal-to-with-where-clause/combining-not-equal-to-with-other-conditions.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, credits, department_id 2 | FROM Course 3 | WHERE department_id <> 1 4 | AND is_active = 'Yes' 5 | AND credits > 5; -------------------------------------------------------------------------------- /sql-queries-4/not-equal-to-with-where-clause/handling-null-values.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, gpa 2 | FROM Student 3 | WHERE gpa IS NOT NULL 4 | AND gpa <> 4.0; -------------------------------------------------------------------------------- /sql-queries-4/not-equal-to-with-where-clause/simple-not-equal-to-queries.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, gpa 2 | FROM Student 3 | WHERE gpa <> 4.0; -------------------------------------------------------------------------------- /sql-queries-4/not-equal-to-with-where-clause/standard-not-equal-to-operator.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, department_id 2 | FROM Course 3 | WHERE department_id <> 1; -------------------------------------------------------------------------------- /sql-queries-4/orderby-in-clause/select-case-orderby.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name 2 | FROM Student 3 | WHERE id IN (1110, 1101, 1617, 1107) 4 | ORDER BY CASE 5 | WHEN id = 1110 THEN 1 6 | WHEN id = 1101 THEN 2 7 | WHEN id = 1617 THEN 3 8 | WHEN id = 1107 THEN 4 9 | ELSE 5 10 | END; 11 | -------------------------------------------------------------------------------- /sql-queries-4/orderby-in-clause/select-cte-orderby.sql: -------------------------------------------------------------------------------- 1 | WITH OrderList AS ( 2 | SELECT 1110 AS id, 1 AS ord 3 | UNION ALL 4 | SELECT 1101 AS id, 2 AS ord 5 | UNION ALL 6 | SELECT 1617 AS id, 3 AS ord 7 | UNION ALL 8 | SELECT 1107 AS id, 4 AS ord 9 | ) 10 | SELECT s.id, s.name 11 | FROM Student s 12 | JOIN OrderList ol ON s.id = ol.id 13 | ORDER BY ol.ord; 14 | -------------------------------------------------------------------------------- /sql-queries-4/orderby-in-clause/select-field-orderby.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name 2 | FROM Student 3 | WHERE id IN (1110, 1101, 1617, 1107) 4 | ORDER BY FIELD(id, 1110, 1101, 1617, 1107); 5 | -------------------------------------------------------------------------------- /sql-queries-4/orderby-in-clause/select-temp-orderby.sql: -------------------------------------------------------------------------------- 1 | CREATE TEMPORARY TABLE temp_order (id INT, ord INT); 2 | INSERT INTO temp_order (id, ord) VALUES (1110, 1), (1101, 2), (1617, 3), (1107, 4); 3 | 4 | SELECT s.id, s.name 5 | FROM Student s 6 | JOIN temp_order t ON s.id = t.id 7 | ORDER BY t.ord; 8 | 9 | DROP TEMPORARY TABLE temp_order; 10 | -------------------------------------------------------------------------------- /sql-queries-4/physical-vs-logical-deletion/manual-deletion.sql: -------------------------------------------------------------------------------- 1 | DELETE FROM Exam WHERE student_id = 1007; 2 | DELETE FROM Registration WHERE student_id = 1007; 3 | 4 | DELETE FROM Student WHERE id = 1007; -------------------------------------------------------------------------------- /sql-queries-4/physical-vs-logical-deletion/physical-deletion.sql: -------------------------------------------------------------------------------- 1 | DELETE FROM department WHERE id = 1; 2 | 3 | SELECT * FROM department; -------------------------------------------------------------------------------- /sql-queries-4/physical-vs-logical-deletion/using-deleted_at Column.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE Student ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMP; 2 | 3 | UPDATE Student SET deleted_at = CURRENT_TIMESTAMP WHERE id = 1011; 4 | 5 | SELECT * FROM Student WHERE id = 1011; -------------------------------------------------------------------------------- /sql-queries-4/physical-vs-logical-deletion/using-is_deleted Column.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE Student ADD COLUMN is_deleted BOOLEAN DEFAULT FALSE; 2 | 3 | UPDATE Student SET is_deleted = TRUE WHERE id = 1010; 4 | 5 | SELECT * FROM Student WHERE is_deleted = FALSE; -------------------------------------------------------------------------------- /sql-queries-4/retrieve-size-table/using pg_table_size-function-postgres.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | schemaname AS schema_name, 3 | tablename AS table_name, 4 | pg_size_pretty(pg_table_size(schemaname || '.' || tablename)) AS table_size 5 | FROM 6 | pg_tables 7 | WHERE 8 | schemaname NOT IN ('information_schema', 'pg_catalog') 9 | ORDER BY 10 | pg_table_size(schemaname || '.' || tablename) DESC; 11 | -------------------------------------------------------------------------------- /sql-queries-4/retrieve-size-table/using-custom-query-postgres.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | relname AS table_name, 3 | pg_size_pretty(pg_total_relation_size(relid)) AS total_size, 4 | pg_size_pretty(pg_relation_size(relid)) AS data_size, 5 | pg_size_pretty(pg_total_relation_size(relid) - pg_relation_size(relid)) AS index_size 6 | FROM 7 | pg_stat_user_tables 8 | ORDER BY 9 | pg_total_relation_size(relid) DESC; 10 | -------------------------------------------------------------------------------- /sql-queries-4/retrieve-size-table/using-information-schema-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | table_schema AS 'Database', 3 | table_name AS 'Table', 4 | ROUND((data_length + index_length) / 1024 / 1024, 2) AS 'Size (MB)' 5 | FROM 6 | information_schema.tables 7 | WHERE 8 | table_schema = 'University' 9 | ORDER BY 10 | (data_length + index_length) DESC; 11 | -------------------------------------------------------------------------------- /sql-queries-4/retrieve-size-table/using-information-schema-postgres.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | table_schema, 3 | table_name, 4 | pg_size_pretty(pg_total_relation_size(table_schema || '.' || table_name)) AS table_size 5 | FROM 6 | information_schema.tables 7 | WHERE 8 | table_schema NOT IN ('information_schema', 'pg_catalog') 9 | ORDER BY 10 | pg_total_relation_size(table_schema || '.' || table_name) DESC; 11 | -------------------------------------------------------------------------------- /sql-queries-4/retrieve-size-table/using-show-table-status-mysql.sql: -------------------------------------------------------------------------------- 1 | SHOW TABLE STATUS FROM University; 2 | -------------------------------------------------------------------------------- /sql-queries-4/retrieve-size-table/using-sp_spaceused-sql-server.sql: -------------------------------------------------------------------------------- 1 | EXEC sp_MSforeachtable 'EXEC sp_spaceused ''?'''; 2 | 3 | -------------------------------------------------------------------------------- /sql-queries-4/trimming-strings-sql/apply-trim-function-columns.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | id, 3 | LTRIM(RTRIM(employee_name)) AS LR_trimmedEmployeeName, 4 | TRIM(job_title) AS T_trimmedJobTitle 5 | FROM Ventures; -------------------------------------------------------------------------------- /sql-queries-4/trimming-strings-sql/using-LTRIM.sql: -------------------------------------------------------------------------------- 1 | SELECT LTRIM(' Hello World ') AS TrimmedString; -------------------------------------------------------------------------------- /sql-queries-4/trimming-strings-sql/using-RTRIM.sql: -------------------------------------------------------------------------------- 1 | SELECT RTRIM(' Hello World ') AS TrimmedString; -------------------------------------------------------------------------------- /sql-queries-4/trimming-strings-sql/using-TRIM.sql: -------------------------------------------------------------------------------- 1 | SELECT TRIM(' Hello World ') AS TrimmedString; -------------------------------------------------------------------------------- /sql-queries-4/which-sql-require-commit-mysql/create-temporary-table.sql: -------------------------------------------------------------------------------- 1 | START TRANSACTION; -- Start a transaction 2 | 3 | /* Create a temporary table */ 4 | CREATE TEMPORARY TABLE tbl1 5 | SELECT * 6 | FROM Department; 7 | 8 | DROP TEMPORARY TABLE tbl1; -- Drop temporary table 9 | 10 | COMMIT; --Commit transaction 11 | -------------------------------------------------------------------------------- /sql-queries-4/which-sql-require-commit-mysql/delete.sql: -------------------------------------------------------------------------------- 1 | START TRANSACTION; --Start transaction 2 | 3 | /* Delete data*/ 4 | DELETE 5 | FROM Department 6 | WHERE id=4 OR id=5; 7 | 8 | COMMIT; --Commit transaction 9 | -------------------------------------------------------------------------------- /sql-queries-4/which-sql-require-commit-mysql/insert.sql: -------------------------------------------------------------------------------- 1 | START TRANSACTION; -- Start transaction 2 | 3 | /* Add data */ 4 | INSERT 5 | INTO Department 6 | VALUES(6,'Data Science','DS'); 7 | 8 | INSERT 9 | INTO Department 10 | VALUES(7,'Computer Engineering','CE'); 11 | 12 | COMMIT; -- Commit transaction 13 | -------------------------------------------------------------------------------- /sql-queries-4/which-sql-require-commit-mysql/replace.sql: -------------------------------------------------------------------------------- 1 | START TRANSACTION; -- Start transaction 2 | 3 | /* Replace data */ 4 | REPLACE 5 | INTO Department 6 | VALUES (5, 'Math', 'MA'); 7 | 8 | COMMIT; -- Commit transaction 9 | -------------------------------------------------------------------------------- /sql-queries-4/which-sql-require-commit-mysql/update.sql: -------------------------------------------------------------------------------- 1 | START TRANSACTION; --Start transaction 2 | 3 | /* Update data */ 4 | UPDATE Department 5 | SET code ='DSc' 6 | WHERE id=6; 7 | 8 | COMMIT; --Commit transaction 9 | -------------------------------------------------------------------------------- /sql-queries-5/String Concatenation and Aggregation in SQL/ifnull.sql: -------------------------------------------------------------------------------- 1 | USE University; SELECT CONCAT(IFNULL(textbook, 'No textbook assigned'), ' for ', IFNULL(name, 'Unknown Course')) AS course_description FROM Course; 2 | -------------------------------------------------------------------------------- /sql-queries-5/diff-setautocommit=1-starttransaction-mysql/autocommit-enabled.sql: -------------------------------------------------------------------------------- 1 | SET autocommit=1; --Turns on automatic transaction mode 2 | 3 | CREATE TABLE Department 4 | ( 5 | id INT PRIMARY KEY NOT Null, 6 | name VARCHAR (50), 7 | code VARCHAR (4), 8 | UNIQUE (id) 9 | ); -- Runs in a separate transaction 10 | 11 | SELECT SELECT * FROM DEPARTMENT; --Runs in a separate transaction 12 | 13 | INSERT INTO Department VALUES(6,'Data Science','DS'); --Runs in a separate transaction 14 | -------------------------------------------------------------------------------- /sql-queries-5/diff-setautocommit=1-starttransaction-mysql/set-autocommit.sql: -------------------------------------------------------------------------------- 1 | SET autocommit=1; --Enables autocommit mode 2 | 3 | /*These are equivalent*/ 4 | SET autocommit = DEFAULT; 5 | 6 | SET autocommit='ON'; 7 | SET @@autocommit = 'ON'; 8 | 9 | SET SESSION autocommit = 'ON'; 10 | SET @@SESSION.autocommit = 'ON'; 11 | 12 | SET LOCAL autocommit = 'ON'; 13 | SET @@LOCAL.autocommit = 'ON'; 14 | 15 | SELECT @@autocommit; --Query autocommit mode 16 | -------------------------------------------------------------------------------- /sql-queries-5/diff-setautocommit=1-starttransaction-mysql/start-transaction.sql: -------------------------------------------------------------------------------- 1 | START TRANSACTION; --Starts a single transaction 2 | 3 | /* SQL Statements*/ 4 | SELECT SELECT * FROM DEPARTMENT; 5 | INSERT INTO Department VALUES(6,'Data Science','DS'); 6 | INSERT INTO Department VALUES(7,'Computer Engineering','CE'); 7 | UPDATE Department SET name = 'Math' WHERE id=5; 8 | 9 | COMMIT; -- or ROLLBACK ends the single transaction 10 | -------------------------------------------------------------------------------- /sql-queries-5/export-sql-schema-without-data/customize-export-mysql.sh: -------------------------------------------------------------------------------- 1 | mysqldump -u user -p -h 127.0.0.1 --no-data --skip-triggers University > university_schema_no_triggers.sql 2 | 3 | -------------------------------------------------------------------------------- /sql-queries-5/export-sql-schema-without-data/customize-export-postgresql.sh: -------------------------------------------------------------------------------- 1 | pg_dump -U user -h 127.0.0.1 -s --no-indexes -f baeldung_no_indexes_schema.sql University -------------------------------------------------------------------------------- /sql-queries-5/export-sql-schema-without-data/export-entire-database-mysql.sh: -------------------------------------------------------------------------------- 1 | mysqldump -u user -p -h 127.0.0.1 --no-data University > university_schema.sql 2 | 3 | ls -lh 4 | 5 | cat university_schema.sql 6 | 7 | -------------------------------------------------------------------------------- /sql-queries-5/export-sql-schema-without-data/export-entire-database-postgresql.sh: -------------------------------------------------------------------------------- 1 | pg_dump -U user -h 127.0.0.1 -s -f university_schema.sql University 2 | 3 | cat university_schema.sql 4 | 5 | -------------------------------------------------------------------------------- /sql-queries-5/export-sql-schema-without-data/export-specific-schemas-postgresql.sh: -------------------------------------------------------------------------------- 1 | pg_dump -U user -h 127.0.0.1 -s -n public -f baeldung_public_schema.sql University -------------------------------------------------------------------------------- /sql-queries-5/export-sql-schema-without-data/export-specific-table-mysql.sh: -------------------------------------------------------------------------------- 1 | mysqldump -u user -p -h 127.0.0.1 --no-data University Student > university_student_schema.sql 2 | 3 | cat university_student_schema.sql 4 | 5 | -------------------------------------------------------------------------------- /sql-queries-5/removing-leading-zeros-in-sql/altering-student-table-MySQL-PostgreSQL.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE Student ADD COLUMN formatted_id VARCHAR(10); 2 | 3 | UPDATE Student 4 | SET formatted_id = CONCAT('0', id) 5 | WHERE id <= 2000; 6 | 7 | UPDATE Student 8 | SET formatted_id = id 9 | WHERE formatted_id IS NULL; 10 | -------------------------------------------------------------------------------- /sql-queries-5/removing-leading-zeros-in-sql/altering-student-table-SQL-Server.sql: -------------------------------------------------------------------------------- 1 | -- Add a new column to the Student table 2 | ALTER TABLE Student ADD formatted_id VARCHAR(10); 3 | 4 | -- Update the new column with leading zeros 5 | UPDATE Student 6 | SET formatted_id = '0' + CAST(id AS VARCHAR(10)) 7 | WHERE id <= 2000; 8 | 9 | -- Update remaining rows where formatted_id is NULL 10 | UPDATE Student 11 | SET formatted_id = CAST(id AS VARCHAR(10)) 12 | WHERE formatted_id IS NULL; 13 | -------------------------------------------------------------------------------- /sql-queries-5/removing-leading-zeros-in-sql/example-formatted-data.sql: -------------------------------------------------------------------------------- 1 | SELECT name, formatted_id 2 | FROM Student 3 | WHERE id in (1607,1007,2017,1010,1111,2008); -------------------------------------------------------------------------------- /sql-queries-5/removing-leading-zeros-in-sql/trimming-with-MySQL.sql: -------------------------------------------------------------------------------- 1 | SELECT name, formatted_id, 2 | TRIM(LEADING '0' FROM formatted_id) AS cleaned_id 3 | FROM Student 4 | WHERE id in (1607,1007,2017,1010,1111,2008); 5 | -------------------------------------------------------------------------------- /sql-queries-5/removing-leading-zeros-in-sql/trimming-with-PostgreSQL.sql: -------------------------------------------------------------------------------- 1 | SELECT name, formatted_id, 2 | LTRIM(formatted_id, '0') AS cleaned_id 3 | FROM Student 4 | WHERE id in (1607,1007,2017,1010,1111,2008); 5 | -------------------------------------------------------------------------------- /sql-queries-5/removing-leading-zeros-in-sql/trimming-with-SQL-Server.sql: -------------------------------------------------------------------------------- 1 | SELECT name, formatted_id, 2 | SUBSTRING(formatted_id, 3 | PATINDEX('%[^0]%', formatted_id), 4 | LEN(formatted_id) 5 | ) AS cleaned_id 6 | FROM Student 7 | WHERE id in (1607,1007,2017,1010,1111,2008); 8 | -------------------------------------------------------------------------------- /sql-queries-5/removing-leading-zeros-in-sql/using-CAST-function-MySQL.sql: -------------------------------------------------------------------------------- 1 | SELECT name, formatted_id, 2 | CAST(formatted_id AS UNSIGNED) AS cleaned_id 3 | FROM Student 4 | WHERE id in (1607,1007,2017,1010,1111,2008); -------------------------------------------------------------------------------- /sql-queries-5/removing-leading-zeros-in-sql/using-CAST-function-PostgreSQL.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | name, 3 | formatted_id, 4 | CAST(formatted_id AS INTEGER) AS cleaned_id 5 | FROM Student 6 | WHERE id in (1607,1007,2017,1010,1111,2008); -------------------------------------------------------------------------------- /sql-queries-5/removing-leading-zeros-in-sql/using-CAST-function-SQL-Server.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | name, 3 | formatted_id, 4 | CAST(formatted_id AS INT) AS cleaned_id 5 | FROM Student 6 | WHERE id in (1607,1007,2017,1010,1111,2008); -------------------------------------------------------------------------------- /sql-queries-5/removing-leading-zeros-in-sql/using-CONVERT-function-with-MySQL.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | name, 3 | formatted_id, 4 | CONVERT(formatted_id, UNSIGNED) AS cleaned_id 5 | FROM Student 6 | WHERE id IN (1607,1007,2017,1010,1111,2008); -------------------------------------------------------------------------------- /sql-queries-5/removing-leading-zeros-in-sql/using-CONVERT-function-with-PosgreSQL.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | name, 3 | formatted_id, 4 | formatted_id::INTEGER AS cleaned_id 5 | FROM Student 6 | WHERE id IN (1607,1007,2017,1010,1111,2008); -------------------------------------------------------------------------------- /sql-queries-5/removing-leading-zeros-in-sql/using-CONVERT-function-with-SQL-Server.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | name, 3 | formatted_id, 4 | CONVERT(INT, formatted_id) AS cleaned_id 5 | FROM Student 6 | WHERE id in (1607,1007,2017,1010,1111,2008); -------------------------------------------------------------------------------- /sql-queries-5/select-butoom-N-row-in-sql/using-orderby-and-limit-postgresql.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, gpa 2 | FROM Student 3 | ORDER BY gpa ASC 4 | LIMIT 5; -------------------------------------------------------------------------------- /sql-queries-5/select-butoom-N-row-in-sql/using-orderby-and-offset-fetch-clause-sqlserver.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, gpa 2 | FROM Student 3 | WHERE gpa IS NOT NULL 4 | ORDER BY gpa ASC 5 | OFFSET (SELECT COUNT(*) FROM Student WHERE gpa IS NOT NULL) - 5 ROWS 6 | FETCH NEXT 5 ROWS ONLY; -------------------------------------------------------------------------------- /sql-queries-5/select-butoom-N-row-in-sql/using-rownumber-window-function-postgresql.sql: -------------------------------------------------------------------------------- 1 | WITH RankedStudents AS ( 2 | SELECT id, name, gpa, 3 | ROW_NUMBER() OVER (ORDER BY gpa ASC) AS row_num 4 | FROM Student 5 | ) 6 | SELECT id, name, gpa 7 | FROM RankedStudents 8 | WHERE row_num <= 5; -------------------------------------------------------------------------------- /sql-queries-5/select-butoom-N-row-in-sql/using-rownumber-window-function-sqlserver.sql: -------------------------------------------------------------------------------- 1 | WITH RankedStudents AS ( 2 | SELECT id, name, gpa, 3 | ROW_NUMBER() OVER (ORDER BY gpa ASC) AS row_num 4 | FROM Student 5 | WHERE gpa IS NOT NULL 6 | ) 7 | SELECT id, name, gpa 8 | FROM RankedStudents 9 | WHERE row_num <= 5 10 | ORDER BY gpa ASC; -------------------------------------------------------------------------------- /sql-queries-5/select-butoom-N-row-in-sql/using-subqueries-with-orderby-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, gpa 2 | FROM ( 3 | SELECT id, name, gpa 4 | FROM Student 5 | ORDER BY gpa ASC 6 | LIMIT 5 7 | ) AS BottomStudents 8 | ORDER BY gpa ASC; 9 | -------------------------------------------------------------------------------- /sql-queries-5/turning-off-autocommit-mysql-client/README: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /sql-queries-5/turning-off-autocommit-mysql-client/batch-dml-explicit-transaction.sql: -------------------------------------------------------------------------------- 1 | START TRANSACTION; 2 | 3 | INSERT INTO Department 4 | VALUES(6,'Data Science','DS'); 5 | 6 | INSERT INTO Department 7 | VALUES(7,'Computer Engineering','CE'); 8 | 9 | UPDATE Department 10 | SET name = 'Math' 11 | WHERE id=5; 12 | 13 | COMMIT; 14 | -------------------------------------------------------------------------------- /sql-queries-5/turning-off-autocommit-mysql-client/batch-dml-implicit-transaction.sql: -------------------------------------------------------------------------------- 1 | SET AUTOCOMMIT='OFF'; 2 | 3 | DELETE 4 | FROM Department 5 | WHERE id=6 OR id=7; 6 | 7 | SAVEPOINT sp1; 8 | 9 | UPDATE Department 10 | SET name = 'Mathematics' 11 | WHERE id=5; 12 | 13 | ROLLBACK TO SAVEPOINT sp1; 14 | 15 | RELEASE SAVEPOINT sp1; 16 | 17 | COMMIT; 18 | -------------------------------------------------------------------------------- /sql-queries-5/turning-off-autocommit-mysql-client/persist-global-autocommit-off-setting.sql: -------------------------------------------------------------------------------- 1 | /*Use one of these to turn off global autocommit mode across server restarts in addition to for subsequent client sessions*/ 2 | SET PERSIST autocommit = 'OFF'; 3 | SET @@PERSIST.autocommit = 0; 4 | 5 | /*Use one of these to turn off global autocommit mode across server restarts only*/ 6 | SET PERSIST_ONLY autocommit = 'OFF'; 7 | SET @@PERSIST_ONLY.autocommit = 0; 8 | -------------------------------------------------------------------------------- /sql-queries-5/turning-off-autocommit-mysql-client/select-autocommit-global.sql: -------------------------------------------------------------------------------- 1 | /* Use one of the statements to find the global scoped setting for autocommit system variable */ 2 | 3 | SELECT @@GLOBAL.autocommit; 4 | 5 | SHOW GLOBAL VARIABLES LIKE 'autocommit'; 6 | 7 | SELECT * 8 | FROM performance_schema.global_variables 9 | WHERE VARIABLE_NAME = 'autocommit'; 10 | -------------------------------------------------------------------------------- /sql-queries-5/turning-off-autocommit-mysql-client/select-autocommit-session.sql: -------------------------------------------------------------------------------- 1 | /* Use one of the SELECT statements. */ 2 | SELECT @@autocommit; 3 | SELECT @@SESSION.autocommit; 4 | SELECT @@LOCAL.autocommit; 5 | 6 | /* Use one of the SHOW VARIABLES statements. */ 7 | SHOW VARIABLES LIKE 'autocommit'; 8 | SHOW SESSION VARIABLES LIKE 'autocommit' 9 | 10 | /* Query the perfrmance_schema */ 11 | SELECT * 12 | FROM performance_schema.session_variables 13 | WHERE VARIABLE_NAME = 'autocommit'; 14 | -------------------------------------------------------------------------------- /sql-queries-5/turning-off-autocommit-mysql-client/turn-off-autocommit-lock-unlock-tables.sql: -------------------------------------------------------------------------------- 1 | /*First Session*/ 2 | SET autocommit=0; 3 | 4 | LOCK TABLES Department WRITE, 5 | Program READ; 6 | 7 | INSERT INTO Department 8 | VALUES(6,'Data Science','DS'); 9 | 10 | COMMIT; 11 | 12 | /*Second Session*/ 13 | USE University; 14 | 15 | /*First Session*/ 16 | UNLOCK TABLES; 17 | 18 | /*Second Session*/ 19 | SELECT * FROM Department; 20 | -------------------------------------------------------------------------------- /sql-queries-5/turning-off-autocommit-mysql-client/turn-off-autocommit-session-level.sql: -------------------------------------------------------------------------------- 1 | /*Use one of these statements to turn off the autocommit mode at the session level*/ 2 | 3 | SET autocommit = 'OFF'; 4 | 5 | SET SESSION autocommit = 'OFF'; 6 | SET LOCAL autocommit = 'OFF'; 7 | SET @@SESSION.autocommit = 'OFF'; 8 | SET @@LOCAL.autocommit = 'OFF'; 9 | SET @@autocommit = 'OFF'; 10 | SET autocommit = 'OFF'; 11 | SET autocommit = 0; 12 | -------------------------------------------------------------------------------- /sql-queries-5/turning-off-autocommit-mysql-client/turn-off-autocommit-transaction-level.sql: -------------------------------------------------------------------------------- 1 | START TRANSACTION; -- This statement automatically turns off the autocommit mode 2 | 3 | SELECT THREAD_ID, 4 | STATE, 5 | TRX_ID, 6 | ACCESS_MODE, 7 | ISOLATION_LEVEL, 8 | AUTOCOMMIT FROM 9 | performance_schema.events_transactions_current; -- This statement can be used to find the autocommit mode in an active transaction 10 | 11 | SELECT * 12 | FROM DEPARTMENT; 13 | 14 | COMMIT; --This statement ends the transaction 15 | -------------------------------------------------------------------------------- /sql-queries-5/turning-off-autocommit-mysql-client/turn-off-global-autocommit.sql: -------------------------------------------------------------------------------- 1 | /*Use one of these statements to turn on global scope autocommit mode*/ 2 | 3 | SET GLOBAL autocommit = 'OFF'; 4 | 5 | SET @@GLOBAL.autocommit = 0; 6 | -------------------------------------------------------------------------------- /sql-queries-5/turning-off-autocommit-mysql-client/turn-on-autocommit.sql: -------------------------------------------------------------------------------- 1 | SET autocommit = DEFAULT; 2 | 3 | SET autocommit = 1; 4 | -------------------------------------------------------------------------------- /sql-queries-6/README: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /sql-queries-6/SUM-groupby-id/complex-aggregation-example.sql: -------------------------------------------------------------------------------- 1 | SELECT s.id, s.name, SUM(c.credits) AS student_credits 2 | FROM Student s 3 | LEFT JOIN Registration r ON s.id = r.student_id 4 | LEFT JOIN Course c ON r.course_id = c.id 5 | GROUP BY s.id, s.name; 6 | -------------------------------------------------------------------------------- /sql-queries-6/SUM-groupby-id/filter-group-result.sql: -------------------------------------------------------------------------------- 1 | SELECT department_id, SUM(credits) AS dept_total_credits 2 | FROM Course 3 | GROUP BY department_id 4 | HAVING SUM(credits) > 80; 5 | -------------------------------------------------------------------------------- /sql-queries-6/SUM-groupby-id/grouping-data.sql: -------------------------------------------------------------------------------- 1 | SELECT department_id, SUM(credits) AS dept_total_credits 2 | FROM Course 3 | GROUP BY department_id; 4 | -------------------------------------------------------------------------------- /sql-queries-6/SUM-groupby-id/handling-null-values.sql: -------------------------------------------------------------------------------- 1 | SELECT s.id, s.name, SUM(COALESCE(c.credits, 0)) AS student_credits 2 | FROM Student s 3 | LEFT JOIN Registration r ON s.id = r.student_id 4 | LEFT JOIN Course c ON r.course_id = c.id 5 | GROUP BY s.id, s.name; 6 | -------------------------------------------------------------------------------- /sql-queries-6/check-indexes-in-sql/using-SHOW-INDEX-mysql.sql: -------------------------------------------------------------------------------- 1 | SHOW INDEX FROM Student; -------------------------------------------------------------------------------- /sql-queries-6/check-indexes-in-sql/using-di-command-pg.sql: -------------------------------------------------------------------------------- 1 | \di -------------------------------------------------------------------------------- /sql-queries-6/check-indexes-in-sql/using-information_schema.STATISTICS-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT INDEX_NAME, COLUMN_NAME, SEQ_IN_INDEX, NON_UNIQUE, INDEX_TYPE 2 | FROM information_schema.STATISTICS 3 | WHERE TABLE_SCHEMA = 'University' AND TABLE_NAME = 'Exam'; -------------------------------------------------------------------------------- /sql-queries-6/check-indexes-in-sql/using-pg_catalog.pg_index-system-table.sql: -------------------------------------------------------------------------------- 1 | SELECT i.indexrelid::regclass AS index_name, 2 | array_to_string(array_agg(a.attname), ', ') AS index_columns 3 | FROM pg_index i 4 | JOIN pg_attribute a ON a.attnum = ANY(i.indkey) 5 | WHERE i.indrelid = 'course'::regclass 6 | GROUP BY i.indexrelid; 7 | -------------------------------------------------------------------------------- /sql-queries-6/check-indexes-in-sql/using-pg_indexes-system-catalog-pg.sql: -------------------------------------------------------------------------------- 1 | SELECT indexname, indexdef 2 | FROM pg_indexes 3 | WHERE tablename = 'student'; -------------------------------------------------------------------------------- /sql-queries-6/check-indexes-in-sql/using-sp_helpindex-sqlserver.sql: -------------------------------------------------------------------------------- 1 | EXEC sp_helpindex 'Student'; -------------------------------------------------------------------------------- /sql-queries-6/check-indexes-in-sql/using-sys.index_columns.sql: -------------------------------------------------------------------------------- 1 | SELECT i.name AS index_name, c.name AS column_name, ic.index_column_id 2 | FROM sys.indexes i 3 | JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id 4 | JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id 5 | WHERE i.object_id = OBJECT_ID('Student'); 6 | -------------------------------------------------------------------------------- /sql-queries-6/check-indexes-in-sql/using-sys.indexes-sqlserver.sql: -------------------------------------------------------------------------------- 1 | SELECT name AS index_name, type_desc, is_unique, is_primary_key 2 | FROM sys.indexes 3 | WHERE object_id = OBJECT_ID('Course') -------------------------------------------------------------------------------- /sql-queries-6/range-values/mssql.sql: -------------------------------------------------------------------------------- 1 | WITH number_range AS ( 2 | SELECT 1 AS number 3 | UNION ALL 4 | SELECT number + 1 FROM number_range 5 | WHERE number < 10 ) 6 | SELECT number FROM number_range; OPTION (MAXRECURSION 1000) -------------------------------------------------------------------------------- /sql-queries-6/range-values/mysql.sql: -------------------------------------------------------------------------------- 1 | WITH RECURSIVE numbers AS ( 2 | SELECT 5 AS number 3 | UNION ALL 4 | SELECT number + 1 FROM numbers 5 | WHERE number < 10 ) 6 | SELECT number FROM numbers; -------------------------------------------------------------------------------- /sql-queries-6/range-values/postgres.sql: -------------------------------------------------------------------------------- 1 | SELECT generate_series(1, 10) AS numbers: -------------------------------------------------------------------------------- /sql-queries-6/run-select-without-locking-mysql/autocommit-on-select-without-locks.sql: -------------------------------------------------------------------------------- 1 | SET autocommit=ON; --Set autocommit on 2 | 3 | SELECT * 4 | FROM Department; --Runs in a separate transaction without acquiring any locks 5 | 6 | SELECT * 7 | FROM DEPARTMENT 8 | FOR UPDATE; --Runs in a separate transaction without acquiring any locks 9 | 10 | SELECT * 11 | FROM DEPARTMENT 12 | FOR SHARE; --Runs in a separate transaction without acquiring any locks 13 | -------------------------------------------------------------------------------- /sql-queries-6/run-select-without-locking-mysql/innodb-status.sql: -------------------------------------------------------------------------------- 1 | SET GLOBAL innodb_status_output_locks=ON; --Enable InnoDB Lock monitor 2 | 3 | SHOW ENGINE INNODB STATUS; --List InnoDB status 4 | -------------------------------------------------------------------------------- /sql-queries-6/run-select-without-locking-mysql/plain-select.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM DEPARTMENT; 3 | -------------------------------------------------------------------------------- /sql-queries-6/run-select-without-locking-mysql/select-expressions-only.sql: -------------------------------------------------------------------------------- 1 | SELECT 1, 2 | SQRT(4), 3 | JSON_QUOTE('[a, b, c]'); 4 | -------------------------------------------------------------------------------- /sql-queries-6/run-select-without-locking-mysql/select-for-share.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM DEPARTMENT 3 | FOR SHARE; 4 | -------------------------------------------------------------------------------- /sql-queries-6/run-select-without-locking-mysql/select-for-update.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM DEPARTMENT 3 | FOR UPDATE; 4 | -------------------------------------------------------------------------------- /sql-queries-6/run-select-without-locking-mysql/select-sub-query.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE DEPARTMENT_copy 2 | AS SELECT * 3 | FROM DEPARTMENT; --Create a new table as a copy of the DEPARTMENT table 4 | 5 | SELECT * 6 | FROM DEPARTMENT_copy 7 | WHERE code = (SELECT code FROM DEPARTMENT WHERE id=5) 8 | FOR UPDATE; --Run a locking SELECT query on the DEPARTMENT table with a plain SELECT query as a sub-query 9 | -------------------------------------------------------------------------------- /sql-queries-6/run-select-without-locking-mysql/set-transaction-read-only.sql: -------------------------------------------------------------------------------- 1 | SET 2 | GLOBAL 3 | TRANSACTION 4 | READ ONLY; 5 | 6 | SET 7 | SESSION 8 | TRANSACTION 9 | READ ONLY; 10 | 11 | SET 12 | TRANSACTION 13 | READ ONLY; 14 | 15 | -------------------------------------------------------------------------------- /sql-queries-6/run-select-without-locking-mysql/update-query.sql: -------------------------------------------------------------------------------- 1 | UPDATE DEPARTMENT 2 | SET code='MA' 3 | WHERE id=5; 4 | -------------------------------------------------------------------------------- /sql-queries-6/run-sql-queries-on-csv-file/data.csv: -------------------------------------------------------------------------------- 1 | name,sex,age,weight,height 2 | Alex,M,41,74,170 3 | Bert,M,42,66,166 4 | Dave,M,39,72,167 5 | Elly,F,30,70,124 6 | Luke,M,34,72,163 7 | Omar,M,38,69,145 8 | Page,F,31,67,135 9 | Ruth,F,28,65,131 -------------------------------------------------------------------------------- /sql-queries-6/run-sql-queries-on-csv-file/example2_csv.py: -------------------------------------------------------------------------------- 1 | import duckdb 2 | 3 | # Run a query directly on the CSV file 4 | query = "SELECT AVG(weight) AS avg_weight FROM read_csv_auto('data.csv')" 5 | avg_weight = duckdb.query(query).to_df() 6 | print(avg_weight) 7 | 8 | # Another query to count individuals by gender 9 | count_gender_query = "SELECT sex, COUNT(*) AS count FROM read_csv_auto('data.csv') GROUP BY sex" 10 | count_gender = duckdb.query(count_gender_query).to_df() 11 | print(count_gender) 12 | -------------------------------------------------------------------------------- /sql-queries-6/run-sql-queries-on-csv-file/import-data-to-sqlite.sh: -------------------------------------------------------------------------------- 1 | sqlite3 :memory: -cmd '.mode csv' -cmd '.import data.csv my_table' -------------------------------------------------------------------------------- /sql-queries-6/run-sql-queries-on-csv-file/install-duckdb.sh: -------------------------------------------------------------------------------- 1 | pip install duckdb -------------------------------------------------------------------------------- /sql-queries-6/run-sql-queries-on-csv-file/install-pandas-and-pandasql.sh: -------------------------------------------------------------------------------- 1 | pip install pandas pandasql sqlalchemy==1.4.46 2 | 3 | -------------------------------------------------------------------------------- /sql-queries-6/run-sql-queries-on-csv-file/install-sqlite.sh: -------------------------------------------------------------------------------- 1 | # Intall SQLite 2 | sudo apt-get install sqlite3 3 | 4 | # Check version of SQLite 5 | sqlite3 --version -------------------------------------------------------------------------------- /sql-queries-6/run-sql-queries-on-csv-file/run-sql-queries-noninteractively.sh: -------------------------------------------------------------------------------- 1 | sqlite3 :memory: -cmd '.mode csv' -cmd '.import data.csv my_table' 'SELECT sex, COUNT(*) FROM my_table GROUP BY sex;' -------------------------------------------------------------------------------- /sql-queries-6/run-sql-queries-on-csv-file/running-example2_csv.py.sh: -------------------------------------------------------------------------------- 1 | python example2_csv.py -------------------------------------------------------------------------------- /sql-queries-6/run-sql-queries-on-csv-file/running-example_csv.py.sh: -------------------------------------------------------------------------------- 1 | python example_csv.py -------------------------------------------------------------------------------- /sql-queries-6/run-sql-queries-on-csv-file/running-sql-queries-sqlite.sql: -------------------------------------------------------------------------------- 1 | SELECT AVG(weight) FROM my_table; 2 | 3 | SELECT sex, COUNT(*) FROM my_table GROUP BY sex; 4 | -------------------------------------------------------------------------------- /sql-queries-6/sql-paginate-count/sql-paginate-count.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Faculty 3 | ORDER BY id 4 | OFFSET 1 5 | LIMIT 3; 6 | 7 | SELECT id, name, position, start_date, end_date, department_id, 8 | COUNT(*) OVER() AS full_count 9 | FROM Faculty; 10 | 11 | SELECT id, name, position, start_date, end_date, department_id, 12 | COUNT(*) OVER() AS full_count 13 | FROM Faculty 14 | ORDER BY id 15 | OFFSET 1 16 | LIMIT 4; 17 | -------------------------------------------------------------------------------- /sql-queries-7/Accessing-Query-Tables-within-subquery/correlated-subqueries.sql: -------------------------------------------------------------------------------- 1 | SELECT c.id, 2 | c.name, 3 | (SELECT COUNT(DISTINCT r.student_id) 4 | FROM Registration r 5 | WHERE r.course_id = c.id) AS enrolled_students 6 | FROM Course c 7 | WHERE c.credits > 5; -------------------------------------------------------------------------------- /sql-queries-7/Accessing-Query-Tables-within-subquery/correlated-subquery-cross-compatible-solution.sql: -------------------------------------------------------------------------------- 1 | SELECT s.name, 2 | (SELECT COUNT(*) 3 | FROM Registration r 4 | WHERE r.student_id = s.id) AS course_count 5 | FROM Student s 6 | ORDER BY course_count DESC; -------------------------------------------------------------------------------- /sql-queries-7/Accessing-Query-Tables-within-subquery/outer-query-reference.sql: -------------------------------------------------------------------------------- 1 | SELECT s.name, s.gpa 2 | FROM Student s 3 | WHERE s.gpa > ( 4 | SELECT AVG(s2.gpa) 5 | FROM Student s2 6 | WHERE s2.enrollment_date = s.enrollment_date 7 | ); 8 | -------------------------------------------------------------------------------- /sql-queries-7/Accessing-Query-Tables-within-subquery/outer-reference-FROM-clause-limitation.sql: -------------------------------------------------------------------------------- 1 | SELECT s.name, c.course_count 2 | FROM Student s 3 | JOIN ( 4 | SELECT student_id, COUNT(*) AS course_count 5 | FROM Registration 6 | WHERE student_id = s.id 7 | GROUP BY student_id 8 | ) c ON s.id = c.student_id; -------------------------------------------------------------------------------- /sql-queries-7/Accessing-Query-Tables-within-subquery/outer-reference-SELECT-clause.sql: -------------------------------------------------------------------------------- 1 | SELECT s.name, 2 | s.gpa, 3 | (SELECT COUNT(*) 4 | FROM Registration r 5 | WHERE r.student_id = s.id) AS total_registrations 6 | FROM Student s 7 | WHERE s.gpa >= 4.0; -------------------------------------------------------------------------------- /sql-queries-7/Accessing-Query-Tables-within-subquery/outer-reference-WHERE-clause.sql: -------------------------------------------------------------------------------- 1 | SELECT c.id, c.name 2 | FROM Course c 3 | WHERE EXISTS ( 4 | SELECT 1 5 | FROM Registration r 6 | WHERE r.course_id = c.id 7 | AND r.semester = 'SPRING' 8 | ); -------------------------------------------------------------------------------- /sql-queries-7/Accessing-Query-Tables-within-subquery/reference-outer-query-table-subquery.sql: -------------------------------------------------------------------------------- 1 | SELECT s.name, s.gpa 2 | FROM Student s 3 | WHERE EXISTS ( 4 | SELECT 1 5 | FROM Registration r 6 | WHERE r.student_id = s.id 7 | AND r.semester = 'SPRING' 8 | AND r.year = 2023 9 | ); -------------------------------------------------------------------------------- /sql-queries-7/Accessing-Query-Tables-within-subquery/using-JOIN-and-GROUP BY- cross-compatible-solution.sql: -------------------------------------------------------------------------------- 1 | SELECT s.name, COUNT(r.id) AS course_count 2 | FROM Student s 3 | LEFT JOIN Registration r ON s.id = r.student_id 4 | GROUP BY s.id, s.name; -------------------------------------------------------------------------------- /sql-queries-7/README: -------------------------------------------------------------------------------- 1 | ### Relevant Articles: 2 | 3 | -------------------------------------------------------------------------------- /sql-queries-7/create-json-format-group-concat-mysql/group-by-related-exception-fixed.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | department_id AS Department, 3 | JSON_OBJECT(id,GROUP_CONCAT(name)) AS Courses 4 | FROM course 5 | GROUP BY department_id,id; 6 | -------------------------------------------------------------------------------- /sql-queries-7/create-json-format-group-concat-mysql/group-by-related-exception.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | department_id AS Department, 3 | JSON_OBJECT(id,GROUP_CONCAT(name)) AS Courses 4 | FROM course 5 | GROUP BY department_id; 6 | -------------------------------------------------------------------------------- /sql-queries-7/create-json-format-group-concat-mysql/json-array-from-literal.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | GROUP_CONCAT('[','"first element"',',','"second element"',',','"third element"',']') 3 | AS result; 4 | -------------------------------------------------------------------------------- /sql-queries-7/create-json-format-group-concat-mysql/json-array-from-table-elaborate-example.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | department_id AS Department, 3 | JSON_ARRAY(GROUP_CONCAT(name)) AS Courses 4 | FROM course 5 | GROUP BY department_id \G 6 | -------------------------------------------------------------------------------- /sql-queries-7/create-json-format-group-concat-mysql/json-array-from-table-with-JSON_ARRAY-function.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | prerequisite_id AS Prerequisite, 3 | JSON_ARRAY( 4 | GROUP_CONCAT(course_id)) AS Courses 5 | FROM prerequisite 6 | GROUP BY prerequisite_id; 7 | -------------------------------------------------------------------------------- /sql-queries-7/create-json-format-group-concat-mysql/json-array-from-table.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | prerequisite_id AS Prerequisite, 3 | CONCAT('[',GROUP_CONCAT(course_id),']') AS Courses 4 | FROM prerequisite 5 | GROUP BY prerequisite_id; 6 | -------------------------------------------------------------------------------- /sql-queries-7/create-json-format-group-concat-mysql/json-array-with-JSON_ARRAY-function.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | GROUP_CONCAT( 3 | JSON_ARRAY("first element","second element","third element") 4 | ) 5 | AS result; 6 | -------------------------------------------------------------------------------- /sql-queries-7/create-json-format-group-concat-mysql/json-object-from-literal.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | GROUP_CONCAT('{','"1"',': ','"one"',', ','"2"',': ','"two"','}') 3 | AS result; 4 | -------------------------------------------------------------------------------- /sql-queries-7/create-json-format-group-concat-mysql/json-object-from-table-with-JSON_OBJECT-function.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | department_id AS Department, 3 | CONCAT('[', 4 | GROUP_CONCAT(JSON_OBJECT('id', id,'name', name)), 5 | ']') AS Courses 6 | FROM course 7 | GROUP BY department_id\G 8 | -------------------------------------------------------------------------------- /sql-queries-7/create-json-format-group-concat-mysql/json-object-from-table.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | department_id AS Department, 3 | CONCAT('[', 4 | GROUP_CONCAT(CONCAT('{"id":"', id, '", "name":"',name,'"}')), 5 | ']') AS Courses 6 | FROM course 7 | GROUP BY department_id \G 8 | -------------------------------------------------------------------------------- /sql-queries-7/create-json-format-group-concat-mysql/json-object-with-JSON_OBJECT-function.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | JSON_MERGE_PRESERVE( 3 | GROUP_CONCAT( 4 | JSON_OBJECT("1","one")), 5 | GROUP_CONCAT( 6 | JSON_OBJECT("2","two") 7 | ) 8 | ) 9 | AS result; 10 | -------------------------------------------------------------------------------- /sql-queries-7/insert-column-in-existing-table/insert-column-at-any-position-MySQL.sql: -------------------------------------------------------------------------------- 1 | -- Add column named fourth_column after third_column in Baeldung table 2 | ALTER TABLE Baeldung ADD fourth_column varchar(100) AFTER third_column; 3 | 4 | -- Query information_schema.columns for columns in Baeldung table 5 | SELECT column_name FROM information_schema.columns WHERE table_name = 'Baeldung'; 6 | -------------------------------------------------------------------------------- /sql-queries-7/insert-column-in-existing-table/insert-column-at-end-of-table.sql: -------------------------------------------------------------------------------- 1 | -- Create table Baeldung 2 | CREATE TABLE Baeldung (first_column int, second_column varchar(150)); 3 | 4 | -- Add column named third_column to table Baeldung 5 | ALTER TABLE Baeldung ADD third_column varchar(100); 6 | 7 | -- Query information_schema.columns for columns in table Baeldung 8 | SELECT column_name FROM information_schema.columns WHERE table_name = 'Baeldung'; 9 | -------------------------------------------------------------------------------- /sql-queries-7/insert-column-in-existing-table/insert-column-at-first-position-MySQL.sql: -------------------------------------------------------------------------------- 1 | -- Add column named new_first_column to the first position in table Baeldung 2 | ALTER TABLE Baeldung ADD new_first_column date FIRST; 3 | 4 | -- Query information_schema.columns for columns in table Baeldung 5 | SELECT column_name FROM information_schema.columns WHERE table_name = 'Baeldung'; 6 | -------------------------------------------------------------------------------- /sql-queries-7/looping-through-records/using-cursor-postgresql.sql: -------------------------------------------------------------------------------- 1 | DO $$ 2 | DECLARE 3 | studentRecord RECORD; 4 | BEGIN 5 | -- Declare and open the cursor 6 | FOR studentRecord IN SELECT id, name FROM Student LOOP 7 | -- Process each row 8 | RAISE NOTICE 'Processing Student: %', studentRecord.name; 9 | END LOOP; 10 | END $$; 11 | -------------------------------------------------------------------------------- /sql-queries-7/looping-through-records/using-while-loop-sqlserver.sql: -------------------------------------------------------------------------------- 1 | DECLARE @Counter INT = 1; 2 | DECLARE @MaxID INT = (SELECT MAX(id) FROM Student); 3 | 4 | WHILE @Counter <= @MaxID 5 | BEGIN 6 | -- Process each row based on the counter value 7 | SELECT name FROM Student WHERE id = @Counter; 8 | 9 | -- Increment the counter 10 | SET @Counter = @Counter + 1; 11 | END; 12 | -------------------------------------------------------------------------------- /sql-queries-7/sum-with-conditions/basic-sum.sql: -------------------------------------------------------------------------------- 1 | SELECT SUM(credits) FROM Course; 2 | -------------------------------------------------------------------------------- /sql-queries-7/sum-with-conditions/merging-where-groupby.sql: -------------------------------------------------------------------------------- 1 | SELECT department_id, SUM(credits) FROM Course WHERE is_active = 'Yes' GROUP BY department_id; 2 | -------------------------------------------------------------------------------- /sql-queries-7/sum-with-conditions/multiple-conditions.sql: -------------------------------------------------------------------------------- 1 | SELECT SUM(credits) FROM Course WHERE is_active = 'Yes' AND department_id = 4; 2 | -------------------------------------------------------------------------------- /sql-queries-7/sum-with-conditions/sum-with-case.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | SUM(CASE WHEN is_active = 'Yes' THEN credits ELSE 0 END) AS active_credits, 3 | SUM(CASE WHEN is_active = 'No' THEN credits ELSE 0 END) AS inactive_credits 4 | FROM Course; 5 | -------------------------------------------------------------------------------- /sql-queries-7/sum-with-conditions/sum-with-groupby.sql: -------------------------------------------------------------------------------- 1 | SELECT department_id, SUM(credits) FROM Course GROUP BY department_id; 2 | -------------------------------------------------------------------------------- /sql-queries-7/sum-with-conditions/sum-with-where.sql: -------------------------------------------------------------------------------- 1 | SELECT SUM(credits) FROM Course WHERE is_active = 'Yes'; 2 | -------------------------------------------------------------------------------- /sql-queries-8/Give-all-permission-to-a-user/implementation-in-mysql.sql: -------------------------------------------------------------------------------- 1 | CREATE USER 'dev_user'@'%' IDENTIFIED BY 'password123'; 2 | 3 | GRANT ALL PRIVILEGES ON University.* TO 'dev_user'@'%'; 4 | 5 | SELECT GRANTEE, PRIVILEGE_TYPE 6 | FROM information_schema.user_privileges 7 | WHERE GRANTEE = "'dev_user'@'%'"; 8 | 9 | SHOW GRANTS FOR 'dev_user'@'%'; -------------------------------------------------------------------------------- /sql-queries-8/Retrieving_Table_and_Index_Storage_Size_in_SQL/MySQL_Basic_Table_Storage_Information.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | table_name, 3 | ROUND((data_length / 1024 / 1024), 2) AS data_size_mb, 4 | ROUND((index_length / 1024 / 1024), 2) AS index_size_mb, 5 | table_rows, 6 | ROUND(((data_length + index_length) / 1024 / 1024), 2) AS total_size_mb 7 | FROM information_schema.tables 8 | WHERE 9 | table_schema = 'University' 10 | AND table_type = 'BASE TABLE' 11 | ORDER BY 12 | total_size_mb DESC; 13 | -------------------------------------------------------------------------------- /sql-queries-8/Retrieving_Table_and_Index_Storage_Size_in_SQL/Postgre_Table_Storage_Information.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | relname AS table_name, 3 | pg_size_pretty(pg_relation_size(c.oid)) AS table_size, 4 | pg_size_pretty(pg_total_relation_size(c.oid)) AS total_size, 5 | reltuples::bigint AS row_estimate 6 | FROM pg_class c 7 | JOIN pg_namespace n 8 | ON n.oid = c.relnamespace 9 | WHERE 10 | nspname = 'public' 11 | AND relkind = 'r' 12 | ORDER BY 13 | pg_total_relation_size(c.oid) DESC; -------------------------------------------------------------------------------- /sql-queries-8/Retrieving_Table_and_Index_Storage_Size_in_SQL/Postgres_Index_Storage_Details.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | schemaname, 3 | tablename, 4 | indexname, 5 | pg_size_pretty(pg_relation_size(i.indexrelid)) AS index_size, 6 | indexdef 7 | FROM pg_indexes i 8 | JOIN pg_stat_user_indexes ui 9 | ON i.indexname = ui.indexrelname 10 | WHERE 11 | schemaname = 'public' 12 | ORDER BY 13 | pg_relation_size(i.indexrelid) DESC; -------------------------------------------------------------------------------- /sql-queries-8/Set-Database-From-Single-User-Mode-to-Multi-User-Mode/Set-Database-From-Single-User-Mode-to-Multi-User-Mode-MySQL.sql: -------------------------------------------------------------------------------- 1 | --Listing all active connections to the database 2 | SHOW PROCESSLIST; 3 | 4 | --Terminating active connections 5 | KILL ; 6 | 7 | --Limiting database to allow only one connection (single-user mode) 8 | SET GLOBAL max_connections = 1; 9 | 10 | --Reverting database to allow multiple connections (multi-user mode) 11 | SET GLOBAL max_connections = 151; 12 | -------------------------------------------------------------------------------- /sql-queries-8/Set-Database-From-Single-User-Mode-to-Multi-User-Mode/Set-Database-From-Single-User-Mode-to-Multi-User-Mode-SQL-Server.sql: -------------------------------------------------------------------------------- 1 | -- checking the database mode 2 | SELECT DATABASEPROPERTYEX('University', 'UserAccess') AS UserAccessMode; 3 | 4 | -- Converting database to multi-user mode 5 | ALTER DATABASE University SET MULTI_USER; 6 | -------------------------------------------------------------------------------- /sql-queries-8/case-insensitive-searches/search-mssql.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name 2 | FROM Course 3 | WHERE name COLLATE Latin1_General_CI_AS like '%OPERATING%'; -------------------------------------------------------------------------------- /sql-queries-8/case-insensitive-searches/search-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name 2 | FROM Course 3 | WHERE REGEXP_LIKE(name, 'OPERATING', 'i'); 4 | 5 | SELECT id, name 6 | FROM Course 7 | WHERE name COLLATE utf8mb4_general_ci LIKE '%OPERATING%'; -------------------------------------------------------------------------------- /sql-queries-8/case-insensitive-searches/search-pg.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name 2 | FROM Course 3 | WHERE name ILIKE '%operating%'; 4 | 5 | SELECT id, name 6 | FROM Course 7 | WHERE name ~* 'OPERATING'; 8 | -------------------------------------------------------------------------------- /sql-queries-8/case-insensitive-searches/setup.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO Course values 2 | ('CS119', 'OPERATING SYSTEM Principles', 'OS by Abraham Silberschatz', 7, true); 3 | 4 | -- reset script 5 | DELETE FROM Course 6 | WHERE name = 'OPERATING SYSTEM Principles'; -------------------------------------------------------------------------------- /sql-queries-8/case-insensitive-searches/standard.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name 2 | FROM Course 3 | WHERE LOWER(name) LIKE '%phil%'; -------------------------------------------------------------------------------- /sql-queries-8/collation/MSSQL/List_of_all_available_UFT-8_collations.sql: -------------------------------------------------------------------------------- 1 | SELECT name 2 | FROM sys.fn_helpcollations() 3 | WHERE name LIKE '%UTF8'; 4 | -------------------------------------------------------------------------------- /sql-queries-8/collation/MSSQL/MSSQL_Database_Charset.sql: -------------------------------------------------------------------------------- 1 | SELECT name, collation_name 2 | FROM sys.databases 3 | WHERE name = DB_NAME(); 4 | -------------------------------------------------------------------------------- /sql-queries-8/collation/MSSQL/Support_UTF-8.sql: -------------------------------------------------------------------------------- 1 | ALTER DATABASE University 2 | COLLATE Latin1_General_100_CI_AS_SC_UTF8; 3 | -------------------------------------------------------------------------------- /sql-queries-8/collation/MSSQL/Testing_MSSQL_Collations.sql: -------------------------------------------------------------------------------- 1 | SELECT name 2 | FROM Student 3 | WHERE name = 'Zoë Johnson' 4 | COLLATE Latin1_General_100_CI_AI_SC_UTF8; 5 | 6 | SELECT name 7 | FROM Student 8 | WHERE name = 'Zoë Johnson' 9 | COLLATE Latin1_General_100_CI_AS_SC_UTF8; 10 | -------------------------------------------------------------------------------- /sql-queries-8/collation/MySQL/Force_the_use_of_a_different_collation.sql: -------------------------------------------------------------------------------- 1 | SELECT name 2 | FROM Student 3 | WHERE name = 'Jose Garcia'; 4 | 5 | SELECT name 6 | FROM Student 7 | WHERE name = 'Jose Garcia' 8 | COLLATE utf8mb4_bin; 9 | -------------------------------------------------------------------------------- /sql-queries-8/collation/MySQL/Identify_collations.sql: -------------------------------------------------------------------------------- 1 | SHOW COLLATION 2 | WHERE Charset = 'utf8mb4' 3 | AND Collation LIKE '%bg%'; 4 | -------------------------------------------------------------------------------- /sql-queries-8/collation/MySQL/MySQL_Database_Charset.sql: -------------------------------------------------------------------------------- 1 | SELECT SCHEMA_NAME, DEFAULT_CHARACTER_SET_NAME 2 | FROM INFORMATION_SCHEMA.SCHEMATA 3 | WHERE SCHEMA_NAME = DATABASE(); 4 | -------------------------------------------------------------------------------- /sql-queries-8/collation/MySQL/Setting_Collation.sql: -------------------------------------------------------------------------------- 1 | # Database Level 2 | ALTER DATABASE University 3 | CHARACTER SET utf8mb4 4 | COLLATE utf8mb4_unicode_ci; 5 | 6 | # Table Level 7 | ALTER TABLE Student 8 | CONVERT TO CHARACTER SET utf8mb4 9 | COLLATE utf8mb4_unicode_ci; 10 | 11 | # Column Level 12 | ALTER TABLE Student 13 | MODIFY name VARCHAR(255) 14 | CHARACTER SET utf8mb4 15 | COLLATE utf8mb4_unicode_ci; 16 | -------------------------------------------------------------------------------- /sql-queries-8/collation/MySQL/Upgrade_to_utf8mb4.sql: -------------------------------------------------------------------------------- 1 | ALTER DATABASE University 2 | CHARACTER SET utf8mb4; 3 | 4 | ALTER TABLE Student 5 | CONVERT TO CHARACTER SET utf8mb4; 6 | -------------------------------------------------------------------------------- /sql-queries-8/collation/PostgreSQL/Check_the_current_locale_settings.sql: -------------------------------------------------------------------------------- 1 | SELECT datname, 2 | datcollate AS "Collation", 3 | datctype AS "Character Type" 4 | FROM pg_database 5 | WHERE datname = current_database(); 6 | -------------------------------------------------------------------------------- /sql-queries-8/collation/PostgreSQL/List_all_the_collations.sql: -------------------------------------------------------------------------------- 1 | SELECT collname 2 | FROM pg_collation; 3 | -------------------------------------------------------------------------------- /sql-queries-8/collation/PostgreSQL/PostgreSQL_Database_Charset.sql: -------------------------------------------------------------------------------- 1 | SELECT datname, pg_encoding_to_char(encoding) AS encoding 2 | FROM pg_database 3 | WHERE datname = current_database(); 4 | -------------------------------------------------------------------------------- /sql-queries-8/reasons-the-DELETE-statement-in-SQL-can-be-very-slow/basic-delete.sql: -------------------------------------------------------------------------------- 1 | DELETE FROM Student WHERE id = 1001; 2 | -------------------------------------------------------------------------------- /sql-queries-8/reasons-the-DELETE-statement-in-SQL-can-be-very-slow/creating-multiple-Indexes.sql: -------------------------------------------------------------------------------- 1 | CREATE INDEX idx_student_reg ON Registration(student_id, semester, year); 2 | CREATE INDEX idx_course_reg ON Registration(course_id, semester); 3 | CREATE INDEX idx_reg_date ON Registration(reg_datetime); 4 | -------------------------------------------------------------------------------- /sql-queries-8/reasons-the-DELETE-statement-in-SQL-can-be-very-slow/delete-with-foreign-key.sql: -------------------------------------------------------------------------------- 1 | DELETE FROM Department WHERE id = 1; 2 | -------------------------------------------------------------------------------- /sql-queries-8/reasons-the-DELETE-statement-in-SQL-can-be-very-slow/implementing-batch-delete.sql: -------------------------------------------------------------------------------- 1 | DECLARE @BatchSize INT = 1000; 2 | DECLARE @RowsAffected INT = 1; 3 | 4 | WHILE @RowsAffected > 0 5 | BEGIN 6 | DELETE TOP (@BatchSize) 7 | FROM Registration 8 | WHERE year < 2022; 9 | 10 | SET @RowsAffected = @@ROWCOUNT; 11 | END 12 | -------------------------------------------------------------------------------- /sql-queries-8/reasons-the-DELETE-statement-in-SQL-can-be-very-slow/index-optimization-delete.sql: -------------------------------------------------------------------------------- 1 | ALTER INDEX idx_reg_date ON Registration DISABLE; 2 | ALTER INDEX idx_course_reg ON Registration DISABLE; 3 | 4 | DELETE FROM Registration 5 | WHERE year = 2022 AND semester = 'SPRING'; 6 | 7 | ALTER INDEX idx_reg_date ON Registration REBUILD; 8 | ALTER INDEX idx_course_reg ON Registration REBUILD; 9 | -------------------------------------------------------------------------------- /sql-queries-8/reasons-the-DELETE-statement-in-SQL-can-be-very-slow/lock-behaviour.sql: -------------------------------------------------------------------------------- 1 | DELETE FROM Course WHERE department_id = 1; 2 | -------------------------------------------------------------------------------- /sql-queries-8/reasons-the-DELETE-statement-in-SQL-can-be-very-slow/multiple-foreign-key-delete.sql: -------------------------------------------------------------------------------- 1 | BEGIN TRANSACTION; 2 | DELETE FROM Exam WHERE student_id = 1001; 3 | DELETE FROM Registration WHERE student_id = 1001; 4 | DELETE FROM Student WHERE id = 1001; 5 | COMMIT; 6 | -------------------------------------------------------------------------------- /sql-queries-8/reset-autoincrement-mysql/alter-table-to-reset-autoincrement.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE department_copy AUTO_INCREMENT = 10; 2 | 3 | INSERT INTO department_copy(name,code) 4 | VALUES 5 | ("Computer Engineering","CE"), 6 | ("Electronics","E"), 7 | ("Information Sciences","IS"); 8 | 9 | SELECT * FROM department_copy; 10 | -------------------------------------------------------------------------------- /sql-queries-8/reset-autoincrement-mysql/insert-to-reset-autoincrement.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO department_copy(id,name,code) 2 | VALUES 3 | (10,"Computer Engineering","CE"); 4 | 5 | INSERT INTO department_copy(name,code) 6 | VALUES 7 | ("Electronics","E"), 8 | ("Information Sciences","IS"); 9 | 10 | SELECT * FROM department_copy; 11 | -------------------------------------------------------------------------------- /sql-queries-8/reset-autoincrement-mysql/update-to-reset-autoincrement.sql: -------------------------------------------------------------------------------- 1 | UPDATE department_copy 2 | SET id=10 WHERE code="MA"; 3 | 4 | INSERT INTO department_copy(name,code) 5 | VALUES 6 | ("Data Science","DS"); 7 | 8 | SELECT * FROM department_copy; 9 | -------------------------------------------------------------------------------- /sql-queries-8/selecting-single-row-based-on-multiple-criteria-from-one-column/selecting-single-row-based-on-multiple-criteria-mssql.sql: -------------------------------------------------------------------------------- 1 | SELECT TOP 1 * 2 | FROM Course 3 | WHERE textbook LIKE 'Signals%Oppenheim' 4 | ORDER BY id; 5 | -------------------------------------------------------------------------------- /sql-queries-8/selecting-single-row-based-on-multiple-criteria-from-one-column/selecting-single-row-based-on-multiple-criteria-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Course 3 | WHERE textbook LIKE '%Numerical%' AND textbook LIKE '%Optimization%' 4 | ORDER BY id 5 | LIMIT 1; 6 | -------------------------------------------------------------------------------- /sql-queries-8/selecting-single-row-based-on-multiple-criteria-from-one-column/selecting-single-row-based-on-multiple-criteria-pgsql.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Course 3 | WHERE textbook LIKE '%Numerical%' OR textbook LIKE '%Optimization%' 4 | ORDER BY id 5 | LIMIT 1; 6 | 7 | -- Using regular expressions as another alternative 8 | SELECT * 9 | FROM Course 10 | WHERE textbook ~* 'Numerical|Optimization' 11 | ORDER BY id 12 | LIMIT 1; 13 | -------------------------------------------------------------------------------- /sql-queries-9/README.md: -------------------------------------------------------------------------------- 1 | ### Relevant Articles 2 | - [Understanding the SQL OVER() Clause](https://www.baeldung.com/sql/over) 3 | - [Deleting a Column From a Table in SQL](https://www.baeldung.com/sql/delete-column-from-table) -------------------------------------------------------------------------------- /sql-queries-9/calculate-percentage-sql-statement/dynamically-calculate-percentage-grades.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | Grade, 3 | ROUND((COUNT(*) * 100.0) / (SELECT COUNT(*) FROM UserGrades), 2) AS Percentage 4 | FROM 5 | UserGrades 6 | GROUP BY 7 | Grade 8 | ORDER BY 9 | Grade; 10 | 11 | -------------------------------------------------------------------------------- /sql-queries-9/delete-column-from-table/delete-column-from-table.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE table_name DROP COLUMN column_name; 2 | -------------------------------------------------------------------------------- /sql-queries-9/delete-column-from-table/delete-columns-from-table-mssql.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE table_name DROP COLUMN column_name_1, column_name_2; 2 | -------------------------------------------------------------------------------- /sql-queries-9/delete-column-from-table/delete-columns-from-table-mysql.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE table_name DROP COLUMN column_name_1, DROP COLUMN column_name_2; 2 | -------------------------------------------------------------------------------- /sql-queries-9/delete-column-from-table/delete-columns-from-table-pg.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE table_name DROP COLUMN column_name_1, column_name_2; 2 | -------------------------------------------------------------------------------- /sql-queries-9/keyword-search-sql/full-text-search-mysql.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE Course ADD FULLTEXT(name, textbook); 2 | 3 | SELECT id, name, textbook, credits 4 | FROM Course 5 | WHERE MATCH(name, textbook) AGAINST('Operating Systems'); 6 | 7 | -------------------------------------------------------------------------------- /sql-queries-9/keyword-search-sql/full-text-search-sqlserver.sql: -------------------------------------------------------------------------------- 1 | CREATE FULLTEXT CATALOG ftCatalog AS DEFAULT; 2 | CREATE FULLTEXT INDEX ON Course(name, textbook) KEY INDEX PK_Course; 3 | 4 | SELECT id, name, textbook, credits 5 | FROM Course 6 | WHERE CONTAINS((name, textbook), 'Operating AND Systems'); 7 | -------------------------------------------------------------------------------- /sql-queries-9/keyword-search-sql/using-like-operator.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, textbook, credits 2 | FROM Course 3 | WHERE name LIKE '%Operating%'; 4 | 5 | SELECT id, name, textbook, credits 6 | FROM Course 7 | WHERE name LIKE '%Database Systems%' OR textbook LIKE '%Database Systems%'; -------------------------------------------------------------------------------- /sql-queries-9/limit-number-of-rows-after-ordering/limit-number-of-rows-after-ordering-mssql.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM table_name 3 | ORDER BY column_name 4 | OFFSET offset_value ROWS 5 | FETCH NEXT number_of_rows ROWS ONLY; 6 | -------------------------------------------------------------------------------- /sql-queries-9/limit-number-of-rows-after-ordering/limit-number-of-rows-after-ordering-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM table_name 3 | ORDER BY column_name 4 | LIMIT offset_value, number_of_rows; 5 | -------------------------------------------------------------------------------- /sql-queries-9/limit-number-of-rows-after-ordering/limit-number-of-rows-after-ordering-pgsql.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM table_name 3 | ORDER BY column_name 4 | LIMIT number_of_rows OFFSET offset_value; 5 | -------------------------------------------------------------------------------- /sql-queries-9/null-to-zero/ansi.sql: -------------------------------------------------------------------------------- 1 | SELECT AVG(COALESCE(lab_hours, 0)) FROM Student; 2 | 3 | SELECT AVG( 4 | CASE WHEN lab_hours IS NULL THEN 0 ELSE lab_hours END ) 5 | FROM Student; -------------------------------------------------------------------------------- /sql-queries-9/null-to-zero/mssql.sql: -------------------------------------------------------------------------------- 1 | SELECT AVG(ISNULL(lab_hours, 0)) FROM Student; -------------------------------------------------------------------------------- /sql-queries-9/null-to-zero/mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT AVG(IFNULL(lab_hours, 0)) FROM Student; -------------------------------------------------------------------------------- /sql-queries-9/sql-over-clause/over-clause-with-group-by.sql: -------------------------------------------------------------------------------- 1 | SELECT enrollment_date, 2 | MAX(gpa) AS highest_gpa, 3 | MIN(gpa) AS lowest_gpa 4 | FROM Student 5 | GROUP BY enrollment_date; -------------------------------------------------------------------------------- /sql-queries-9/sql-over-clause/over-clause-with-order-by.sql: -------------------------------------------------------------------------------- 1 | SELECT id, semester, grade, 2 | MAX(grade) OVER (PARTITION BY student_id ORDER BY grade) AS course_highest, 3 | MIN(grade) OVER (PARTITION BY student_id ORDER BY grade) AS course_lowest 4 | FROM Exam 5 | ORDER BY course_id; -------------------------------------------------------------------------------- /sql-queries-9/sql-over-clause/over-clause-with-partition-by.sql: -------------------------------------------------------------------------------- 1 | SELECT name, position, 2 | COUNT(*) OVER (PARTITION BY name) AS Total_Positions 3 | FROM Faculty; -------------------------------------------------------------------------------- /sql-queries-9/sql-over-clause/over-clause-with-rows.sql: -------------------------------------------------------------------------------- 1 | SELECT id, enrollment_date, 2 | AVG(gpa) OVER (ORDER BY enrollment_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS Avg3GPAs, 3 | AVG(gpa) OVER (ORDER BY YEAR(enrollment_date) RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS AvgGPAYearOverYear 4 | FROM Student 5 | ORDER BY enrollment_date, id; 6 | -------------------------------------------------------------------------------- /sql-queries-9/using-LEFT-OUTER-JOIN-with-WHERE-clause/using-LEFT-OUTER-JOIN.sql: -------------------------------------------------------------------------------- 1 | SELECT Course.id, Course.name, Course.textbook, Department.code AS department_code 2 | FROM Course 3 | LEFT OUTER JOIN Department 4 | ON Course.department_id = Department.id AND Department.id < 4; 5 | -------------------------------------------------------------------------------- /sql-queries-create-table/README.md: -------------------------------------------------------------------------------- 1 | ### Relevant Articles: 2 | - [Moving Data Between Tables in SQL](https://www.baeldung.com/sql/transfer-data-between-tables) 3 | -------------------------------------------------------------------------------- /sql-queries-create-table/sql-create-table-using-WITH/create-table-with-clause-mysql.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE gpa_new AS 2 | WITH new_high_gpa 3 | AS 4 | ( 5 | SELECT 6 | id, 7 | name, 8 | enrollment_date, 9 | gpa 10 | FROM student 11 | WHERE gpa > 3.5 12 | ) 13 | SELECT * 14 | FROM new_high_gpa; 15 | 16 | SELECT * FROM gpa_new; -------------------------------------------------------------------------------- /sql-queries-create-table/sql-create-table-using-WITH/create-table-with-clause-postgresql.sql: -------------------------------------------------------------------------------- 1 | WITH HighGPAStudents 2 | AS 3 | ( 4 | SELECT 5 | id, 6 | name, 7 | gpa, 8 | graduation_date 9 | FROM Student 10 | WHERE gpa > 3.5 11 | ) 12 | 13 | SELECT * 14 | INTO StudentsWithHighGPA 15 | FROM HighGPAStudents; 16 | 17 | SELECT * FROM StudentsWithHighGPA; -------------------------------------------------------------------------------- /sql-queries-create-table/sql-create-table-using-WITH/create-table-with-clause-sql-server.sql: -------------------------------------------------------------------------------- 1 | WITH HighGPAStudents 2 | AS 3 | ( 4 | SELECT 5 | id, 6 | name, 7 | gpa, 8 | graduation_date 9 | FROM Student 10 | WHERE gpa > 3.5 11 | ) 12 | SELECT * 13 | INTO StudentsWithHighGPA 14 | FROM HighGPAStudents; 15 | 16 | SELECT * FROM StudentsWithHighGPA; -------------------------------------------------------------------------------- /sql-queries-dates-1/current-date-rows/current-date-rows-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Registration 2 | WHERE reg_datetime BETWEEN CURRENT_DATE 3 | AND (CURRENT_DATE + INTERVAL 1 day - INTERVAL 1 microsecond); 4 | 5 | SELECT * FROM Registration 6 | WHERE reg_datetime > CURRENT_DATE 7 | AND reg_datetime < (CURRENT_DATE + INTERVAL 1 day); 8 | 9 | SELECT * FROM Registration 10 | WHERE DATE(reg_datetime) = CURRENT_DATE; 11 | 12 | SELECT * FROM Registration 13 | WHERE CAST(reg_datetime AS DATE) = CURRENT_DATE; -------------------------------------------------------------------------------- /sql-queries-dates-1/current-date-rows/current-date-rows-sqlserver.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Registration 2 | WHERE reg_datetime BETWEEN CAST(GETDATE() AS DATE) 3 | AND DATEADD(MILLISECOND, -3, DATEADD(DAY, 1, CAST(CONVERT(DATE, GETDATE()) AS DATETIME))); 4 | 5 | SELECT * FROM Registration 6 | WHERE reg_datetime >= CAST(GETDATE() AS DATE) 7 | AND reg_datetime < CAST(DATEADD(DAY, 1, GETDATE()) AS DATE); 8 | 9 | SELECT * FROM Registration 10 | WHERE CAST(reg_datetime AS DATE) = CAST(GETDATE() AS DATE); -------------------------------------------------------------------------------- /sql-queries-dates-1/select-date-without-time/cast()-function.sql: -------------------------------------------------------------------------------- 1 | SELECT CAST(graduation_datetime AS DATE) AS date_only FROM Student; -------------------------------------------------------------------------------- /sql-queries-dates-1/select-date-without-time/date()-function.sql: -------------------------------------------------------------------------------- 1 | SELECT DATE(graduation_datetime) AS date_only FROM Student; -------------------------------------------------------------------------------- /sql-queries-dates-1/select-date-without-time/date-format()-function.sql: -------------------------------------------------------------------------------- 1 | SELECT DATE_FORMAT(graduation_datetime, '%Y-%m-%d') AS date_only FROM Student; -------------------------------------------------------------------------------- /sql-queries-dates/Selecting_Dates_Within_a_Range_Using_SQL_Queries/Basic Date Filtering.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Student WHERE enrollment_date = '2020-01-15' 2 | -------------------------------------------------------------------------------- /sql-queries-dates/Selecting_Dates_Within_a_Range_Using_SQL_Queries/Handling Time in Date Ranges.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Student WHERE enrollment_date >= '2020-01-15 00:00:00' AND enrollment_date < '2022-12-08 00:00:00' -------------------------------------------------------------------------------- /sql-queries-dates/Selecting_Dates_Within_a_Range_Using_SQL_Queries/Selecting Dates Within a Range.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Student WHERE enrollment_date BETWEEN '2020-01-15' AND '2021-12-31' -------------------------------------------------------------------------------- /sql-queries-dates/Selecting_Dates_Within_a_Range_Using_SQL_Queries/Selecting Dates Within a Range_2.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Student WHERE enrollment_date >= '2020-01-15' AND enrollment_date <= '2021-12-31' -------------------------------------------------------------------------------- /sql-queries-dates/Selecting_Dates_Within_a_Range_Using_SQL_Queries/Using Functions for Date Range Selection.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Student WHERE enrollment_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY) -------------------------------------------------------------------------------- /sql-queries-dates/Selecting_Dates_Within_a_Range_Using_SQL_Queries/Using Functions for Date Range Selection_2.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Student WHERE MONTH(enrollment_date) = 01 AND YEAR(enrollment_date) = 2021 -------------------------------------------------------------------------------- /sql-queries-dates/Selecting_Dates_Within_a_Range_Using_SQL_Queries/Working with Different Date Formats.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Student WHERE STR_TO_DATE(enrollment_date, '%d-%m-%Y') BETWEEN '2020-01-01' AND '2021-12-31' -------------------------------------------------------------------------------- /sql-queries-dates/Selecting_Dates_Within_a_Range_Using_SQL_Queries/Working with Different Date Formats_2.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Student WHERE YEAR(STR_TO_DATE(enrollment_date, '%d-%m-%Y')) = 2021 AND MONTH(STR_TO_DATE(enrollment_date, '%d-%m-%Y')) BETWEEN 1 AND 5 -------------------------------------------------------------------------------- /sql-queries-dates/current-date-and-time/current-date-and-time-mysql.sql: -------------------------------------------------------------------------------- 1 | --NOW funtion 2 | SELECT NOW(); 3 | 4 | -- LOCALTIMESTAMP function 5 | SELECT LOCALTIMESTAMP(); 6 | 7 | --CURRENT_TIMESTAMP function: 8 | SELECT CURRENT_TIMESTAMP(); 9 | 10 | --SYSDATE function 11 | SELECT SYSDATE(); -------------------------------------------------------------------------------- /sql-queries-dates/current-date-and-time/current-date-and-time-postgresql.sql: -------------------------------------------------------------------------------- 1 | --NOW function 2 | SELECT NOW()::TIMESTAMP; 3 | 4 | --CURRENT_TIMESTAMP function 5 | SELECT CURRENT_TIMESTAMP::TIMESTAMP; 6 | 7 | --LOCALTIMESTAMP function 8 | SELECT LOCALTIMESTAMP; -------------------------------------------------------------------------------- /sql-queries-dates/current-date-and-time/current-date-and-time-sqlserver.sql: -------------------------------------------------------------------------------- 1 | --GETDATE function 2 | SELECT GETDATE(); 3 | 4 | --CURRENT_TIMESTAMP system defined constant function 5 | SELECT CURRENT_TIMESTAMP; 6 | 7 | --SYSDATETIME function 8 | SELECT SYSDATETIME(); 9 | 10 | --GETUTCDATE function 11 | SELECT GETUTCDATE(); 12 | 13 | --SYSUTCDATETIME function 14 | SELECT SYSUTCDATETIME(); -------------------------------------------------------------------------------- /sql-queries-dates/current-timestamp-sql-server/current-timestamp-mssql.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | GETDATE() AS CurrentDateTime, 3 | SYSDATETIME() AS PreciseDateTime, 4 | CURRENT_TIMESTAMP AS ANSI_CurrentDateTime, 5 | SYSDATETIMEOFFSET() AS DateTimeWithOffset, 6 | SYSUTCDATETIME() AS UTCDateTime, 7 | GETUTCDATE() as UTCDate; 8 | 9 | SELECT CONVERT(VARCHAR(50), CURRENT_TIMESTAMP, 121); 10 | -------------------------------------------------------------------------------- /sql-queries-dates/first-day-of-month/first-day-of-month-mysql.sql: -------------------------------------------------------------------------------- 1 | -- Using DATE_FROMAT 2 | SELECT id, name, DATE_FORMAT(start_date, '%Y-%m-01') AS StartOfMonth 3 | FROM Program; 4 | 5 | -- Using MAKEDATE and MONTH 6 | SELECT id, name, MAKEDATE(YEAR(start_date), 1) + INTERVAL (MONTH(start_date) - 1) MONTH AS StartOfMonth 7 | FROM Program; -------------------------------------------------------------------------------- /sql-queries-dates/first-day-of-month/first-day-of-month-postgresql.sql: -------------------------------------------------------------------------------- 1 | -- Using DATE_TRUNC 2 | SELECT id, name, DATE_TRUNC('month', start_date) AS StartOfMonth 3 | FROM Program; 4 | 5 | -- Using MAKE_DATE and EXTRACT 6 | SELECT id, name, MAKE_DATE(EXTRACT(YEAR FROM start_date)::int, EXTRACT(MONTH FROM start_date)::int, 1) AS StartOfMonth 7 | FROM Program; -------------------------------------------------------------------------------- /sql-queries-dates/group-year-month/grouping-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT YEAR(reg_datetime) AS year_part, MONTH(reg_datetime) AS month_part, COUNT(*) AS total_registrations 2 | FROM Registration 3 | GROUP BY year_part, month_part 4 | ORDER BY year_part, month_part; 5 | 6 | SELECT DATE_FORMAT(reg_datetime, '%Y-%m') AS month_year, COUNT(*) AS total_registrations 7 | FROM Registration 8 | GROUP BY month_year 9 | ORDER BY month_year; -------------------------------------------------------------------------------- /sql-queries-dates/interval-queries/interval-mssql.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, enrollment_date FROM Student WHERE enrollment_date >= DATEADD(DAY, -10, CONVERT(date, GETDATE())); 2 | SELECT * FROM Registration WHERE reg_datetime >= DATEADD(DAY, -10, GETDATE()); 3 | SELECT * FROM Registration WHERE DATEDIFF(DAY, reg_datetime, GETDATE()) <= 10; -------------------------------------------------------------------------------- /sql-queries-dates/interval-queries/interval-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, enrollment_date FROM Student WHERE enrollment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 10 DAY); 2 | SELECT * FROM Registration WHERE reg_datetime >= DATE_SUB(NOW(), INTERVAL 10 DAY); 3 | -------------------------------------------------------------------------------- /sql-queries-dates/interval-queries/interval-pg.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, enrollment_date FROM Student WHERE enrollment_date >= CURRENT_DATE - INTERVAL '10 days'; 2 | SELECT * FROM Registration WHERE reg_datetime >= CURRENT_TIMESTAMP - INTERVAL '10 days'; -------------------------------------------------------------------------------- /sql-queries-exists/README.md: -------------------------------------------------------------------------------- 1 | ### Relevant Articles: 2 | - [How to Check if a Record Exists in SQL](https://www.baeldung.com/sql/record-check-existence) 3 | -------------------------------------------------------------------------------- /sql-queries-exists/record-existence/count.sql: -------------------------------------------------------------------------------- 1 | SELECT COUNT(*) as count FROM Program WHERE department_id = 1; 2 | -------------------------------------------------------------------------------- /sql-queries-exists/record-existence/exists.sql: -------------------------------------------------------------------------------- 1 | if exists (SELECT 1 FROM Program WHERE department_id = 7) 2 | print 'Program found for department_id 7'; 3 | else 4 | print 'No program found for department_id 7'; 5 | -------------------------------------------------------------------------------- /sql-queries-exists/record-existence/select.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Program WHERE department_id = 11; 2 | SELECT * FROM Program WHERE department_id = 16; 3 | -------------------------------------------------------------------------------- /sql-queries-exists/record-existence/top.sql: -------------------------------------------------------------------------------- 1 | SELECT TOP 1 * FROM Program WHERE department_id=11; 2 | -------------------------------------------------------------------------------- /sql-queries-index/README.md: -------------------------------------------------------------------------------- 1 | ### Relevant Articles: 2 | - [How to Ignore an Index in an SQL Query](https://www.baeldung.com/sql/index-exclude) 3 | 4 | -------------------------------------------------------------------------------- /sql-queries-index/Relationship-between-primary-key-and-clustered-indexes/Examples-clustered-indexes/Clustered-index-on-a-composite-key.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE Mentorship ( 2 | mentor_id INT, 3 | student_id INT, 4 | start_date DATE, 5 | end_date DATE, 6 | status VARCHAR(50), 7 | PRIMARY KEY (mentor_id, student_id)); 8 | -------------------------------------------------------------------------------- /sql-queries-index/Relationship-between-primary-key-and-clustered-indexes/Examples-clustered-indexes/Custom-created-index.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE Library ( 2 | book_id INT PRIMARY KEY, 3 | book_title VARCHAR(255), 4 | author VARCHAR(255), 5 | isbn VARCHAR(20), 6 | available_copies INT, 7 | borrowed_date DATE); 8 | CREATE CLUSTERED INDEX IX_borrowed_date ON Library (borrowed_date); 9 | -------------------------------------------------------------------------------- /sql-queries-index/Relationship-between-primary-key-and-clustered-indexes/Examples-clustered-indexes/Primary-key-clustered-index.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE Classroom ( 2 | id INT PRIMARY KEY, 3 | room_number VARCHAR(50), 4 | building_name VARCHAR(100), 5 | capacity INT); 6 | -------------------------------------------------------------------------------- /sql-queries-index/Relationship-between-primary-key-and-clustered-indexes/Examples-clustered-indexes/Primary-key-with-Non-Clustered-Index.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE Alumni ( 2 | alumni_id INT PRIMARY KEY NONCLUSTERED, 3 | student_id INT, 4 | employment_status VARCHAR(50), 5 | employer VARCHAR(255), 6 | position VARCHAR(100), 7 | graduation_year INT); 8 | -------------------------------------------------------------------------------- /sql-queries-index/composite-index-in-sql/analyze-composite-index-performance.sql: -------------------------------------------------------------------------------- 1 | --analyze query performance after assigning composite index 2 | EXPLAIN SELECT * 3 | FROM Student 4 | WHERE enrollment_date = '2020-01-15' AND gpa > 4.0; 5 | 6 | --optimized query 7 | SELECT * 8 | FROM Student 9 | WHERE enrollment_date = '2020-01-15' AND gpa > 4.0; 10 | -------------------------------------------------------------------------------- /sql-queries-index/composite-index-in-sql/analyze-query-with-no-composite-index.sql: -------------------------------------------------------------------------------- 1 | --analyze query performance on column without composite index assigned, using EXPLAIN 2 | EXPLAIN SELECT * 3 | FROM Student 4 | WHERE birth_date = '2002-05-15' AND gpa > 3.5; 5 | -------------------------------------------------------------------------------- /sql-queries-index/composite-index-in-sql/create-composite-index.sql: -------------------------------------------------------------------------------- 1 | --show index in table 2 | SHOW INDEX FROM Student; 3 | 4 | --create index on multiple columns 5 | CREATE INDEX idx_enrollment_gpa 6 | ON Student (enrollment_date, gpa); 7 | -------------------------------------------------------------------------------- /sql-queries-index/composite-index-in-sql/drop-composite-index.sql: -------------------------------------------------------------------------------- 1 | --drop the index created 2 | DROP INDEX idx_enrollment_gpa 3 | ON Student; 4 | 5 | --Verify if index is dropped 6 | SHOW INDEX FROM Student; 7 | -------------------------------------------------------------------------------- /sql-queries-index/composite-vs-multi-col-indexes-sql/create-composite-indexes.sql: -------------------------------------------------------------------------------- 1 | CREATE INDEX idx_gpa_and_enrollment ON Student (gpa, enrollemnt_date); 2 | CREATE INDEX idx_gpa ON Student (gpa); -- redundant 3 | CREATE INDEX idx_enrollment ON Student (enrollemnt_date); -- NOT redundant 4 | -------------------------------------------------------------------------------- /sql-queries-index/composite-vs-multi-col-indexes-sql/create-individual-indexes.sql: -------------------------------------------------------------------------------- 1 | CREATE INDEX idx_gpa ON Student (gpa); 2 | CREATE INDEX idx_enrollment ON Student(enrollment_date); 3 | -------------------------------------------------------------------------------- /sql-queries-index/composite-vs-multi-col-indexes-sql/query-students.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Student WHERE gpa > 3 AND enrollment_date > (NOW() - INTERVAL 4 YEAR); 2 | 3 | EXPLAIN ANALYZE SELECT * FROM Student WHERE gpa > 3 AND enrollment_date > (NOW() - INTERVAL 4 YEAR); 4 | -------------------------------------------------------------------------------- /sql-queries-index/index-rebuild/creating_db_role.sql: -------------------------------------------------------------------------------- 1 | IF NOT EXISTS ( 2 | SELECT 1 3 | FROM sys.database_principals 4 | WHERE name = 'index_maintenance' AND type = 'R' 5 | ) 6 | BEGIN 7 | CREATE ROLE index_maintenance; 8 | END 9 | GO 10 | 11 | GRANT ALTER ON OBJECT::dbo.Teaching TO index_maintenance; 12 | GO 13 | -------------------------------------------------------------------------------- /sql-queries-index/index-rebuild/db_database.sql: -------------------------------------------------------------------------------- 1 | BACKUP DATABASE University 2 | TO DISK = 'C:\Backups\University_FULL.bak' 3 | WITH FORMAT, 4 | INIT, 5 | NAME = 'Full Backup Before Index Rebuild', 6 | SKIP, 7 | STATS = 10; 8 | -------------------------------------------------------------------------------- /sql-queries-index/index-rebuild/rebuild_index_on_table.sql: -------------------------------------------------------------------------------- 1 | ALTER INDEX [PK__Teaching__3213E83FFA8FEA28] 2 | ON dbo.Teaching 3 | REBUILD WITH ( 4 | FILLFACTOR = 90, 5 | SORT_IN_TEMPDB = ON, 6 | STATISTICS_NORECOMPUTE = OFF); 7 | -------------------------------------------------------------------------------- /sql-queries-index/retrieve-table-primary-key/information_schema-postgres.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | kcu.column_name 3 | FROM 4 | information_schema.table_constraints tc 5 | JOIN 6 | information_schema.key_column_usage kcu 7 | ON 8 | tc.constraint_name = kcu.constraint_name 9 | WHERE 10 | tc.table_schema = 'public' 11 | AND tc.table_name = 'student' 12 | AND tc.constraint_type = 'PRIMARY KEY'; -------------------------------------------------------------------------------- /sql-queries-index/retrieve-table-primary-key/pg_constraint-system-catalog-postgres.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | conname AS constraint_name, 3 | conrelid::regclass AS table_name, 4 | a.attname AS column_name 5 | FROM 6 | pg_constraint AS c 7 | JOIN 8 | pg_attribute AS a 9 | ON 10 | a.attnum = ANY(c.conkey) 11 | AND a.attrelid = c.conrelid 12 | WHERE 13 | c.contype = 'p' 14 | AND c.conrelid = 'Student'::regclass; 15 | -------------------------------------------------------------------------------- /sql-queries-index/retrieve-table-primary-key/using-information-schema-sqlserver.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | kcu.COLUMN_NAME 3 | FROM 4 | INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc 5 | JOIN 6 | INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu 7 | ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME 8 | WHERE 9 | tc.TABLE_SCHEMA = 'dbo' 10 | AND tc.TABLE_NAME = 'Student' 11 | AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'; 12 | -------------------------------------------------------------------------------- /sql-queries-index/retrieve-table-primary-key/using-pg_indexes-postgres.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | indexname AS constraint_name, 3 | tablename AS table_name, 4 | indexdef AS definition 5 | FROM 6 | pg_indexes 7 | WHERE 8 | tablename = 'student' 9 | AND indexname = 'student_pkey'; 10 | -------------------------------------------------------------------------------- /sql-queries-index/retrieve-table-primary-key/using-show-index-mysql.sql: -------------------------------------------------------------------------------- 1 | SHOW INDEX FROM Student WHERE Key_name = 'PRIMARY'; -------------------------------------------------------------------------------- /sql-queries-index/retrieve-table-primary-key/using-show-keys-mysql.sql: -------------------------------------------------------------------------------- 1 | SHOW KEYS FROM Student WHERE Key_name = 'PRIMARY'; -------------------------------------------------------------------------------- /sql-queries-index/retrieve-table-primary-key/using-sp_help-stored-procedure-sqlserver.sql: -------------------------------------------------------------------------------- 1 | EXEC sp_help 'Student'; -------------------------------------------------------------------------------- /sql-queries-index/sql-ignore-index/mysql-analyze-query-plan.sql: -------------------------------------------------------------------------------- 1 | EXPLAIN 2 | ANALYZE 3 | SELECT name, type, department_id 4 | FROM Program 5 | WHERE department_id=1 6 | GROUP BY name, type, department_id 7 | ORDER BY department_id; 8 | -------------------------------------------------------------------------------- /sql-queries-index/sql-ignore-index/mysql-ignore-index-IGNORE-INDEX-hint.sql: -------------------------------------------------------------------------------- 1 | EXPLAIN ANALYZE 2 | SELECT name, type, department_id 3 | FROM Program IGNORE INDEX(program_department_id_fkey) 4 | WHERE department_id=1 5 | GROUP BY name, type, department_id 6 | ORDER BY department_id; 7 | -------------------------------------------------------------------------------- /sql-queries-index/sql-ignore-index/mysql-ignore-index-USE-INDEX-hint.sql: -------------------------------------------------------------------------------- 1 | EXPLAIN 2 | ANALYZE 3 | SELECT name, type, department_id 4 | FROM Program 5 | USE INDEX() 6 | WHERE department_id=1 7 | GROUP BY name, type, department_id 8 | ORDER BY department_id; 9 | -------------------------------------------------------------------------------- /sql-queries-index/sql-ignore-index/mysql-ignore-index-for-group-by.sql: -------------------------------------------------------------------------------- 1 | EXPLAIN ANALYZE 2 | SELECT name, type, department_id 3 | FROM Program 4 | IGNORE INDEX FOR GROUP BY(program_department_id_fkey) 5 | WHERE department_id=1 6 | GROUP BY name, type, department_id 7 | ORDER BY department_id; 8 | -------------------------------------------------------------------------------- /sql-queries-index/sql-ignore-index/mysql-ignore-index-for-join.sql: -------------------------------------------------------------------------------- 1 | EXPLAIN ANALYZE 2 | SELECT name, type, department_id 3 | FROM Program 4 | IGNORE INDEX FOR JOIN(program_department_id_fkey) 5 | WHERE department_id=1 6 | GROUP BY name, type, department_id 7 | ORDER BY department_id; 8 | -------------------------------------------------------------------------------- /sql-queries-index/sql-ignore-index/mysql-ignore-index-for-order-by.sql: -------------------------------------------------------------------------------- 1 | EXPLAIN ANALYZE 2 | SELECT name, type, department_id 3 | FROM Program 4 | IGNORE INDEX FOR ORDER BY(program_department_id_fkey) 5 | WHERE department_id=1 6 | GROUP BY name, type, department_id 7 | ORDER BY department_id; 8 | -------------------------------------------------------------------------------- /sql-queries-index/sql-ignore-index/mysql-optimizer-hint-no-index.sql: -------------------------------------------------------------------------------- 1 | EXPLAIN ANALYZE 2 | SELECT /*+ NO_INDEX(Program program_department_id_fkey)*/ name, type, department_id 3 | FROM Program 4 | WHERE department_id =1 5 | GROUP BY name, type, department_id 6 | ORDER BY department_id; 7 | -------------------------------------------------------------------------------- /sql-queries-index/sql-ignore-index/mysql-show-indexes.sql: -------------------------------------------------------------------------------- 1 | SHOW INDEXES 2 | FROM Program; 3 | -------------------------------------------------------------------------------- /sql-queries-index/sql-ignore-index/sql-server-WITH-clause.sql: -------------------------------------------------------------------------------- 1 | SELECT name, type, department_id 2 | FROM Program 3 | WITH (INDEX(PK__Program__3213E83F9B13E52E,csindx_simple)) 4 | WHERE department_id =1 5 | GROUP BY name, type, department_id 6 | ORDER BY department_id; 7 | -------------------------------------------------------------------------------- /sql-queries-index/sql-ignore-index/sql-server-ignore-index-by-exclusion.sql: -------------------------------------------------------------------------------- 1 | SELECT name, type, department_id 2 | FROM Program 3 | WITH (INDEX(PK__Program__3213E83F9B13E52E)) 4 | WHERE department_id =1 5 | GROUP BY name, type, department_id 6 | ORDER BY department_id; 7 | -------------------------------------------------------------------------------- /sql-queries-index/sql-ignore-index/sql-server-ignore-index-hint.sql: -------------------------------------------------------------------------------- 1 | SELECT name, type, department_id 2 | FROM Program 3 | WHERE department_id =1 AND type='Major' 4 | GROUP BY name, type, department_id 5 | ORDER BY department_id 6 | OPTION (IGNORE_NONCLUSTERED_COLUMNSTORE_INDEX); 7 | -------------------------------------------------------------------------------- /sql-queries-index/sql-ignore-index/sql-server-setup.sql: -------------------------------------------------------------------------------- 1 | CREATE NONCLUSTERED COLUMNSTORE INDEX csindx_simple 2 | ON Program (department_id, type); 3 | -------------------------------------------------------------------------------- /sql-queries-like/README.md: -------------------------------------------------------------------------------- 1 | [When to Use Equals (=) vs. LIKE in SQL Queries](https://www.baeldung.com/sql/queries-equals-vs-like) 2 | -------------------------------------------------------------------------------- /sql-queries-like/equals-vs-like/Equals (=) String Comparison.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Student 3 | WHERE name = 'John Liu'; 4 | 5 | SELECT * 6 | FROM Student 7 | WHERE name = 'jòhn liù'; 8 | -------------------------------------------------------------------------------- /sql-queries-like/equals-vs-like/Equals (=) With Date and Time Data.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Student 3 | WHERE birth_date = '2001-04-05'; 4 | 5 | SELECT * 6 | FROM Student 7 | WHERE birth_date >= '2001-04-05' 8 | AND birth_date < '2001-04-06'; 9 | 10 | SELECT * 11 | FROM Student 12 | WHERE birth_date = '2001-04-05 08:30:00'; 13 | -------------------------------------------------------------------------------- /sql-queries-like/equals-vs-like/Equals (=) With Numeric Data.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Student 3 | WHERE id = 1001; 4 | -------------------------------------------------------------------------------- /sql-queries-like/equals-vs-like/LIKE Wildcard Characters.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Student 3 | WHERE name LIKE 'S%'; 4 | 5 | SELECT * 6 | FROM Student 7 | WHERE name LIKE 'R% R__'; 8 | -------------------------------------------------------------------------------- /sql-queries-like/equals-vs-like/LIKE vs. Equals (=).sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Student 3 | WHERE name = 'Agatha Christi '; 4 | 5 | SELECT * 6 | FROM Student 7 | WHERE name LIKE 'Agatha Christi '; 8 | -------------------------------------------------------------------------------- /sql-queries/column-search/column-search-mssql.sql: -------------------------------------------------------------------------------- 1 | SELECT t.name AS table_name 2 | FROM sys.tables t 3 | JOIN sys.columns c ON t.object_id = c.object_id 4 | WHERE c.name = 'department_id'; 5 | 6 | SELECT OBJECT_NAME(object_id) AS table_name 7 | FROM sys.columns 8 | WHERE name = 'department_id'; -------------------------------------------------------------------------------- /sql-queries/column-search/column-search-pg.sql: -------------------------------------------------------------------------------- 1 | SELECT c.relname AS table_name 2 | FROM pg_catalog.pg_attribute a 3 | JOIN pg_catalog.pg_class c ON a.attrelid = c.oid 4 | WHERE a.attname = 'department_id'; 5 | 6 | SELECT c.relname AS table_name 7 | FROM pg_catalog.pg_attribute a 8 | JOIN pg_catalog.pg_class c ON a.attrelid = c.oid 9 | WHERE a.attname = 'department_id' 10 | AND c.relkind = 'r'; -------------------------------------------------------------------------------- /sql-queries/column-search/column-search.sql: -------------------------------------------------------------------------------- 1 | SELECT table_name 2 | FROM information_schema.columns 3 | WHERE column_name = 'department_id'; -------------------------------------------------------------------------------- /sql-queries/identify-duplicate-values/functions-and-clauses.sql: -------------------------------------------------------------------------------- 1 | -- COUNT function 2 | select COUNT(emp_id) from employee; 3 | 4 | -- GROUP BY clause 5 | select office_location, count(emp_id) from employee group by office_location; 6 | 7 | -- HAVING clause 8 | select office_location, count(emp_id) from employee group by office_location having office_location = 'Palo Alto'; 9 | -------------------------------------------------------------------------------- /sql-queries/identify-duplicate-values/identify-duplicate-rows.sql: -------------------------------------------------------------------------------- 1 | -- duplicate values in one column 2 | SELECT emp_id, COUNT(emp_id) 3 | FROM employee 4 | GROUP BY emp_id 5 | HAVING COUNT(emp_id) > 1; 6 | 7 | -- duplicate values in multiple columns 8 | SELECT emp_id, first_name, last_name, COUNT(*) 9 | FROM employee 10 | GROUP BY emp_id, first_name, last_name 11 | HAVING COUNT(*) > 1; 12 | -------------------------------------------------------------------------------- /sql-queries/inner-join/inner-join-3-tables.sql: -------------------------------------------------------------------------------- 1 | SELECT Employees.name, Departments.department_name, Salaries.salary 2 | FROM Employees 3 | INNER JOIN Departments ON Employees.department_id = Departments.department_id 4 | INNER JOIN Salaries ON Employees.employee_id = Salaries.employee_id; -------------------------------------------------------------------------------- /sql-queries/inner-join/nested-subquerie-inner-join.sql: -------------------------------------------------------------------------------- 1 | SELECT emp_dept.name, emp_dept.department_name, Salaries.salary 2 | FROM (SELECT Employees.name, Employees.employee_id, Departments.department_name 3 | FROM Employees 4 | INNER JOIN Departments ON Employees.department_id = Departments.department_id) AS emp_dept 5 | INNER JOIN Salaries ON emp_dept.employee_id = Salaries.employee_id; -------------------------------------------------------------------------------- /sql-queries/list-tables/list-tables-mssql.sql: -------------------------------------------------------------------------------- 1 | SELECT name FROM sys.tables; -------------------------------------------------------------------------------- /sql-queries/list-tables/list-tables-mysql.sql: -------------------------------------------------------------------------------- 1 | show tables; -------------------------------------------------------------------------------- /sql-queries/list-tables/list-tables-pg.sql: -------------------------------------------------------------------------------- 1 | SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = 'public'; -------------------------------------------------------------------------------- /sql-queries/list-tables/list-tables.sql: -------------------------------------------------------------------------------- 1 | SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE'; -------------------------------------------------------------------------------- /sql-queries/matching-multiple-patterns/matching-multiple-patterns-postgresql.sql: -------------------------------------------------------------------------------- 1 | -- Using LIKE With ARRAY 2 | SELECT name, textbook 3 | FROM Course 4 | WHERE name LIKE ANY (ARRAY ['Introduction to%', 'Advanced%']); 5 | 6 | -- Using the SIMILAR operator 7 | SELECT name, textbook 8 | FROM Course 9 | WHERE name SIMILAR TO 'Introduction to%|Advanced%'; -------------------------------------------------------------------------------- /sql-queries/matching-multiple-patterns/migration-multiple-patterns-sqlserver.sql: -------------------------------------------------------------------------------- 1 | -- Using CONTAINS 2 | SELECT name, textbook 3 | FROM Course 4 | WHERE CONTAINS (name, '"Introduction to*" OR "Advanced*"'); 5 | -------------------------------------------------------------------------------- /sql-queries/prevent-division-by-zero/prevent-division-by-zero-sqlserver.sql: -------------------------------------------------------------------------------- 1 | SET ARITHABORT OFF; 2 | SET ANSI_WARNINGS OFF; -------------------------------------------------------------------------------- /sql-queries/sql-if-then/case-query.sql: -------------------------------------------------------------------------------- 1 | SELECT student_id, course_id, 2 | CASE 3 | WHEN grade = 'A+' THEN 'SUPER' 4 | WHEN grade = 'A' THEN 'EXCELLENT' 5 | WHEN grade = 'B+' THEN 'GOOD' 6 | WHEN grade = 'B' THEN 'SATISFACTORY' 7 | WHEN grade = 'C' THEN 'NEEDS IMPROVEMENT' 8 | ELSE 'POOR' 9 | END AS grade_remarks 10 | FROM EXAM; -------------------------------------------------------------------------------- /sql-queries/sql-if-then/choose-query-sql.sql: -------------------------------------------------------------------------------- 1 | SELECT student_id, course_id, 2 | CHOOSE( 3 | CASE grade 4 | WHEN 'A+' THEN 1 5 | WHEN 'A' THEN 2 6 | WHEN 'B+' THEN 3 7 | WHEN 'B' THEN 4 8 | WHEN 'C' THEN 5 9 | ELSE 6 10 | END, 11 | 'SUPER', 'EXCELLENT', 'GOOD', 'SATISFACTORY', 'NEEDS IMPROVEMENT', 'POOR' 12 | ) AS grade_remarks 13 | FROM EXAM; -------------------------------------------------------------------------------- /sql-queries/sql-if-then/elt-query-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT student_id, course_id, 2 | ELT( 3 | CASE grade 4 | WHEN 'A+' THEN 1 5 | WHEN 'A' THEN 2 6 | WHEN 'B+' THEN 3 7 | WHEN 'B' THEN 4 8 | WHEN 'C' THEN 5 9 | ELSE 6 10 | END, 11 | 'SUPER', 'EXCELLENT', 'GOOD', 'SATISFACTORY', 'NEEDS IMPROVEMENT', 'POOR' 12 | ) AS grade_remarks 13 | FROM EXAM; -------------------------------------------------------------------------------- /sql-queries/sql-if-then/if-query-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT student_id, course_id, 2 | IF(grade = 'A+', 'SUPER', 3 | IF(grade = 'A', 'EXCELLENT', 4 | IF(grade = 'B+', 'GOOD', 5 | IF(grade = 'B', 'SATISFACTORY', 6 | IF(grade = 'C', 'NEEDS IMPROVEMENT', 'POOR')))) 7 | ) AS grade_remarks 8 | FROM EXAM; -------------------------------------------------------------------------------- /sql-queries/sql-if-then/iif-query-sql.sql: -------------------------------------------------------------------------------- 1 | SELECT student_id, course_id, 2 | IIF(grade = 'A+', 'SUPER', 3 | IIF(grade = 'A', 'EXCELLENT', 4 | IIF(grade = 'B+', 'GOOD', 5 | IIF(grade = 'B', 'SATISFACTORY', 6 | IIF(grade = 'C', 'NEEDS IMPROVEMENT', 'POOR')))) 7 | ) AS grade_remarks 8 | FROM EXAM; -------------------------------------------------------------------------------- /sql-queries/sql-in-vs-exists/exists-operator-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Exam WHERE EXISTS(SELECT * FROM Department WHERE Exam.id=Department.id); -------------------------------------------------------------------------------- /sql-queries/sql-in-vs-exists/in-operator-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Department WHERE code IN('ME', 'CE'); -------------------------------------------------------------------------------- /sql-queries/sql-in-vs-exists/in-operator-subquery-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Exam WHERE id IN (SELECT id FROM Department); -------------------------------------------------------------------------------- /sql-queries/sql-text-search/search-all.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Product WHERE description LIKE '%Milk%' OR description LIKE '%Dark%'; 2 | SELECT * FROM Product WHERE LOWER(description) LIKE LOWER('%Milk%') OR LOWER(description) LIKE LOWER('%Dark%'); -------------------------------------------------------------------------------- /sql-queries/sql-text-search/search-mssql.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Product WHERE CHARINDEX('Milk', description) > 0 OR CHARINDEX('Dark', description) > 0; -------------------------------------------------------------------------------- /sql-queries/sql-text-search/search-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Product WHERE description REGEXP 'Milk' OR description REGEXP 'Dark'; 2 | SELECT * FROM Product WHERE POSITION('Milk' IN description) > 0 OR POSITION('Dark' IN description) > 0; 3 | SELECT * FROM Product WHERE POSITION('milk' IN LOWER(description)) > 0 OR POSITION('dark' IN LOWER(description)) > 0; -------------------------------------------------------------------------------- /sql-queries/sql-text-search/search-pg.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM Product WHERE description ~ 'Milk' OR description ~ 'Dark'; 2 | SELECT * FROM Product WHERE POSITION('Milk' IN description) > 0 OR POSITION('Dark' IN description) > 0; 3 | SELECT * FROM Product WHERE POSITION('milk' IN LOWER(description)) > 0 OR POSITION('dark' IN LOWER(description)) > 0; -------------------------------------------------------------------------------- /sql-subqueries/README.md: -------------------------------------------------------------------------------- 1 | ### Relevant Articles 2 | - [Difference Between CTE and Subquery](https://www.baeldung.com/sql/cte-vs-subquery) -------------------------------------------------------------------------------- /sql-subqueries/difference_between_CTE_and_Subquery/correlated_subquery.sql: -------------------------------------------------------------------------------- 1 | SELECT name 2 | FROM student s 3 | WHERE ( 4 | SELECT COUNT(*) 5 | FROM registration r 6 | WHERE r.student_id = s.id 7 | ) = ( 8 | SELECT MAX(course_count) 9 | FROM ( 10 | SELECT COUNT(*) AS course_count 11 | FROM registration 12 | GROUP BY student_id 13 | ) AS subquery 14 | ); 15 | -------------------------------------------------------------------------------- /sql-subqueries/difference_between_CTE_and_Subquery/multi_row_subquery.sql: -------------------------------------------------------------------------------- 1 | SELECT name 2 | FROM student 3 | WHERE id IN ( 4 | SELECT student_id 5 | FROM registration 6 | WHERE course_id IN ( 7 | SELECT course_id 8 | FROM teaching 9 | WHERE faculty_id = ( 10 | SELECT id 11 | FROM faculty 12 | WHERE name = 'Rory Ross' 13 | ) 14 | ) 15 | ); 16 | -------------------------------------------------------------------------------- /sql-subqueries/difference_between_CTE_and_Subquery/scalar_subquery.sql: -------------------------------------------------------------------------------- 1 | SELECT name, gpa, 2 | (SELECT AVG(gpa) FROM student) AS avg_gpa 3 | FROM student 4 | WHERE gpa > (SELECT AVG(gpa) FROM student); 5 | -------------------------------------------------------------------------------- /sql-subqueries/difference_between_CTE_and_Subquery/subquery_use_case.sql: -------------------------------------------------------------------------------- 1 | SELECT name 2 | FROM student 3 | WHERE id IN ( 4 | SELECT student_id 5 | FROM registration 6 | WHERE course_id = ( 7 | SELECT id 8 | FROM course 9 | WHERE name = 'Introduction to Structural Engineering' 10 | ) 11 | ); 12 | 13 | -------------------------------------------------------------------------------- /sql-subqueries/how-to-use-SELECT-with-multiple-subqueries-to-same-table-in-SQL/subqueries-in-SELECT-clause.sql: -------------------------------------------------------------------------------- 1 | SELECT s.name, 2 | (SELECT COUNT(*) 3 | FROM Exam e 4 | WHERE e.student_id = s.id) AS exam_count 5 | FROM Student s; -------------------------------------------------------------------------------- /sql-subqueries/how-to-use-SELECT-with-multiple-subqueries-to-same-table-in-SQL/subqueries-in-WHERE-clause.sql: -------------------------------------------------------------------------------- 1 | SELECT s.name 2 | FROM Student s 3 | WHERE 5 < ( 4 | SELECT COUNT(*) 5 | FROM Exam e 6 | WHERE e.student_id = s.id 7 | ); -------------------------------------------------------------------------------- /sql-subqueries/subquery-vs-correlated-subquery/subquery.sql: -------------------------------------------------------------------------------- 1 | SELECT s.name AS student_name, s.gpa 2 | FROM Student s 3 | WHERE s.id IN 4 | (SELECT r.student_id 5 | FROM Registration r 6 | INNER JOIN Course c ON r.course_id = c.id 7 | WHERE c.department_id = 8 | (SELECT id 9 | FROM Department 10 | WHERE name = 'Mathematics')); -------------------------------------------------------------------------------- /sql-syntax/CASE_Statement_With_SELECT/CASE_with_aggregate_function.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | CASE 3 | WHEN enrollment_date BETWEEN '2020-01-01' AND '2020-12-31' THEN '2020' 4 | WHEN enrollment_date BETWEEN '2021-01-01' AND '2021-12-31' THEN '2021' 5 | WHEN enrollment_date BETWEEN '2022-01-01' AND '2022-12-31' THEN '2022' 6 | END AS enrollment_year, 7 | COUNT(*) AS student_count 8 | FROM Student 9 | GROUP BY enrollment_year; -------------------------------------------------------------------------------- /sql-syntax/CASE_Statement_With_SELECT/CASE_with_subqueries.sql: -------------------------------------------------------------------------------- 1 | SELECT s.name, s.enrollment_date, 2 | CASE 3 | WHEN s.gpa >= ( 4 | SELECT AVG(gpa) 5 | FROM Student 6 | WHERE YEAR(enrollment_date) = YEAR(s.enrollment_date) 7 | ) THEN 'Above Average' 8 | ELSE 'Below Average' 9 | END AS gpa_rank 10 | FROM Student s; 11 | -------------------------------------------------------------------------------- /sql-syntax/CASE_Statement_With_SELECT/calculations_within_CASE_statement.sql: -------------------------------------------------------------------------------- 1 | SELECT name, 2 | CASE 3 | WHEN gpa >= 3.5 THEN 0.1 * 1000 4 | WHEN gpa >= 3.0 THEN 0.05 * 1000 5 | ELSE 0 6 | END AS bonus 7 | FROM Student; -------------------------------------------------------------------------------- /sql-syntax/CASE_Statement_With_SELECT/searched_CASE.sql: -------------------------------------------------------------------------------- 1 | SELECT name, 2 | CASE 3 | WHEN gpa >= 3.5 THEN 'Honors' 4 | WHEN gpa >= 2.5 THEN 'Satisfactory' 5 | ELSE 'Needs Improvement' 6 | END AS performance 7 | FROM Student; -------------------------------------------------------------------------------- /sql-syntax/CASE_Statement_With_SELECT/simple_CASE.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, 2 | CASE is_active 3 | WHEN 'Yes' THEN 'Active' 4 | WHEN 'No' THEN 'Inactive' 5 | END AS status 6 | FROM Course; 7 | -------------------------------------------------------------------------------- /sql-syntax/escape-single-quote/escape-single-quote-mssql.sql: -------------------------------------------------------------------------------- 1 | -- Using the NCHAR() function to manage the name John O’Liu 2 | INSERT INTO Student (id, name, national_id, birth_date, enrollment_date, graduation_date, gpa) 3 | VALUES (1001, 'John O' + NCHAR(39) + 'Liu', 123345566, '2001-04-05', '2020-01-15', '2024-06-15', 4); 4 | 5 | -- Using a SELECT query with the NCHAR() function to retrieve the row values 6 | SELECT * FROM Student 7 | WHERE name = 'John O' + NCHAR(39) + 'Liu'; 8 | -------------------------------------------------------------------------------- /sql-syntax/escape-single-quote/escape-single-quote-mysql.sql: -------------------------------------------------------------------------------- 1 | -- CHAR(39) generates a single quote (‘), which is then used with the CONCAT() function to combine the strings ‘John O’ and ‘Liu’, along with the single quote 2 | INSERT INTO Student (id, name, national_id, birth_date, enrollment_date, graduation_date, gpa) 3 | VALUES (1001, CONCAT('John O', CHAR(39), 'Liu'), 123345566, '2001-04-05', '2020-01-15', '2024-06-15', 4); 4 | -------------------------------------------------------------------------------- /table-operations-2/README.md: -------------------------------------------------------------------------------- 1 | ### Relevant Articles: 2 | - [How to Find the Engine for a Specific Table in MySQL?](https://www.baeldung.com/sql/mysql-find-table-storage-engine) 3 | - [Changing a Table’s Storage Engine in MySQL](https://www.baeldung.com/sql/mysql-change-table-storage-engine) 4 | - [Pattern Matching in MySQL](https://www.baeldung.com/sql/mysql-pattern-matching) 5 | - [Comments in MySQL](https://www.baeldung.com/sql/mysql-comments-single-line-multiline-hint) -------------------------------------------------------------------------------- /table-operations-2/change-table-engine-in-mysql/changing-storage-engine.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE Student ENGINE=MyISAM; 2 | 3 | SELECT 4 | engine 5 | FROM 6 | information_schema.tables 7 | WHERE 8 | table_schema = 'University' 9 | AND table_name = 'Student'; 10 | 11 | ALTER TABLE Student ENGINE=InnoDB; -------------------------------------------------------------------------------- /table-operations-2/change-table-engine-in-mysql/checking-storage-engine.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | engine 3 | FROM 4 | information_schema.tables 5 | WHERE 6 | table_schema = 'University' 7 | AND table_name = 'Student'; 8 | 9 | SHOW TABLE STATUS LIKE 'Student'; -------------------------------------------------------------------------------- /table-operations-2/change-table-engine-in-mysql/show-storage-engine.sql: -------------------------------------------------------------------------------- 1 | SHOW ENGINES; -------------------------------------------------------------------------------- /table-operations-2/comments-mysql/comments.mysql: -------------------------------------------------------------------------------- 1 | -- This query returns all Students in the University 2 | SELECT * FROM Student; 3 | SELECT * FROM Student -- WHERE NAME = 'John'; 4 | 5 | SELECT * FROM Student WHERE NAME /* wild card matching for name */ LIKE '%John%'; 6 | 7 | SELECT * FROM Student WHERE NAME 8 | /* wild card matching for name. 9 | Change it based on the requirement 10 | */ 11 | LIKE '%John%'; 12 | 13 | SELECT /*! STRAIGHT_JOIN */ * FROM Student /*+ USE INDEX (PRIMARY) */ WHERE id = 1001; -------------------------------------------------------------------------------- /table-operations-2/detect-locked-table-mysql/checking-lock-in-performance_schema.metadata_locks.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM performance_schema.metadata_locks 2 | WHERE OBJECT_TYPE = 'USER LEVEL LOCK'; -------------------------------------------------------------------------------- /table-operations-2/detect-locked-table-mysql/locking-table.sql: -------------------------------------------------------------------------------- 1 | LOCK TABLES Student WRITE; 2 | 3 | -------------------------------------------------------------------------------- /table-operations-2/detect-locked-table-mysql/unlock-table.sql: -------------------------------------------------------------------------------- 1 | UNLOCK TABLES; 2 | 3 | SELECT RELEASE_LOCK('Student'); -------------------------------------------------------------------------------- /table-operations-2/detect-locked-table-mysql/using-show-open-table.sql: -------------------------------------------------------------------------------- 1 | SHOW OPEN TABLES WHERE `Table` LIKE 'Student' AND `Database` LIKE 'University' AND In_use > 0; 2 | 3 | SHOW OPEN TABLES WHERE In_use > 0; -------------------------------------------------------------------------------- /table-operations-2/mysql-images/images/cb_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/sql-tutorials/cd7dd50e082cddbf50c3be20089272a8bad142f0/table-operations-2/mysql-images/images/cb_logo.png -------------------------------------------------------------------------------- /table-operations-2/mysql-images/images/cs_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/sql-tutorials/cd7dd50e082cddbf50c3be20089272a8bad142f0/table-operations-2/mysql-images/images/cs_logo.png -------------------------------------------------------------------------------- /table-operations-2/mysql-images/images/ece_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/sql-tutorials/cd7dd50e082cddbf50c3be20089272a8bad142f0/table-operations-2/mysql-images/images/ece_logo.png -------------------------------------------------------------------------------- /table-operations-2/mysql-images/images/john_pp.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/sql-tutorials/cd7dd50e082cddbf50c3be20089272a8bad142f0/table-operations-2/mysql-images/images/john_pp.jpeg -------------------------------------------------------------------------------- /table-operations-2/mysql-images/images/ma_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/sql-tutorials/cd7dd50e082cddbf50c3be20089272a8bad142f0/table-operations-2/mysql-images/images/ma_logo.png -------------------------------------------------------------------------------- /table-operations-2/mysql-images/images/philip_pp.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/sql-tutorials/cd7dd50e082cddbf50c3be20089272a8bad142f0/table-operations-2/mysql-images/images/philip_pp.jpeg -------------------------------------------------------------------------------- /table-operations-2/mysql-images/images/rita_pp.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/sql-tutorials/cd7dd50e082cddbf50c3be20089272a8bad142f0/table-operations-2/mysql-images/images/rita_pp.jpeg -------------------------------------------------------------------------------- /table-operations-2/mysql-images/images/samantha_pp.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/sql-tutorials/cd7dd50e082cddbf50c3be20089272a8bad142f0/table-operations-2/mysql-images/images/samantha_pp.jpeg -------------------------------------------------------------------------------- /table-operations-2/mysql-images/images/ss_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/sql-tutorials/cd7dd50e082cddbf50c3be20089272a8bad142f0/table-operations-2/mysql-images/images/ss_logo.png -------------------------------------------------------------------------------- /table-operations-2/mysql-images/images/vikas_pp.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/sql-tutorials/cd7dd50e082cddbf50c3be20089272a8bad142f0/table-operations-2/mysql-images/images/vikas_pp.jpeg -------------------------------------------------------------------------------- /table-operations-2/mysql-store-json/creating-table-example.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE Departments ( 2 | id INT PRIMARY KEY NOT NULL, 3 | name VARCHAR(50) NOT NULL, 4 | info JSON 5 | ); -------------------------------------------------------------------------------- /table-operations-2/mysql-store-json/retrieving-json-data.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, info FROM Departments; 2 | 3 | SELECT id, name, JSON_EXTRACT(info, '$.head') AS head FROM Departments; 4 | 5 | SELECT id, name, info->'$.head' AS head FROM Departments; -------------------------------------------------------------------------------- /table-operations/Adding-Comment-to-Table-Columns-in-SQL/Adding-Comments-to-Table-Columns-in-SQLServer.sql: -------------------------------------------------------------------------------- 1 | --Adding Description to the 'name' Column of Existing 'Department' Table 2 | EXEC sp_addextendedproperty @name = N'Description', 3 | @value = N'Department name', 4 | @level0type = N'SCHEMA', @level0name = 'dbo', 5 | @level1type = N'TABLE', @level1name = 'Department', 6 | @level2type = N'COLUMN', @level2name = 'name'; 7 | -------------------------------------------------------------------------------- /table-operations/README.md: -------------------------------------------------------------------------------- 1 | ### Relevant Articles: 2 | - [Detecting Differences Between Two Tables in SQL](https://www.baeldung.com/sql/find-differences-between-tables)1 3 | - [Using ALTER to Drop a Column Only if the Column Exists in SQL](https://www.baeldung.com/sql/drop-column-if-exists) 4 | - [Altering a Column From NULL to NOT NULL in SQL](https://www.baeldung.com/sql/alter-column-constraint-not-null) 5 | - [Dropping a Database Table if It Exists in SQL](https://www.baeldung.com/sql/drop-table-if-exists) -------------------------------------------------------------------------------- /table-operations/altering-column-definition/altering-columns-to-not-null-mssql.sql: -------------------------------------------------------------------------------- 1 | --fetching students' data 2 | SELECT * FROM Student; 3 | 4 | --replacing null with 0.0 5 | UPDATE Student SET gpa = 0.0 6 | WHERE gpa IS NULL; 7 | 8 | --altering columns to not null in SQL Server 9 | ALTER TABLE Student 10 | ALTER COLUMN gpa REAL NOT NULL; 11 | -------------------------------------------------------------------------------- /table-operations/altering-column-definition/altering-columns-to-not-null-mysql.sql: -------------------------------------------------------------------------------- 1 | --fetching students' data 2 | SELECT * FROM Student; 3 | 4 | --replacing null with 0.0 5 | UPDATE Student SET gpa = 0.0 6 | WHERE gpa IS NULL; 7 | 8 | --altering columns to not null in MySQL 9 | ALTER TABLE Student 10 | MODIFY gpa REAL NOT NULL; 11 | -------------------------------------------------------------------------------- /table-operations/determine-database-version/mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT VERSION(); 2 | 3 | mysql -u root -e "SELECT VERSION()" 4 | 5 | SELECT @@GLOBAL.version; 6 | -------------------------------------------------------------------------------- /table-operations/determine-database-version/postgresql.sql: -------------------------------------------------------------------------------- 1 | SELECT version(); 2 | 3 | show server_version; 4 | 5 | SELECT * 6 | FROM pg_config 7 | WHERE name = 'VERSION'; 8 | -------------------------------------------------------------------------------- /table-operations/determine-database-version/sqlserver.sql: -------------------------------------------------------------------------------- 1 | SELECT @@VERSION; 2 | 3 | sqlcmd -S localhost -U sa -Q 'select @@VERSION' 4 | 5 | SELECT SERVERPROPERTY('productversion') AS productversion, SERVERPROPERTY ('productlevel') as productlevel, SERVERPROPERTY ('edition') as edition 6 | -------------------------------------------------------------------------------- /table-operations/drop-table-if-exists/script-ms-sql.sql: -------------------------------------------------------------------------------- 1 | Use University; 2 | 3 | SELECT * INTO Active_course 4 | FROM Course 5 | WHERE is_active = 'Yes'; 6 | 7 | SELECT name 8 | FROM sys.tables; 9 | 10 | DROP TABLE IF EXISTS Active_courses; 11 | 12 | SELECT name 13 | FROM sys.tables; 14 | 15 | DROP TABLE IF EXISTS Active_courses; 16 | -------------------------------------------------------------------------------- /table-operations/drop-table-if-exists/script-mysql.sql: -------------------------------------------------------------------------------- 1 | Use University; 2 | 3 | CREATE TABLE Active_courses AS 4 | SELECT * FROM Course 5 | WHERE is_active = 'Yes'; 6 | 7 | show tables; 8 | 9 | DROP TABLE IF EXISTS Active_courses; 10 | 11 | show tables; 12 | 13 | DROP TABLE IF EXISTS Active_courses; 14 | -------------------------------------------------------------------------------- /table-operations/insert-csv-file-into-sql-table/access-mysql-terminal.sh: -------------------------------------------------------------------------------- 1 | mysql -h 127.0.0.1 -P 3306 -u root -p -------------------------------------------------------------------------------- /table-operations/insert-csv-file-into-sql-table/implementation-in-postgres.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE employees ( 2 | id SERIAL PRIMARY KEY, 3 | name VARCHAR(50), 4 | age INTEGER, 5 | department VARCHAR(30), 6 | hire_date DATE 7 | ); 8 | 9 | \copy employees(id, name, age, department, hire_date) 10 | FROM '/home/kali/import-csv/employee_data.csv' 11 | DELIMITER ',' 12 | CSV HEADER; 13 | 14 | SELECT * FROM employees; -------------------------------------------------------------------------------- /table-operations/insert-csv-file-into-sql-table/sample-data.sh: -------------------------------------------------------------------------------- 1 | mkdir import-csv 2 | cd import-csv 3 | cat employee_data.csv 4 | pwd -------------------------------------------------------------------------------- /table-operations/insert-csv-file-into-sql-table/using-bulk-insert-comman.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE employees ( 2 | id INT PRIMARY KEY, 3 | name NVARCHAR(50), 4 | age INT, 5 | department NVARCHAR(30), 6 | hire_date DATE 7 | ); 8 | 9 | BULK INSERT employees 10 | FROM '/home/kali/import-csv/employee_data.csv' 11 | WITH ( 12 | FIELDTERMINATOR = ',', 13 | ROWTERMINATOR = '\n', 14 | FIRSTROW = 2 15 | ); -------------------------------------------------------------------------------- /table-operations/insert-csv-file-into-sql-table/using-mysqlimport-mysql.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE employee_data ( 2 | id INT PRIMARY KEY, 3 | name VARCHAR(50), 4 | age INT, 5 | department VARCHAR(30), 6 | hire_date DATE 7 | ); 8 | 9 | SELECT * FROM employee_data; -------------------------------------------------------------------------------- /table-operations/insert-csv-file-into-sql-table/using-mysqlimport.sh: -------------------------------------------------------------------------------- 1 | mysqlimport --local --fields-terminated-by=',' --lines-terminated-by='\n' --ignore-lines=1 --columns='id,name,age,department,hire_date' -u root -p --host=127.0.0.1 University /home/kali/import-csv/employee_data.csv -------------------------------------------------------------------------------- /table-operations/sql-alter-drop-if-exist/drop-conditional-alter-psql.sql: -------------------------------------------------------------------------------- 1 | DO $$ 2 | BEGIN 3 | IF EXISTS ( 4 | SELECT 1 5 | FROM information_schema.columns 6 | WHERE table_schema = 'public' 7 | AND table_name = 'student' 8 | AND column_name = 'national_id' 9 | ) THEN 10 | EXECUTE 'ALTER TABLE Student DROP COLUMN national_id'; 11 | END IF; 12 | END $$; 13 | 14 | 15 | SELECT * FROM Student LIMIT 3; 16 | -------------------------------------------------------------------------------- /table-operations/sql-alter-drop-if-exist/if-column-exist-mysql.sql: -------------------------------------------------------------------------------- 1 | SELECT column_name 2 | FROM information_schema.columns 3 | WHERE table_schema = 'University' AND table_name = 'Student' AND column_name = 'national_id'; 4 | -------------------------------------------------------------------------------- /table-operations/sql-alter-drop-if-exist/if-column-exist-psql.sql: -------------------------------------------------------------------------------- 1 | SELECT column_name 2 | FROM information_schema.columns 3 | WHERE table_schema = 'public' AND table_name = 'student' AND column_name = 'national_id'; 4 | -------------------------------------------------------------------------------- /table-operations/sql-alter-drop-if-exist/if-column-exist-sqlserver.sql: -------------------------------------------------------------------------------- 1 | SELECT COLUMN_NAME 2 | FROM INFORMATION_SCHEMA.COLUMNS 3 | WHERE TABLE_SCHEMA = 'dbo' 4 | AND TABLE_NAME = 'student' 5 | AND COLUMN_NAME = 'national_id'; 6 | -------------------------------------------------------------------------------- /table-operations/temporary-table-select/extract_data_into_temp.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM ( 3 | SELECT id, name, textbook, credits 4 | FROM Course 5 | WHERE is_active = 'No' 6 | ) 7 | AS Temp_table; 8 | -------------------------------------------------------------------------------- /table-operations/temporary-table-select/extract_data_into_temp_sqlserver.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, textbook, credits 2 | INTO #Inactive_courses 3 | FROM Course 4 | WHERE is_active = 'No'; 5 | SELECT * FROM #Inactive_courses; 6 | -------------------------------------------------------------------------------- /table-operations/temporary-table-select/temp_with_join_statement.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM ( 3 | SELECT id, name, textbook, credits 4 | FROM Course 5 | WHERE is_active = 'No' 6 | ) AS Temp_table 7 | JOIN Teaching ON Temp_table.id = Teaching.course_id; 8 | -------------------------------------------------------------------------------- /table-operations/temporary-table-select/temp_with_join_statement_SQLserver.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, textbook, credits 2 | INTO #Inactive_courses 3 | FROM Course 4 | WHERE is_active = 'No'; 5 | 6 | SELECT * 7 | FROM #Inactive_courses 8 | JOIN Teaching ON #Inactive_courses.id = Teaching.course_id; 9 | -------------------------------------------------------------------------------- /updating/insert-or-update-if-exists/merge-sql-server.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CS'); 2 | 3 | MERGE INTO Department AS target 4 | USING (SELECT 1 AS id, 'Computer Science' AS name, 'CSE' AS code) AS source 5 | ON target.id = source.id 6 | WHEN MATCHED THEN 7 | UPDATE SET name = source.name, code = source.code 8 | WHEN NOT MATCHED THEN 9 | INSERT (id, name, code) VALUES (source.id, source.name, source.code); 10 | 11 | SELECT * from Department; -------------------------------------------------------------------------------- /updating/insert-or-update-if-exists/on-conflict-postgresql.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CS'); 2 | 3 | INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CSE') 4 | ON CONFLICT (id) DO UPDATE SET name = 'Computer Science', code = 'CSE'; 5 | 6 | SELECT * from Department; -------------------------------------------------------------------------------- /updating/insert-or-update-if-exists/on-duplicate-key-mysql.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CS'); 2 | 3 | INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CSE') 4 | ON DUPLICATE KEY UPDATE name = 'Computer Science', code = 'CSE'; 5 | 6 | SELECT * from Department; -------------------------------------------------------------------------------- /updating/insert-or-update-if-exists/replace-mysql.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CS'); 2 | 3 | REPLACE INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CSE'); 4 | 5 | SELECT * from Department; -------------------------------------------------------------------------------- /updating/update-data-table/merge-into-pq.sql: -------------------------------------------------------------------------------- 1 | MERGE INTO department AS dept 2 | USING new_department AS new_dept 3 | ON dept.id = new_dept.id 4 | WHEN MATCHED THEN UPDATE 5 | SET name = new_dept.name, 6 | code = new_dept.code 7 | WHEN NOT MATCHED THEN 8 | INSERT (id, name, code) 9 | VALUES (new_dept.id, new_dept.name, new_dept.code); -------------------------------------------------------------------------------- /updating/update-data-table/merge-into.sql: -------------------------------------------------------------------------------- 1 | MERGE INTO department 2 | USING new_department 3 | ON department.id = new_department.id 4 | WHEN MATCHED THEN UPDATE 5 | SET department.name = new_department.name, 6 | department.code = new_department.code; -------------------------------------------------------------------------------- /updating/update-data-table/sample-table.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE New_Department 2 | ( 3 | id INT PRIMARY KEY NOT Null, 4 | name VARCHAR (50), 5 | code VARCHAR (4), 6 | UNIQUE (id) 7 | ); 8 | 9 | INSERT INTO New_Department (id, name, code) VALUES 10 | (1, 'Telecom Engineering', 'TE'), 11 | (2, 'Electronics and Communications', 'EC'), 12 | (3, 'Mechatronics Engineering', 'MET'), 13 | (4, 'Civil Engineering', 'CE'), 14 | (5, 'Software Engineering', 'SE'); 15 | -------------------------------------------------------------------------------- /updating/update-data-table/update-with-join-mysql.sql: -------------------------------------------------------------------------------- 1 | UPDATE department 2 | INNER JOIN new_department 3 | ON department.id = new_department.id 4 | SET department.name = new_department.name, 5 | department.code = new_department.code -------------------------------------------------------------------------------- /updating/update-data-table/update-with-join.sql: -------------------------------------------------------------------------------- 1 | UPDATE department 2 | SET department.name = new_department.name, 3 | department.code = new_department.code 4 | FROM department 5 | INNER JOIN new_department 6 | ON department.id = new_department.id; -------------------------------------------------------------------------------- /updating/update-data-table/update-with-subquery.sql: -------------------------------------------------------------------------------- 1 | UPDATE department 2 | SET name = (SELECT name FROM new_department WHERE new_department.id = department.id), 3 | code = (SELECT code FROM new_department WHERE new_department.id = department.id) 4 | WHERE department.id IN (SELECT id FROM new_department) -------------------------------------------------------------------------------- /updating/update-data-table/update-with-where-mysql.sql: -------------------------------------------------------------------------------- 1 | UPDATE 2 | department, 3 | new_department 4 | SET 5 | department.name = new_department.name, 6 | department.code = new_department.code 7 | WHERE 8 | department.id = new_department.id; -------------------------------------------------------------------------------- /updating/update-data-table/update-with-where-pg.sql: -------------------------------------------------------------------------------- 1 | UPDATE department dept 2 | SET name = new_dept.name, 3 | code = new_dept.code 4 | FROM new_department new_dept 5 | WHERE new_dept.id = dept.id; -------------------------------------------------------------------------------- /updating/update-data-table/update-with-where.sql: -------------------------------------------------------------------------------- 1 | UPDATE department 2 | SET department.name = new_department.name, 3 | department.code = new_department.code 4 | FROM department, new_department 5 | WHERE department.id = new_department.id -------------------------------------------------------------------------------- /updating/update-replace/update-replace-basic.sql: -------------------------------------------------------------------------------- 1 | UPDATE Student 2 | SET name = REPLACE(name, 'Liu', 'Smith'); 3 | -------------------------------------------------------------------------------- /updating/update-replace/update-replace-where.sql: -------------------------------------------------------------------------------- 1 | UPDATE Student 2 | SET name = REPLACE(name, 'Liu', 'Smith') 3 | WHERE name LIKE '%Liu%'; 4 | --------------------------------------------------------------------------------