diff --git a/src/data/roadmaps/sql/content/abs@6vYFb_D1N_-tLWZftL-Az.md b/src/data/roadmaps/sql/content/abs@6vYFb_D1N_-tLWZftL-Az.md index ec9c8fef7..603fb18e6 100644 --- a/src/data/roadmaps/sql/content/abs@6vYFb_D1N_-tLWZftL-Az.md +++ b/src/data/roadmaps/sql/content/abs@6vYFb_D1N_-tLWZftL-Az.md @@ -1,38 +1,8 @@ # ABS -The `ABS` function in SQL is used to return the absolute value of a number, i.e., the numeric value without its sign. The function takes a single argument which must be a number (integer, float, etc.) and returns the absolute, non-negative equivalent. +The `ABS()` function in SQL returns the absolute value of a given numeric expression, meaning it converts any negative number to its positive equivalent while leaving positive numbers unchanged. This function is useful when you need to ensure that the result of a calculation or a value stored in a database column is non-negative, such as when calculating distances, differences, or other metrics where only positive values make sense. For example, `SELECT ABS(-5)` would return `5`. -The general syntax for the ABS function is as follows: +Learn more from the following resources: -```sql -ABS(expression) -``` - -In the syntax above, the `expression` is required and can either be a literal number, a column name, the result of another function, or any valid SQL expression that resolves to a numeric value. - -## Examples - -Consider a database table `Orders`: - -| OrderID | Product | Quantity | -|---------|---------|----------| -| 1 | Apple | -5 | -| 2 | Banana | 10 | -| 3 | Cherry | -15 | - -If you want to get the absolute value of the 'Quantity' column, you could use the `ABS`function like this: - -```sql -SELECT OrderID, Product, ABS(Quantity) as 'Absolute Quantity' -FROM Orders; -``` - -The output will be: - -| OrderID | Product | Absolute Quantity | -|---------|---------|-------------------| -| 1 | Apple | 5 | -| 2 | Banana | 10 | -| 3 | Cherry | 15 | - -As you can see, the negative values in the 'Quantity' column have been converted to positive values by the `ABS` function. \ No newline at end of file +- [@article@How to compute an absolute value in SQL](https://www.airops.com/sql-guide/how-to-compute-an-absolute-value-in-sql) +- [@article@ABS](https://www.w3schools.com/sql/func_sqlserver_abs.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/advanced-functions@vTMd0bqz4eTgLnhfgY61h.md b/src/data/roadmaps/sql/content/advanced-functions@vTMd0bqz4eTgLnhfgY61h.md index 8ade965e0..76470429d 100644 --- a/src/data/roadmaps/sql/content/advanced-functions@vTMd0bqz4eTgLnhfgY61h.md +++ b/src/data/roadmaps/sql/content/advanced-functions@vTMd0bqz4eTgLnhfgY61h.md @@ -1,69 +1,8 @@ # Advanced SQL Functions -Advanced SQL functions provide complex data manipulation and query capabilities enabling the user to perform tasks that go beyond the capabilities of basic SQL commands. +Advanced SQL functions enable more sophisticated data manipulation and analysis within databases, offering powerful tools for complex queries. Key areas include: -## Window Function - -Windowing Functions provide the ability to perform calculations across sets of rows related to the current query row. - -```sql -SELECT productName, productLine, buyPrice, - AVG(buyPrice) OVER(PARTITION BY productLine) as avg_price -FROM products -ORDER BY productLine, buyPrice; -``` - -## Aggregate Function - -Aggregate functions return a single result row based on groups of rows, rather than on single rows. - -```sql -SELECT COUNT(*) FROM products; -``` - -## Analytic Functions - -Analytic functions compute an aggregate value based on a group of rows. They differ from aggregate functions in that they return multiple rows for each group. - -```sql -SELECT department_id, last_name, hire_date, - COUNT(*) OVER (PARTITION BY department_id) as dept_count, - RANK() OVER (PARTITION BY department_id ORDER BY hire_date) as ranking -FROM employees; -``` - -## Scalar Function - -A scalar function returns a single value each time it is invoked. It is based on the input value. - -```sql -SELECT UPPER(productName) FROM products; -``` - -## Stored Procedures - -Stored Procedures are a prepared SQL code that you can save so the code can be reused over and over again. - -```sql -CREATE PROCEDURE SelectAllProducts @Product varchar(50) -AS -SELECT * FROM products WHERE Product = @Product -GO; -``` - -## String Functions - -Functions that manipulate the string data types. For example, `LEFT()`, `LENGTH()`, `LOWER()`, etc. - -```sql -SELECT LEFT('This is a test', 4); -``` - -## Date Functions - -Functions that manipulate the date data types. For example, `GETDATE()`, `DATEADD()`, `DATEDIFF()`, etc. - -```sql -SELECT GETDATE() AS CurrentDateTime; -``` -Remember, not all types or functions are supported by every SQL distribution but most of them have some sort of equivalent. \ No newline at end of file +- **String Functions**: Manipulate text data using functions like `CONCAT`, `SUBSTRING`, and `REPLACE` to combine, extract, or modify strings. +- **Date & Time**: Manage temporal data with functions like `DATEADD`, `DATEDIFF`, and `FORMAT`, allowing for calculations and formatting of dates and times. +- **Numeric Functions**: Perform advanced calculations using functions such as `ROUND`, `FLOOR`, and `CEIL`, providing precision in numerical data processing. +- **Conditional**: Implement logic within queries using functions like `CASE`, `COALESCE`, and `NULLIF` to control data flow and handle conditional scenarios. \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/advanced-sql@UDqbT1y-YzBrljfKSz_RG.md b/src/data/roadmaps/sql/content/advanced-sql@UDqbT1y-YzBrljfKSz_RG.md index 04d5ee674..0cfe84c90 100644 --- a/src/data/roadmaps/sql/content/advanced-sql@UDqbT1y-YzBrljfKSz_RG.md +++ b/src/data/roadmaps/sql/content/advanced-sql@UDqbT1y-YzBrljfKSz_RG.md @@ -1,74 +1,3 @@ # Advanced SQL Concepts -Advanced SQL commands offer powerful functionality that allow you to conduct complex queries and operations on your database. These include operations like Stored Procedures, Triggers, Views, and more. - -## Stored Procedures - -A stored procedure is a prepared SQL code that you save, so the code can be reused over and over again. They are particularly useful when repetitive tasks need to be performed, with less client-server communication. - -```sql -CREATE PROCEDURE procedure_name -AS -sql_statement -GO; -``` - -## Triggers - -A Trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE, UPDATE) occurs. Triggers are useful for maintaining integrity in the database. Triggers can also be used to log historical data. - -```sql -CREATE TRIGGER trigger_name -ON table_name -FOR INSERT, UPDATE, DELETE -AS --- SQL Statements -``` - -## Views - -A view is a virtual table based on the result-set of an SQL statement. It allows you to view data that is derived from other tables. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. - -```sql -CREATE VIEW view_name AS -SELECT column1, column2, ... -FROM table_name -WHERE condition; -``` - -## JOINs - -JOINs are used to combine rows from two or more tables, based on a related column between them. Types include INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN. - -```sql -SELECT Orders.OrderID, Customers.CustomerName -FROM Orders -INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID; -``` - -## Subqueries - -A subquery is a query that is embedded in the WHERE or HAVING clause of another SQL query. Subqueries can return individual values or a list of records. - -```sql -SELECT column_name [, column_name ] -FROM table1 [, table2 ] -WHERE column_name OPERATOR - (SELECT column_name [, column_name ] - FROM table1 [, table2 ] - [WHERE]) -``` - -## Set Operators - -Set operators allow the results of multiple queries to be combined into a single result set. The UNION, UNION ALL, INTERSECT, and MINUS operators are some of the set operators. - -```sql -SELECT column_name(s) FROM table1 -UNION -SELECT column_name(s) FROM table2; -``` - -Note: Make sure to adjust the code examples given above according to your specific use case. In some cases, you may also need to adjust them according to the syntax of the specific SQL variant that you are using. - -Also, it's important to note that these are some of the many advanced SQL topics. There are others like Window functions, CTEs, Pivoting and more. Another important area is working with different database systems as each system (like MySQL, PostgreSQL, etc.) has its own specific set of features and syntax. \ No newline at end of file +Advanced SQL concepts encompass a wide range of sophisticated techniques and features that go beyond basic querying and data manipulation. These include complex joins, subqueries, window functions, stored procedures, triggers, and advanced indexing strategies. By mastering these concepts, database professionals can optimize query performance, implement complex business logic, ensure data integrity, and perform advanced data analysis, enabling them to tackle more challenging database management and data processing tasks in large-scale, enterprise-level applications. \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/aggregate-queries@LX9nzJ4uqznHN4SksoDvr.md b/src/data/roadmaps/sql/content/aggregate-queries@LX9nzJ4uqznHN4SksoDvr.md index 14abe37a4..e7e289fe6 100644 --- a/src/data/roadmaps/sql/content/aggregate-queries@LX9nzJ4uqznHN4SksoDvr.md +++ b/src/data/roadmaps/sql/content/aggregate-queries@LX9nzJ4uqznHN4SksoDvr.md @@ -1,80 +1,10 @@ # Aggregate Queries -SQL aggregate functions are inbuilt functions that are used to perform some calculation on the data and return a single value. This is why they form the basis for "aggregate queries". These functions operate on a set of rows and return a single summarized result. - -## Common Aggregate Functions - -**1. COUNT()** - -Counts the number of rows. - - ```sql - SELECT COUNT(column_name) - FROM table_name - WHERE condition; - ``` - -**2. SUM()** - -Returns the sum of a numeric column. - - ```sql - SELECT SUM(column_name) - FROM table_name - WHERE condition; - ``` - -**3. AVG()** - -Returns the average value of a numeric column. - - ```sql - SELECT AVG(column_name) - FROM table_name - WHERE condition; - ``` - -**4. MIN()** - -Returns the smallest value of the selected column. - - ```sql - SELECT MIN(column_name) - FROM table_name - WHERE condition; - ``` - -**5. MAX()** - -Returns the largest value of the selected column. - - ```sql - SELECT MAX(column_name) - FROM table_name - WHERE condition; - ``` - -These functions ignore NULL values. - -## GROUP BY and HAVING Clauses - -To separate the results into groups of accumulated data, you can use the GROUP BY clause. - -```sql -SELECT column1, aggregate_function(column2) -FROM table -GROUP BY column1; -``` - -"A group" is represented by ROW(s) that have the same value in the specific column(s). The GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group by some columns. - -The HAVING clause is used with the GROUP BY clause, it applies to summarized group records, unlike the 'where' clause. It was added to SQL because the WHERE keyword could not be used with aggregate functions. - -```sql -SELECT column1, aggregate_function(column2) -FROM table -GROUP BY column1 -HAVING conditions; -``` - -Aggregate queries are simply a way of summarizing information in your database. Although they are a powerful tool, they can become complex very quickly, especially if you start nesting them together or combining multiple aggregate functions in a single query. \ No newline at end of file +Aggregate queries in SQL are used to perform calculations on multiple rows of data, returning a single summary value or grouped results. These queries typically involve the use of aggregate functions, such as: + + • COUNT(): Returns the number of rows that match a specific condition. + • SUM(): Calculates the total sum of a numeric column. + • AVG(): Computes the average value of a numeric column. + • MIN() and MAX(): Find the smallest and largest values in a column, respectively. + • GROUP BY: Used to group rows that share a common value in specified columns, allowing aggregate functions to be applied to each group. + • HAVING: Filters the results of a GROUP BY clause based on a specified condition, similar to WHERE but for groups. \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/alter-table@WjXlO42WL9saDS7RIGapt.md b/src/data/roadmaps/sql/content/alter-table@WjXlO42WL9saDS7RIGapt.md index 16cc41ffd..d92bed2fd 100644 --- a/src/data/roadmaps/sql/content/alter-table@WjXlO42WL9saDS7RIGapt.md +++ b/src/data/roadmaps/sql/content/alter-table@WjXlO42WL9saDS7RIGapt.md @@ -1,75 +1,8 @@ # Alter Table -The `ALTER TABLE` command in SQL is used to add, delete/drop, or modify columns in an existing table. It's also useful for adding and dropping constraints such as primary key, foreign key, etc. +The `ALTER TABLE` statement in SQL is used to modify the structure of an existing table. This includes adding, dropping, or modifying columns, changing the data type of a column, setting default values, and adding or dropping primary or foreign keys. -## Add Column +Learn more from the following resources: -A single column can be added using the following syntax: - -```sql -ALTER TABLE tableName -ADD columnName datatype; -``` - -To add more than one column: - -```sql -ALTER TABLE tableName -ADD (columnName1 datatype, - columnName2 datatype, - ... - ); -``` - -## Drop Column - -To drop a single column: - -```sql -ALTER TABLE tableName -DROP COLUMN columnName; -``` - -To drop multiple columns: - -```sql -ALTER TABLE tableName -DROP (columnName1, - columnName2, - ... - ); -``` - -## Modify Column - -To modify the datatype of a column: - -```sql -ALTER TABLE tableName -MODIFY COLUMN columnName newDataType; -``` - -## Add/Drop Constraints - -To add constraints: - -```sql -ALTER TABLE tableName -ADD CONSTRAINT constraintName -PRIMARY KEY (column1, column2, ... column_n); -``` - -To drop constraints: - -```sql -ALTER TABLE tableName -DROP CONSTRAINT constraintName; -``` - -To drop PRIMARY KEY: - -```sql -ALTER TABLE table_name -DROP PRIMARY KEY; -``` -In conclusion, `ALTER TABLE` in SQL lets you alter the structure of an existing table. This is a powerful command that lets you dynamically add, modify, and delete columns as well as the constraints placed on them. It ensures you are more flexible in dealing with changing data storage requirements. +- [@article@ALTER TABLE Statement](https://www.techonthenet.com/sql/tables/alter_table.php) +- [@article@ALTER TABLE - PostgreSQL](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-alter-table/) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/avg@Wou6YXLYUgomvcELh851L.md b/src/data/roadmaps/sql/content/avg@Wou6YXLYUgomvcELh851L.md index dcc59ff0e..5fd7009b8 100644 --- a/src/data/roadmaps/sql/content/avg@Wou6YXLYUgomvcELh851L.md +++ b/src/data/roadmaps/sql/content/avg@Wou6YXLYUgomvcELh851L.md @@ -1,40 +1,8 @@ # AVG -The `AVG()` function in SQL is an aggregate function that returns the average value of a numeric column. It calculates the sum of values in a column and then divides it by the count of those values. +The `AVG()` function in SQL is an aggregate function that calculates the average value of a numeric column. It returns the sum of all the values in the column, divided by the count of those values. -Syntax: -```sql -SELECT AVG(column_name) -FROM table_name; -``` -This statement will return the average value of the specified column. +Learn more from the following resources: -## Example Usage of AVG: - -Consider the following table `Orders`: - -| OrderID | CustomerID | Quantity | -|---------|------------|----------| -| 1 | A | 30 | -| 2 | A | 40 | -| 3 | B | 20 | -| 4 | B | 60 | -| 5 | C | 50 | -| 6 | C | 10 | - -Let's calculate the average quantity in the `Orders` table: -```sql -SELECT AVG(Quantity) AS AvgQuantity -FROM Orders; -``` -The result is 35. This value is the average of all `Quantity` values in the table. - -It's also possible to group the average function by one or more columns. For example, to find the average quantity of order per customer, we can write: -```sql -SELECT CustomerID, AVG(Quantity) as AvgQuantity -FROM Orders -GROUP BY CustomerID; -``` -It will calculate the average quantity for each customer and display the result along with the associated customer's ID. - -> Note: The `AVG()` function works only with numeric data types (`INT`, `FLOAT`, `DECIMAL`, etc.). It will return an error if used with non-numeric data types. +- [@article@AVG](https://www.sqlshack.com/sql-avg-function-introduction-and-examples/) +- [@article@SQL AVG() Function](https://www.w3schools.com/sql/sql_avg.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/basic-sql-syntax@JDDG4KfhtIlw1rkNCzUli.md b/src/data/roadmaps/sql/content/basic-sql-syntax@JDDG4KfhtIlw1rkNCzUli.md index 0b1ce2eed..69b616fd0 100644 --- a/src/data/roadmaps/sql/content/basic-sql-syntax@JDDG4KfhtIlw1rkNCzUli.md +++ b/src/data/roadmaps/sql/content/basic-sql-syntax@JDDG4KfhtIlw1rkNCzUli.md @@ -1,65 +1,6 @@ # Basic SQL Syntax -SQL, or Structured Query Language, uses a specific set of commands to interact with a database. It includes the use of keyword-like statements to accomplish several tasks such as creating, deleting, or modifying tables, retrieving, inserting, or modifying data. - -The `SELECT` statement is used to retrieve data from a database. The data returned is stored in a result table, called the result-set. - -```sql -SELECT column1, column2 FROM table_name; -``` - -The `INSERT INTO` statement is used to insert new rows of data in a table. - -```sql -INSERT INTO table_name (column1, column2, column3) -VALUES (value1, value2, value3); -``` - -The `UPDATE` statement is used to modify existing records in a table. - -```sql -UPDATE table_name -SET column1 = value1, column2 = value2 -WHERE condition; -``` - -The `DELETE` statement is used to remove rows from a table. - -```sql -DELETE FROM table_name WHERE condition; -``` - -The `CREATE TABLE` statement is used to create a new table in a database. - -```sql -CREATE TABLE table_name ( - column1 datatype constraints, - column2 datatype constraints, - column3 datatype constraints -); -``` - -The `ALTER TABLE ` statement is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop constraints on the existing table. - -```sql --- To add a column -ALTER TABLE table_name -ADD column_name datatype; - --- To delete/drop column -ALTER TABLE table_name -DROP COLUMN column_name; - --- To modify existing column -ALTER TABLE table_name -MODIFY COLUMN column_name datatype; -``` - -The `DROP TABLE` statement is used to drop an existing table in a database. - -```sql -DROP TABLE table_name; -``` +Basic SQL syntax consists of straightforward commands that allow users to interact with a relational database. The core commands include `SELECT` for querying data, `INSERT INTO` for adding new records, `UPDATE` for modifying existing data, and `DELETE` for removing records. Queries can be filtered using `WHERE`, sorted with `ORDER BY`, and data from multiple tables can be combined using `JOIN`. These commands form the foundation of SQL, enabling efficient data manipulation and retrieval within a database. Learn more about SQL from the following resources: diff --git a/src/data/roadmaps/sql/content/begin@7sTW1vwUhCFOMXYjScVEt.md b/src/data/roadmaps/sql/content/begin@7sTW1vwUhCFOMXYjScVEt.md index 0c0492a2c..3477e6d79 100644 --- a/src/data/roadmaps/sql/content/begin@7sTW1vwUhCFOMXYjScVEt.md +++ b/src/data/roadmaps/sql/content/begin@7sTW1vwUhCFOMXYjScVEt.md @@ -1,43 +1,8 @@ # BEGIN -In SQL, a transaction refers to a unit of work performed against a database. Transactions in SQL are used to ensure the integrity of the database. The keywords used in SQL to control the transactions are `BEGIN`, `COMMIT`, `ROLLBACK`. +`BEGIN` is used in SQL to start a transaction, which is a sequence of one or more SQL operations that are executed as a single unit. A transaction ensures that all operations within it are completed successfully before any changes are committed to the database. If any part of the transaction fails, the `ROLLBACK` command can be used to undo all changes made during the transaction, maintaining the integrity of the database. Once all operations are successfully completed, the `COMMIT` command is used to save the changes. Transactions are crucial for maintaining data consistency and handling errors effectively. -## BEGIN +Learn more from the following resources: -In the context of SQL transactions, `BEGIN` is a keyword used to start a transaction. It marks the point at which the data referenced by a connection is logically consistent. After the `BEGIN` statement, the transaction is considered to be "open" and remains so until it is committed or rolled back. - -Once you've initiated a transaction with `BEGIN`, all the subsequent SQL statements will be a part of this transaction until an explicit `COMMIT` or `ROLLBACK` is given. - -## Syntax - -The syntax to start a transaction is: -```sql -BEGIN TRANSACTION; -``` -or simply, -```sql -BEGIN; -``` -## Example - -Below is a simple example of using `BEGIN` in SQL: - -```sql -BEGIN; - -INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country) -VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway'); - -COMMIT; -``` - -In this example: -- `BEGIN;` marks the start of the transaction. -- The `INSERT` statement adds a new row of data to the `Customers` table. -- `COMMIT;` ends the transaction and permanently saves the changes made during this transaction. - -Note: If something goes wrong with one of the SQL statements within the transaction (after the `BEGIN;` statement), you can choose to `ROLLBACK` the transaction, which means canceling all the changes made in this transaction up to the point of error. - -## Conclusion - -In summary, `BEGIN` in SQL is used to start a transaction, which enables modifications done in a database to be viewed as a logically coherent occurrence. \ No newline at end of file +- [@article@BEGIN...END Statement](https://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc00801.1510/html/iqrefso/BABFBJAB.htm) +- [@article@SQL 'BEGIN' & 'END' Statements](https://reintech.io/blog/understanding-sql-begin-end-statements-guide) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/case@W2ePJHdfEiEJ3ZKoRQKt_.md b/src/data/roadmaps/sql/content/case@W2ePJHdfEiEJ3ZKoRQKt_.md index 73724bc06..b2306ae11 100644 --- a/src/data/roadmaps/sql/content/case@W2ePJHdfEiEJ3ZKoRQKt_.md +++ b/src/data/roadmaps/sql/content/case@W2ePJHdfEiEJ3ZKoRQKt_.md @@ -1,47 +1,8 @@ # CASE -`CASE` is a conditional statement in SQL that performs different actions based on different conditions. It allows you to perform IF-THEN-ELSE logic within SQL queries. It can be used in any statement or clause that allows a valid expression. +The CASE statement in SQL is used to create conditional logic within a query, allowing you to perform different actions based on specific conditions. It operates like an if-else statement, returning different values depending on the outcome of each condition. The syntax typically involves specifying one or more WHEN conditions, followed by the result for each condition, and an optional ELSE clause for a default outcome if none of the conditions are met. -There are two forms of the `CASE` statement: +Learn more from the following resources: -1. **Simple CASE expression** - It compares an expression to a set of simple expressions to return a result. - -```sql -SELECT column1, column2, -(CASE - WHEN condition1 THEN result1 - WHEN condition2 THEN result2 - ... - ELSE result -END) -FROM table_name; -``` - -2. **Searched CASE expression** - It evaluates a set of Boolean expressions to return a result. - -```sql -SELECT column1, column2, -(CASE - WHEN condition1 THEN result1 - WHEN condition2 THEN result2 - ... - ELSE result -END) -FROM table_name; -``` - -In both forms, `CASE` returns a result_1, result_2, ..., if condition_1, condition_2, ... is true. If no conditions are true, it returns the value in the `ELSE` clause. If the `ELSE` clause is omitted and no conditions are true, it returns NULL. - -Here's a concrete example: - -```sql -SELECT OrderID, Quantity, - (CASE - WHEN Quantity > 30 THEN 'Over 30' - WHEN Quantity = 30 THEN 'Equals 30' - ELSE 'Under 30' - END) AS QuantityText -FROM OrderDetails; -``` - -From the "OrderDetails" table, the statement lists 'OrderID', 'Quantity', and a column named 'QuantityText' that displays 'Over 30' if 'Quantity > 30' or 'Equals 30' if 'Quantity = 30' or 'Under 30' if both conditions are false. \ No newline at end of file +- [@article@SQL CASE Expression](https://www.w3schools.com/sql/sql_case.asp) +- [@article@SQL CASE - Intermediate SQL](https://mode.com/sql-tutorial/sql-case) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/ceiling@BAqJQvcguhIhzyII5LRH6.md b/src/data/roadmaps/sql/content/ceiling@BAqJQvcguhIhzyII5LRH6.md index 46dc29663..c14434969 100644 --- a/src/data/roadmaps/sql/content/ceiling@BAqJQvcguhIhzyII5LRH6.md +++ b/src/data/roadmaps/sql/content/ceiling@BAqJQvcguhIhzyII5LRH6.md @@ -1,24 +1,7 @@ # CEILING -`CEILING` is an advanced SQL function that is used to round up values. The function takes a single argument, which is a numeric or decimal number, and returns the smallest integer that is greater than or equal to the supplied number. +The `CEILING()` function in SQL returns the smallest integer greater than or equal to a given numeric value. It's useful when you need to round up a number to the nearest whole number, regardless of whether the number is already an integer or a decimal. For example, `CEILING(4.2)` would return `5`, and `CEILING(-4.7)` would return `-4`. This function is commonly used in scenarios where rounding up is necessary, such as calculating the number of pages needed to display a certain number of items when each page has a fixed capacity. -The syntax for using the `CEILING` function is: +Learn more from the following resources: -```sql -CEILING (numeric_expression) -``` - -The `numeric_expression` is an expression of the exact numeric or approximate numeric data type categories, or types that can be implicitly converted to one of these categories. - -For example, you have a table called 'Products' with a 'Price' column. Here's how you can use the `CEILING` function to round up all the prices to the nearest whole number: - -```sql -SELECT ProductName, Price, CEILING (Price) AS RoundedUpPrice -FROM Products; -``` - -In this example, if the original price was $10.25, the `RoundedUpPrice` will be $11. This is because the `CEILING` function rounds up the 'Price' value to the nearest whole number. - -It's essential to remember that `CEILING` always rounds up. So even if the Price is $10.01, the RoundedUpPrice according to `CEILING` would still be $11. If you want to round to the nearest whole number, you might want to use the `ROUND` function instead. - -Another important note is that the return type of `CEILING` will be of the same type as the provided numeric expression. For instance, if you supply a numeric expression of type decimal, the return type will also be of type decimal. \ No newline at end of file +- [@article@CEILING Function in SQL](https://www.javatpoint.com/ceiling-function-in-sql) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/check@Q0h9Wfnl_W9ThOkv7Q17A.md b/src/data/roadmaps/sql/content/check@Q0h9Wfnl_W9ThOkv7Q17A.md index 008b0d8ba..00d4efea0 100644 --- a/src/data/roadmaps/sql/content/check@Q0h9Wfnl_W9ThOkv7Q17A.md +++ b/src/data/roadmaps/sql/content/check@Q0h9Wfnl_W9ThOkv7Q17A.md @@ -1,64 +1,7 @@ # CHECK -In SQL, `CHECK` is a constraint that limits the value range that can be placed in a column. It enforces domain integrity by limiting the values in a column to meet a certain condition. +A `CHECK` constraint in SQL is used to enforce data integrity by specifying a condition that must be true for each row in a table. It allows you to define custom rules or restrictions on the values that can be inserted or updated in one or more columns. `CHECK` constraints help maintain data quality by preventing invalid or inconsistent data from being added to the database, ensuring that only data meeting specified criteria is accepted. -`CHECK` constraint can be used in a column definition when you create or modify a table. +Learn more from the following resources: -## Syntax - -To use the `CHECK` constraint, you can follow this syntax: - -```sql -CREATE TABLE table_name ( - column1 datatype CONSTRAINT constraint_name CHECK (condition), - column2 datatype, - ... -); -``` - -If you need to apply the `CHECK` constraint on multiple columns, use the following syntax: - -```sql -CREATE TABLE table_name ( - column1 datatype, - column2 datatype, - ..., - CONSTRAINT constraint_name CHECK (condition) -); -``` - -## Examples - -Here is an example of applying a `CHECK` constraint on a single column: - -```sql -CREATE TABLE Employees ( - ID int NOT NULL, - Age int, - Salary int CHECK (Salary>0), -); -``` - -Above SQL statement ensures that the salary of all employees in the Employees table must be more than 0. - -Here is an example of applying a `CHECK` constraint on multiple columns: - -```sql -CREATE TABLE Employees ( - ID int NOT NULL, - Age int, - Salary int, - CONSTRAINT CHK_Person CHECK (Age>=18 AND Salary>=0) -); -``` - -Above SQL ensures that the persons' age must be greater than or equal to 18, and their salary is more than or equal to 0. - -It is also possible to use the `ALTER TABLE` command to add a `CHECK` constraint after the table has been created. - -```sql -ALTER TABLE Employees -ADD CONSTRAINT CHK_EmployeeAge CHECK (Age >= 21 AND Age <= 60); -``` - -Above SQL ensures that the employees' age must be between 21 and 60. \ No newline at end of file +- [@article@CHECK - PostgreSQL](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-check/) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/coalesce@k7lZe4QRt9q4InUImFmvx.md b/src/data/roadmaps/sql/content/coalesce@k7lZe4QRt9q4InUImFmvx.md index dc56261a1..be5fb2207 100644 --- a/src/data/roadmaps/sql/content/coalesce@k7lZe4QRt9q4InUImFmvx.md +++ b/src/data/roadmaps/sql/content/coalesce@k7lZe4QRt9q4InUImFmvx.md @@ -1,28 +1,8 @@ # COALESCE -The `COALESCE` function in SQL is used to manage NULL values in data. It scans from left to right through the arguments and returns the first argument that is not `NULL`. +`COALESCE` is an SQL function that returns the first non-null value in a list of expressions. It's commonly used to handle null values or provide default values in queries. `COALESCE` evaluates its arguments in order and returns the first non-null result, making it useful for data cleaning, report generation, and simplifying complex conditional logic in SQL statements. -Syntax: -```sql -COALESCE(value1,value2,..., valueN) -``` -The `COALESCE` function allows handling the case where you have possible `NULL` values in your data and you want to replace it with some other value. +Learn more from the following resources: -For instance, here is an example of how you might use `COALESCE`: - -```sql -SELECT product_name, COALESCE(price, 0) AS Price -FROM products; -``` -In this example, if the "price" column for a product entry is `NULL`, it will instead return "0". - -Another common use case is using `COALESCE` to find the first non-NULL value in a list: - -```sql -SELECT COALESCE(NULL, NULL, 'third value', 'fourth value'); -``` -In this case, it would return "third value", as that's the first non-NULL value in the list. - -Remember, `COALESCE` does not update the original data. It only returns the first non-NULL value in the runtime. To update any NULL values permanently, you would need to use an `UPDATE` statement. - -The `COALESCE` function in SQL improves the reliability of your queries when null values are involved. Whether it's replacing nulls with default values or finding the earliest valid date, it's a very useful function to grasp. \ No newline at end of file +- [@article@How to use the COALESCE function in SQL](https://learnsql.com/blog/coalesce-function-sql/) +- [@article@COALESCE - PostgreSQL](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-coalesce/) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/column@wmtt-3auWLdQWuVdwZLPd.md b/src/data/roadmaps/sql/content/column@wmtt-3auWLdQWuVdwZLPd.md index 7a6c08b33..7d47be903 100644 --- a/src/data/roadmaps/sql/content/column@wmtt-3auWLdQWuVdwZLPd.md +++ b/src/data/roadmaps/sql/content/column@wmtt-3auWLdQWuVdwZLPd.md @@ -2,38 +2,7 @@ In SQL, columns are used to categorize the data in a table. A column serves as a structure that stores a specific type of data (ints, str, bool, etc.) in a table. Each column in a table is designed with a type, which configures the data that it can hold. Using the right column types and size can help to maintain data integrity and optimize performance. -## **Common SQL Column Types** +Learn more from the following resources: -1. **CHAR(n)** - It is a fixed-length character string that holds `n` characters. The size can be 1 to 255. For example, - ```sql - CREATE TABLE Employee(ID CHAR(25)); - ``` - -2. **VARCHAR(n)** - A variable-length character string up to `n` characters where `n` can be from 1 to 255. For example, - ```sql - CREATE TABLE Employee(ID VARCHAR(100)); - ``` - -3. **INT** - This type is used for integers. For example, - ```sql - CREATE TABLE Customers(Age INT); - ``` - -4. **DECIMAL(p,s)** - This is a decimal type used for precision and scale. `p` represents the total number of digits and `s` for numbers after the decimal. For example, - ```sql - CREATE TABLE Products(Price DECIMAL(5,2)); - ``` - -5. **DATE** - This type is used for date format 'YYYY-MM-DD'. For example, - ```sql - CREATE TABLE Orders(OrderedDate DATE); - ``` - -6. **BOOL** - It stores Boolean data types. It can only take `True` or `False` values. For example, - ```sql - CREATE TABLE Users(IsActive BOOL); - ``` - -In SQL, the column type helps in interpreting what kind of data to store in which column, whether it's number, text, date, or logical data. Remember, a table contains multiple columns and each column should have its unique name. - -When creating a table, you should specify the column names, types, and maximum length of the type [if required]. \ No newline at end of file +- [@article@SQL Column](https://www.w3schools.com/sql/sql_ref_column.asp) +- [@article@Column Types - PostgreSQL](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-data-types/) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/commit@3cMECz5QPVDOFrk5duObs.md b/src/data/roadmaps/sql/content/commit@3cMECz5QPVDOFrk5duObs.md index 5af2c5e7a..ab4f680e2 100644 --- a/src/data/roadmaps/sql/content/commit@3cMECz5QPVDOFrk5duObs.md +++ b/src/data/roadmaps/sql/content/commit@3cMECz5QPVDOFrk5duObs.md @@ -4,36 +4,6 @@ The SQL COMMIT command is used to save all the modifications made by the current After the SQL COMMIT statement is executed, it can not be rolled back, which means you can't undo the operations. COMMIT command is used when the user is satisfied with the changes made in the transaction, and these changes can now be made permanent in the database. -## Syntax: +Learn more from the following resources: -```sql -COMMIT; -``` -In some databases, if AUTOCOMMIT is enabled (which is typically the default setting), then every single SQL statement is treated as a transaction and automatically committed right after it is executed. - -Example: - -Imagine you have a transaction that transfers money from Account A to Account B. The SQL might look something like this: - -```sql -START TRANSACTION; -UPDATE Account SET amount = amount - 2000 WHERE name = 'A'; -UPDATE Account SET amount = amount + 2000 WHERE name = 'B'; -COMMIT; -``` -In this transaction, $2000 is transferred from account 'A' to account 'B'. The COMMIT statement makes these changes permanent in the database. - -However, keep in mind that if there was an error during this transaction (for instance if Account A did not have enough money), you'd want to ROLLBACK the transaction, not COMMIT, to undo any changes made before the error occurred. - -## Syntax with ROLLBACK: - -```sql -START TRANSACTION; -UPDATE Account SET amount = amount - 2000 WHERE name = 'A'; -UPDATE Account SET amount = amount + 2000 WHERE name = 'B'; -IF @@ERROR != 0 - ROLLBACK -ELSE - COMMIT; -``` -Here, if @@ERROR is not 0, the transaction will be rolled back. Otherwise, the transaction will be committed. \ No newline at end of file +- [@article@SQL COMMIT and ROLLBACK](https://www.digitalocean.com/community/tutorials/sql-commit-sql-rollback) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/common-table-expressions@tedQynR0xicVKhuR1oahw.md b/src/data/roadmaps/sql/content/common-table-expressions@tedQynR0xicVKhuR1oahw.md index 7debfca5e..18f08aa92 100644 --- a/src/data/roadmaps/sql/content/common-table-expressions@tedQynR0xicVKhuR1oahw.md +++ b/src/data/roadmaps/sql/content/common-table-expressions@tedQynR0xicVKhuR1oahw.md @@ -1,59 +1,7 @@ # CTEs (Common Table Expressions) -CTEs or Common Table Expressions are a type of temporary result set that are defined within the execution scope of a single SQL statement. They act like a temporary view for a single query, and they are typically used to simplify subqueries and improve readability. +Common Table Expressions (CTEs) in SQL are named temporary result sets that exist within the scope of a single `SELECT`, `INSERT`, `UPDATE`, `DELETE`, or `MERGE` statement. Defined using the `WITH` clause, CTEs act like virtual tables that can be referenced multiple times within a query. They improve query readability, simplify complex queries by breaking them into manageable parts, and allow for recursive queries. CTEs are particularly useful for hierarchical or graph-like data structures and can enhance query performance in some database systems. -## Syntax +Learn more from the following resources: -Here is the basic syntax of how to use a CTE in SQL: - -```sql -WITH CTE_Name AS -( - SQL Query -) -SELECT * FROM CTE_Name -``` - -In this syntax, the "WITH" keyword is used to create a CTE. The SQL query inside the parentheses is the query that creates the CTE. The final SELECT statement is used to query the data from the CTE. - -## Basic Usage - -An example of how to use a CTE is demonstrated below: - -```sql -WITH Sales_CTE (SalesPersonID, NumberOfOrders) -AS -( - SELECT SalesPersonID, COUNT(OrderID) - FROM SalesOrderHeader - GROUP BY SalesPersonID -) -SELECT E.EmployeeID, E.FirstName, E.LastName, S.NumberOfOrders -FROM Employee E -JOIN Sales_CTE S -ON E.EmployeeID = S.SalesPersonID -ORDER BY S.NumberOfOrders DESC; -``` - -In this example, the CTE groups sales data by `SalesPersonID` and then joins this with the `Employee` table based on the `EmployeeID` to get the corresponding employee details. - -## Recursive CTEs - -SQL also supports recursive CTEs, which are CTEs that reference themselves. Recursive CTEs are generally used to solve problems that require iteration, such as traversing hierarchies. Here's an example: - -```sql -WITH Recursive_CTE AS -( - SELECT EmployeeID, ManagerID, FirstName - FROM Employee - WHERE ManagerID IS NULL - UNION ALL - SELECT E.EmployeeID, E.ManagerID, E.FirstName - FROM Employee E - INNER JOIN Recursive_CTE RCTE - ON E.ManagerID = RCTE.EmployeeID -) -SELECT * FROM Recursive_CTE; -``` - -In the example above, the CTE starts with the employees who have no manager (`ManagerID IS NULL`). Then it recursively adds employees who are managed by the employees already in the CTE. The result is a list of all employees in the company, hierarchically organized by manager. \ No newline at end of file +- [@article@Common Table Expressions (CTEs)](https://hightouch.com/sql-dictionary/sql-common-table-expression-cte) diff --git a/src/data/roadmaps/sql/content/concat@5inpEqafeVCfqsURHzQQg.md b/src/data/roadmaps/sql/content/concat@5inpEqafeVCfqsURHzQQg.md index c8194fa0c..d720a0a6d 100644 --- a/src/data/roadmaps/sql/content/concat@5inpEqafeVCfqsURHzQQg.md +++ b/src/data/roadmaps/sql/content/concat@5inpEqafeVCfqsURHzQQg.md @@ -1,41 +1,7 @@ # CONCAT -`CONCAT` is a SQL function that allows you to concatenate, or join, two or more strings together. This is extremely useful whenever you need to combine text from multiple columns into a single column. +`CONCAT` is an SQL function used to combine two or more strings into a single string. It takes multiple input strings as arguments and returns a new string that is the concatenation of all the input strings in the order they were provided. `CONCAT` is commonly used in `SELECT` statements to merge data from multiple columns, create custom output formats, or generate dynamic SQL statements. -The syntax for the `CONCAT` function is quite simple: +Learn more from the following resources: -```sql -CONCAT(string1, string2, ..., string_n) -``` - -This function accepts as input any number of string arguments, from two to as many as needed, and returns a new string which is the result of all the input strings joined together. The strings are concatenated in the order in which they are passed to the function. - -Here's a simple example: - -```sql -SELECT CONCAT('Hello', ' ', 'World'); -``` - -This will return the string: - -``` -'Hello World' -``` - -You can also use `CONCAT` with columns from a table: - -```sql -SELECT CONCAT(first_name, ' ', last_name) AS full_name -FROM employees; -``` - -The above query will return a new column `full_name` which is the result of `first_name` and `last_name` with a space in between. If `first_name` is 'John' and `last_name` is 'Doe', the returned full name would be 'John Doe'. - -However, keep in mind that `CONCAT` will return `NULL` if any of the input strings is `NULL`. To avoid this, you can use the `CONCAT_WS` function which accepts a separator as the first argument and then a list of strings to concatenate. - -```sql -SELECT CONCAT_WS(' ', first_name, last_name) AS full_name -FROM employees; -``` - -The `CONCAT_WS` function will ignore any `NULL` values, only joining the non-NULL values with the provided separator. Hence, 'John NULL' would become just 'John'. +- [@article@An overview of the CONCAT function in SQL](https://www.sqlshack.com/an-overview-of-the-concat-function-in-sql-with-examples/) diff --git a/src/data/roadmaps/sql/content/correlated-subqueries@JZqS3Xapw6mfSPVgFW7av.md b/src/data/roadmaps/sql/content/correlated-subqueries@JZqS3Xapw6mfSPVgFW7av.md index acf9a51cc..78a878bac 100644 --- a/src/data/roadmaps/sql/content/correlated-subqueries@JZqS3Xapw6mfSPVgFW7av.md +++ b/src/data/roadmaps/sql/content/correlated-subqueries@JZqS3Xapw6mfSPVgFW7av.md @@ -1,33 +1,7 @@ # Correlated Subqueries -In SQL, a correlated subquery is a subquery that uses values from the outer query in its WHERE clause. The correlated subquery is evaluated once for each row processed by the outer query. It exists because it depends on the outer query and it cannot execute independently of the outer query because the subquery is correlated with the outer query as it uses its column in its WHERE clause. +In SQL, a correlated subquery is a subquery that uses values from the outer query in its `WHERE` clause. The correlated subquery is evaluated once for each row processed by the outer query. It exists because it depends on the outer query and it cannot execute independently of the outer query because the subquery is correlated with the outer query as it uses its column in its `WHERE` clause. -## Syntax: +Learn more from the following resources: -```sql -SELECT column_name [, column_name...] -FROM table1 [, table2...] -WHERE column_name OPERATOR - (SELECT column_name [, column_name...] - FROM table_name - WHERE condition [table1.column_name = table2.column_name...]); -``` - -## Code Example - -For instance, if you want to get the employees whose salaries are above their department's average salaries, it can be queried with a correlated subquery as follows: - -```sql -SELECT e1.employee_name, e1.salary -FROM employee e1 -WHERE salary > - (SELECT AVG(salary) - FROM employee e2 - WHERE e1.department = e2.department); -``` - -In the example above, the correlated subquery (the inner query) calculates the average salary for each department. The outer query then compares the salary of each employee to the average salary of their respective department. It returns the employees whose salaries are above their department's average. The correlated subquery is executed once for each row selected by the outer query. - -Also note that `e1` and `e2` are the aliases of the `employee` table so that we can use it in both the inner query and outer query. Here, `e2.department` in the inner query comes from the outer query's `e1.department`. - -Thus, a correlated subquery is a subquery that depends on the outer SQL query for its values. This means that the subquery is run once for every Row in the outer query, often resulting in quite a bit of processing, and thus slower results. \ No newline at end of file +- [@official@Correlated Subqueries](https://dev.mysql.com/doc/refman/8.4/en/correlated-subqueries.html) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/count@9aHYrOQDkA84tlxcVK5aD.md b/src/data/roadmaps/sql/content/count@9aHYrOQDkA84tlxcVK5aD.md index b6188d7b7..45e58c00f 100644 --- a/src/data/roadmaps/sql/content/count@9aHYrOQDkA84tlxcVK5aD.md +++ b/src/data/roadmaps/sql/content/count@9aHYrOQDkA84tlxcVK5aD.md @@ -1,29 +1,7 @@ # COUNT -`COUNT` is a SQL function that returns the number of rows that match a specified criteria. Essentially, `COUNT` function is used when you need to know the count of a record in a certain table's column. +`COUNT` is an SQL aggregate function that returns the number of rows that match the specified criteria. It can be used to count all rows in a table, non-null values in a specific column, or rows that meet certain conditions when combined with a `WHERE` clause. `COUNT` is often used in data analysis, reporting, and performance optimization queries to determine the size of datasets or the frequency of particular values. -There are two types of count function; `COUNT(*)` and `COUNT(column)`. +Learn more from the following resources: -- `COUNT(*)` counts all the rows in the target table whether columns contain null values or not. - -```sql -SELECT COUNT(*) FROM table_name; -``` - -- `COUNT(column)` counts the rows in the column of a table excluding null. - -```sql -SELECT COUNT(column_name) FROM table_name; -``` - -You may also use `COUNT()` in conjunction with `GROUP BY` to return the count of rows within each group. - -A typical example would be: - -```sql -SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name; -``` - -Here, `column_name` is the name of the column based on which the rows will be grouped. This query will return the count of rows in each group of `column_name`. - -By understanding how to use the `COUNT()` function, you can extract more meaningful data from your tables, and perform analytics and generate reports based on the counts of certain attributes in your database. +- [@article@COUNT](https://www.w3schools.com/sql/sql_count.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/create-table@epEpBxRosLhuAuKwp823r.md b/src/data/roadmaps/sql/content/create-table@epEpBxRosLhuAuKwp823r.md index 90f70539a..392d08541 100644 --- a/src/data/roadmaps/sql/content/create-table@epEpBxRosLhuAuKwp823r.md +++ b/src/data/roadmaps/sql/content/create-table@epEpBxRosLhuAuKwp823r.md @@ -1,52 +1,7 @@ # Create Table -The `CREATE TABLE` statement in SQL is a Data Definition Language (DDL) command used to create a new table in the database. +`CREATE TABLE` is an SQL statement used to define and create a new table in a database. It specifies the table name, column names, data types, and optional constraints such as primary keys, foreign keys, and default values. This statement establishes the structure of the table, defining how data will be stored and organized within it. `CREATE TABLE` is a fundamental command in database management, essential for setting up the schema of a database and preparing it to store data. -## SQL CREATE TABLE Syntax +Learn more from the following resources: -The syntax for SQL `CREATE TABLE` is as follows: - -```sql -CREATE TABLE table_name ( - column1 datatype, - column2 datatype, - column3 datatype, - .... -); -``` - -- `table_name` is the name of the table that you want to create. -- `column1, column2,...` are the columns in the table. -- `datatype` is the data type for the column, such as varchar, int, date, etc. - -## SQL CREATE TABLE Example - -Here is an example of the `CREATE TABLE` statement: - -```sql -CREATE TABLE Employees ( - ID int, - Name varchar(255), - Salary int, - Department varchar(255), - Position varchar(255) -); -``` - -This SQL command creates a new table named `Employees` with five columns, named 'ID', 'Name', 'Salary', 'Department', and 'Position'. The data types are int for the 'ID' and 'Salary', and varchar(255) for the others. - -## SQL CREATE TABLE with NOT NULL - -The `NOT NULL` constraint enforces a column to not accept null values. When creating a new table, you can add this constraint. Here is a practical example: - -```sql -CREATE TABLE Employees ( - ID int NOT NULL, - Name varchar(255) NOT NULL, - Salary int, - Department varchar(255), - Position varchar(255) -); -``` - -In the example above, the 'ID' and 'Name' must always have a value. They cannot be unassigned or undefined. \ No newline at end of file +- [@article@CREATE TABLE](https://www.tutorialspoint.com/sql/sql-create-table.htm) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/creating-views@PcsGK4VBh0zNQIPZvNES4.md b/src/data/roadmaps/sql/content/creating-views@PcsGK4VBh0zNQIPZvNES4.md index 7af9de131..c0bd413a6 100644 --- a/src/data/roadmaps/sql/content/creating-views@PcsGK4VBh0zNQIPZvNES4.md +++ b/src/data/roadmaps/sql/content/creating-views@PcsGK4VBh0zNQIPZvNES4.md @@ -1,52 +1,8 @@ # Creating Views -In SQL, creating views can be achieved through the `CREATE VIEW` statement. A view is a virtual table based on the result-set of an SQL statement. It contains rows and columns from one or more tables. The syntax for the `CREATE VIEW` statement is: +Creating views in SQL involves using the `CREATE VIEW` statement to define a virtual table based on the result of a `SELECT` query. Views don't store data themselves but provide a way to present data from one or more tables in a specific format. They can simplify complex queries, enhance data security by restricting access to underlying tables, and provide a consistent interface for querying frequently used data combinations. Views can be queried like regular tables and are often used to encapsulate business logic or present data in a more user-friendly manner. -```sql -CREATE VIEW view_name AS -SELECT column1, column2, ... -FROM table_name -WHERE condition; -``` +Learn more from the following resources: -Here: -- `CREATE VIEW view_name` : It creates a new view that you define with `view_name`. -- `AS SELECT column1, column2 ...` : These are the columns you want in your view. You can choose one or more columns from one or more tables. -- `FROM table_name` : `table_name` is the name of the table from which you want to create the view. -- `WHERE` : It is an optional clause that you can use to specify conditions for displaying records. - -**Example:** - -Let's say you have a table named `Employees` having following data: - -| ID | NAME | SALARY | DEPARTMENT_ID | -|----|-------|--------|---------------| -| 1 | John | 3000 | 2 | -| 2 | Sue | 3500 | 3 | -| 3 | Phil | 4500 | 2 | -| 4 | Anna | 5000 | 1 | - -You can create a view that shows only the employees from department 2: - -```sql -CREATE VIEW Department2 AS -SELECT Name, Salary -FROM Employees -WHERE Department_ID = 2; -``` - -After running this statement, `Department2` will be a saved view in your database, and you can query it like you would with a standard table: - -```sql -SELECT * -FROM Department2; -``` - -This would bring up - -| NAME | SALARY | -|------|--------| -| John | 3000 | -| Phil | 4500 | - -In total, the `CREATE VIEW` statement is a useful command when you want to save a particular query and its result set for future use. This can simplify complex queries by breaking them up into manageable parts. \ No newline at end of file +- [@article@How to create a view in SQL](https://www.sqlshack.com/how-to-create-a-view-in-sql-server/) +- [@video@SQL Views in 4 minutes](https://www.youtube.com/watch?v=vLLkNI-vkV8) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/cross-join@7ow6tiSSCnTpv_GYQU017.md b/src/data/roadmaps/sql/content/cross-join@7ow6tiSSCnTpv_GYQU017.md index 722523e81..80895fd11 100644 --- a/src/data/roadmaps/sql/content/cross-join@7ow6tiSSCnTpv_GYQU017.md +++ b/src/data/roadmaps/sql/content/cross-join@7ow6tiSSCnTpv_GYQU017.md @@ -4,34 +4,6 @@ The cross join in SQL is used to combine every row of the first table with every The issue with cross join is it returns the Cartesian product of the two tables, which can result in large numbers of rows and heavy resource usage. It's hence critical to use them wisely and only when necessary. -## Syntax +Learn more from the following resources: -Here's the generic syntax for implementing a CROSS JOIN: - -```sql -SELECT column_name(s) -FROM table1 -CROSS JOIN table2; -``` - -You can alternatively use the below syntax to achieve the same result: - -```sql -SELECT column_name(s) -FROM table1, table2; -``` -Both syntax return the Cartesian product of `table1` and `table2`. - -## Example of CROSS JOIN - -Let's consider two tables, `Employees` and `Departments`, where `Employees` has columns `EmpID, EmpName, DeptID` and `Departments` has columns `DeptID, DeptName`. - -A cross join query would look like this: - -```sql -SELECT Employees.EmpName, Departments.DeptName -FROM Employees -CROSS JOIN Departments; -``` - -This statement will return a result set which is the combination of each row from `Employees` with each row from `Departments`. +- [@article@CROSS JOIN](https://www.w3schools.com/mysql/mysql_join_cross.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/data-constraints@qBios3sZVhcJMpXmj9f7B.md b/src/data/roadmaps/sql/content/data-constraints@qBios3sZVhcJMpXmj9f7B.md index 55f812ea8..83b4efa82 100644 --- a/src/data/roadmaps/sql/content/data-constraints@qBios3sZVhcJMpXmj9f7B.md +++ b/src/data/roadmaps/sql/content/data-constraints@qBios3sZVhcJMpXmj9f7B.md @@ -1,93 +1,7 @@ # Data Constraints -Data constraints in SQL are used to specify rules for the data in a table. Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the table. +Data constraints in SQL are rules applied to columns or tables to enforce data integrity and consistency. They include primary key, foreign key, unique, check, and not null constraints. These constraints define limitations on the data that can be inserted, updated, or deleted in a database, ensuring that the data meets specific criteria and maintains relationships between tables. By implementing data constraints, database designers can prevent invalid data entry, maintain referential integrity, and enforce business rules directly at the database level. -## Types of SQL Data Constraints +Learn more from the following resources: -1. **NOT NULL Constraint**: Ensures that a column cannot have a NULL value. - - For Example: - - ```sql - CREATE TABLE Students ( - ID int NOT NULL, - Name varchar(255) NOT NULL, - Age int - ); - ``` - -2. **UNIQUE Constraint**: Ensures that all values in a column are different. - - For Example: - - ```sql - CREATE TABLE Students ( - ID int NOT NULL UNIQUE, - Name varchar(255) NOT NULL, - Age int - ); - ``` - -3. **PRIMARY KEY Constraint**: Uniquely identifies each record in a database table. Primary keys must contain UNIQUE values. Exactly the same as the UNIQUE constraint but there can be many unique constraints in a table, but only one PRIMARY KEY constraint per table. - - For Example: - - ```sql - CREATE TABLE Students ( - ID int NOT NULL, - Name varchar(255) NOT NULL, - Age int, - PRIMARY KEY (ID) - ); - ``` - -4. **FOREIGN KEY Constraint**: Prevents actions that would destroy links between tables. A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table. - - For Example: - - ```sql - CREATE TABLE Orders ( - OrderID int NOT NULL, - OrderNumber int NOT NULL, - ID int, - PRIMARY KEY (OrderID), - FOREIGN KEY (ID) REFERENCES Students(ID) - ); - ``` - -5. **CHECK Constraint**: The CHECK constraint ensures that all values in a column satisfies certain conditions. - - For Example: - - ```sql - CREATE TABLE Students ( - ID int NOT NULL, - Name varchar(255) NOT NULL, - Age int, - CHECK (Age>=18) - ); - ``` - -6. **DEFAULT Constraint**: Provides a default value for a column when none is specified. - - For Example: - - ```sql - CREATE TABLE Students ( - ID int NOT NULL, - Name varchar(255) NOT NULL, - Age int, - City varchar(255) DEFAULT 'Unknown' - ); - ``` - -7. **INDEX Constraint**: Used to create and retrieve data from the database very quickly. - - For Example: - - ```sql - CREATE INDEX idx_name - ON Students (Name); - ``` - - Note: Indexes are not a part of the SQL standard and are not supported by all databases. +- [@article@Data Constraints](https://www.w3schools.com/sql/sql_constraints.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/data-definition-language-ddl@xPOeXK1EPBNG56vgfG-VV.md b/src/data/roadmaps/sql/content/data-definition-language-ddl@xPOeXK1EPBNG56vgfG-VV.md index ff56b04ff..724d94d7b 100644 --- a/src/data/roadmaps/sql/content/data-definition-language-ddl@xPOeXK1EPBNG56vgfG-VV.md +++ b/src/data/roadmaps/sql/content/data-definition-language-ddl@xPOeXK1EPBNG56vgfG-VV.md @@ -1,49 +1,7 @@ # Data Definition Language (DDL) -Data Definition Language (DDL) is a subset of SQL. Its primary function is to create, modify, and delete database structures but not data. The commands in DDL are: +Data Definition Language (DDL) is a subset of SQL used to define and manage the structure of database objects. DDL commands include `CREATE`, `ALTER`, `DROP`, and `TRUNCATE`, which are used to create, modify, delete, and empty database structures such as tables, indexes, views, and schemas. These commands allow database administrators and developers to define the database schema, set up relationships between tables, and manage the overall structure of the database. DDL statements typically result in immediate changes to the database structure and can affect existing data. -1. `CREATE`: This command is used to create the database or its objects (like table, index, function, views, store procedure, and triggers). +Learn more from the following resources: - ```sql - CREATE TABLE table_name ( - column1 data_type(size), - column2 data_type(size), - ... - ); - ``` - -2. `DROP`: This command is used to delete an existing database or table. - - ```sql - DROP TABLE table_name; - ``` - -3. `ALTER`: This is used to alter the structure of the database. It is used to add, delete/drop or modify columns in an existing table. - - ```sql - ALTER TABLE table_name ADD column_name datatype; - ALTER TABLE table_name DROP COLUMN column_name; - ALTER TABLE table_name MODIFY COLUMN column_name datatype(size); - ``` - -4. `TRUNCATE`: This is used to remove all records from a table, including all spaces allocated for the records which are removed. - - ```sql - TRUNCATE TABLE table_name; - ``` - -5. `RENAME`: This is used to rename an object in the database. - - ```sql - -- To rename a table - ALTER TABLE table_name - RENAME TO new_table_name; - - -- To rename a column - ALTER TABLE table_name - RENAME COLUMN old_column_name TO new_column_name; - ``` - -Remember: In DDL operations, `COMMIT` and `ROLLBACK` statement cannot be performed because the MySQL engine automatically commits the changes. - -Remember to replace `table_name`, `column_name`, `datatype(size)`, `old_table_name`, and `new_table_name` in the examples above with your actual table names, column names, data types and sizes, and the old or new table names you want to specify. +- [@article@Data Definition Language (DDL)](https://docs.getdbt.com/terms/ddl) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/data-integrity--security@R1ktDJpXOz0PTllAcBrdu.md b/src/data/roadmaps/sql/content/data-integrity--security@R1ktDJpXOz0PTllAcBrdu.md index cd500cc11..6a346732a 100644 --- a/src/data/roadmaps/sql/content/data-integrity--security@R1ktDJpXOz0PTllAcBrdu.md +++ b/src/data/roadmaps/sql/content/data-integrity--security@R1ktDJpXOz0PTllAcBrdu.md @@ -1,54 +1,5 @@ # Data Integrity and Security -Integrity Security in SQL refers to the accuracy and consistency of the data in a database. It is a crucial aspect of the database that ensures the data being entered into databases follows the defined rules, preventing any damage to the main data. It comes in several forms: +Data integrity and security in SQL encompass measures and techniques to ensure data accuracy, consistency, and protection within a database. This includes implementing constraints (like primary keys and foreign keys), using transactions to maintain data consistency, setting up user authentication and authorization, encrypting sensitive data, and regularly backing up the database. -**1. Entity Integrity** - -Entity integrity ensures that there are no duplicate rows in a table. This is often managed with the help of the primary key. - -For example, consider the following SQL command to create a table. Primary Key on the EmployeeID column will ensure that every entry in this column is unique. - -```sql -CREATE TABLE Employee ( - EmployeeID int NOT NULL, - LastName varchar(255), - FirstName varchar(255), - Age int, - PRIMARY KEY (EmployeeID) -); -``` - -**2. Domain Integrity** - -Domain Integrity enforces valid entries for a given column by restricting the type, the format, or the range of possible values. - -For example, setting a specific data type and size for a column. - -```sql -CREATE TABLE Employee ( - EmployeeID int NOT NULL, - LastName varchar(50), - FirstName varchar(50), - Age int CHECK (Age>=18 and Age<=60) -); -``` - -**3. Referential Integrity** - -Referential integrity ensures that relationships between tables remain consistent. More specifically, that a foreign key in one table must always refer to the primary key in another table. - -```sql -CREATE TABLE Orders ( - OrderID int NOT NULL, - OrderNumber int NOT NULL, - EmployeeID int, - PRIMARY KEY (OrderID), - FOREIGN KEY (EmployeeID) REFERENCES Employee(EmployeeID) -); -``` -**4. User-Defined Integrity** - -User-defined integrity refers to a set of rules specified by a user, which do not belong to the entity, domain, or referential integrity. -For example, a user might define a rule that an employee's hire date must be less than 3 months in the future. - -Please note that SQL doesn't provide specific built-in functionalities to handle user-defined integrity, it depends on the code logic implemented by each application. +SQL provides various tools and commands to enforce data integrity rules, control access to data, and protect against unauthorized access or data corruption, ensuring the reliability and confidentiality of stored information. \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/data-integrity-constraints@mBQ3Z8GlFcpIena3IB7D_.md b/src/data/roadmaps/sql/content/data-integrity-constraints@mBQ3Z8GlFcpIena3IB7D_.md index 0149de1ce..2b8f22e45 100644 --- a/src/data/roadmaps/sql/content/data-integrity-constraints@mBQ3Z8GlFcpIena3IB7D_.md +++ b/src/data/roadmaps/sql/content/data-integrity-constraints@mBQ3Z8GlFcpIena3IB7D_.md @@ -2,82 +2,8 @@ SQL constraints are used to specify rules for the data in a table. They ensure the accuracy and reliability of the data within the table. If there is any violation between the constraint and the action, the action is aborted by the constraint. -Constraints are classified into two types: column level and table level. Column level constraints apply to individual columns whereas table level constraints apply to the entire table. +Constraints are classified into two types: column level and table level. Column level constraints apply to individual columns whereas table level constraints apply to the entire table. Each constraint has its own purpose and usage, utilizing them effectively helps maintain the accuracy and integrity of the data. -Here are the commonly used constraints: +Learn more from the following resources: -## 1. NOT NULL - -The `NOT NULL` constraint enforces a field to always contain a value. This means that you cannot insert a new record or update a record without adding a value to this field. - -**Example:** - -```sql -CREATE TABLE Employees ( - ID int NOT NULL, - Name varchar(255) NOT NULL, - Age int -); -``` - -## 2. UNIQUE - -The `UNIQUE` constraint ensures that all values in a column are different, thus, prevents duplicate values in a column. - -**Example:** - -```sql -CREATE TABLE Employees ( - ID int NOT NULL UNIQUE, - Name varchar(255) NOT NULL, - Age int -); -``` - -## 3. PRIMARY KEY - -The `PRIMARY KEY` constraint uniquely identifies each record in a database table. This constraint provides uniqueness for the column or set of columns, and not null. - -**Example:** - -```sql -CREATE TABLE Employees ( - ID int NOT NULL, - Name varchar(255) NOT NULL, - Age int, - PRIMARY KEY (ID) -); -``` - -## 4. FOREIGN KEY - -The `FOREIGN KEY` constraint prevents actions that would destroy links between tables. It maintains referential integrity by requiring that a value inserted into a foreign key column exists in the referenced primary key. - -**Example:** - -```sql -CREATE TABLE Orders ( - OrderID int NOT NULL, - OrderNumber int NOT NULL, - EmployeeID int, - PRIMARY KEY (OrderID), - FOREIGN KEY (EmployeeID) REFERENCES Employees(ID) -); -``` - -## 5. CHECK - -The `CHECK` constraint ensures that all values in a field satisfy a condition. It enables a condition to check the value being entered into a record. - -**Example:** - -```sql -CREATE TABLE Employees ( - ID int NOT NULL, - Name varchar(255) NOT NULL, - Age int, - CHECK (Age>=18) -); -``` - -Each constraint has its own purpose and usage, utilizing them effectively helps maintain the accuracy and integrity of the data. \ No newline at end of file +- [@article@Integrity Constraints in SQL: A Guide With Examples](https://www.datacamp.com/tutorial/integrity-constraints-sql) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/data-manipulation-language-dml@WMSXi-eez_hHGDM8kUdWz.md b/src/data/roadmaps/sql/content/data-manipulation-language-dml@WMSXi-eez_hHGDM8kUdWz.md index ad68436ca..c5138ceda 100644 --- a/src/data/roadmaps/sql/content/data-manipulation-language-dml@WMSXi-eez_hHGDM8kUdWz.md +++ b/src/data/roadmaps/sql/content/data-manipulation-language-dml@WMSXi-eez_hHGDM8kUdWz.md @@ -1,41 +1,3 @@ # Data Manipulation Language (DML) -*DML* is a subcategory of `SQL` which stands for _Data Manipulation Language_. The purpose of DML is to insert, retrieve, update and delete data from the database. With this, we can perform operations on existing records. - -DML contains four commands which are: - -1. **INSERT INTO** - This command is used to insert new rows (records) into a table. - -Example: - -```sql -INSERT INTO table_name ( column1, column2, column3, ... ) -VALUES ( value1, value2, value3, ... ) -``` - -2. **SELECT** - This command is used to select data from a database. The data returned is stored in a result table, called the result-set. - -Example: - -```sql -SELECT column1, column2, ... -FROM table_name -``` - -3. **UPDATE** - This command is used to modify the existing rows in a table. - -Example: - -```sql -UPDATE table_name -SET column1 = value1, column2 = value2, ... -WHERE condition; -``` - -4. **DELETE FROM** - This command is used to delete existing rows (records) from a table. - -Example: - -```sql -DELETE FROM table_name WHERE condition; -``` \ No newline at end of file +Data Manipulation Language (DML) is a subset of SQL used to manage data within database objects. It includes commands like `SELECT`, `INSERT`, `UPDATE`, and `DELETE`, which allow users to retrieve, add, modify, and remove data from tables. DML statements operate on the data itself rather than the database structure, enabling users to interact with the stored information. These commands are essential for day-to-day database operations, data analysis, and maintaining the accuracy and relevance of the data within a database system. \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/data-types@tBzMDfCMh6MIagNaxCzin.md b/src/data/roadmaps/sql/content/data-types@tBzMDfCMh6MIagNaxCzin.md index 8356bc5b0..351e22d53 100644 --- a/src/data/roadmaps/sql/content/data-types@tBzMDfCMh6MIagNaxCzin.md +++ b/src/data/roadmaps/sql/content/data-types@tBzMDfCMh6MIagNaxCzin.md @@ -1,82 +1,7 @@ # Data Types -SQL data types define the type of data that can be stored in a database table's column. Depending on the DBMS, the names -of the data types can differ slightly. Here are the general types: +SQL data types define the kind of values that can be stored in a column and determine how the data is stored, processed, and retrieved. Common data types include numeric types (`INTEGER`, `DECIMAL`), character types (`CHAR`, `VARCHAR`), date and time types (`DATE`, `TIMESTAMP`), binary types (`BLOB`), and boolean types. Each database management system may have its own specific set of data types with slight variations. Choosing the appropriate data type for each column is crucial for optimizing storage, ensuring data integrity, and improving query performance. -## INT +Learn more from the following resources: -`INT` is used for whole numbers. For example: - -```sql -CREATE TABLE Employees ( - ID INT, - Name VARCHAR(30) -); -``` - -## DECIMAL - -`DECIMAL` is used for decimal and fractional numbers. For example: - -```sql -CREATE TABLE Items ( - ID INT, - Price DECIMAL(5,2) -); -``` - -## CHAR - -`CHAR` is used for fixed-length strings. For example: - -```sql -CREATE TABLE Employees ( - ID INT, - Initial CHAR(1) -); -``` - -## VARCHAR - -`VARCHAR` is used for variable-length strings. For example: - -```sql -CREATE TABLE Employees ( - ID INT, - Name VARCHAR(30) -); -``` - -## DATE - -`DATE` is used for dates in the format (`YYYY-MM-DD`). - -```sql -CREATE TABLE Employees ( - ID INT, - BirthDate DATE -); -``` - -## DATETIME - -`DATETIME` is used for date and time values in the format (`YYYY-MM-DD HH:MI:SS`). - -```sql -CREATE TABLE Orders ( - ID INT, - OrderDate DATETIME -); -``` - -## BINARY - -`BINARY` is used for binary strings. - -## BOOLEAN - -`BOOLEAN` is used for boolean values (`TRUE` or `FALSE`). - -**Remember**, the specific syntax for creating tables and defining column data types can vary slightly depending upon -the SQL database you are using (MySQL, PostgreSQL, SQL Server, SQLite, Oracle, etc.), but the general concept and -organization of data types is cross-platform. +- [@article@SQL Data Types](https://www.digitalocean.com/community/tutorials/sql-data-types) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/date@Ivqo2wa-_NhGU3vGd0pUI.md b/src/data/roadmaps/sql/content/date@Ivqo2wa-_NhGU3vGd0pUI.md index 278272dc6..4fda764f2 100644 --- a/src/data/roadmaps/sql/content/date@Ivqo2wa-_NhGU3vGd0pUI.md +++ b/src/data/roadmaps/sql/content/date@Ivqo2wa-_NhGU3vGd0pUI.md @@ -1,76 +1,7 @@ # DATE -In SQL, DATE is a data type that stores the date. It does not store time information. The format of the date is, 'YYYY-MM-DD'. For instance, '2022-01-01'. SQL provides several functions to handle and manipulate dates. +The DATE data type in SQL is used to store calendar dates (typically in the format YYYY-MM-DD). It represents a specific day without any time information. DATE columns are commonly used for storing birthdates, event dates, or any other data that requires only day-level precision. SQL provides various functions to manipulate and format DATE values, allowing for date arithmetic, extraction of date components, and comparison between dates. The exact range of valid dates may vary depending on the specific database management system being used. -Below are some common examples of how to use the DATE data type in SQL: +Learn more from the following resources: -## Create a table with DATE data type - -```sql -CREATE TABLE Orders ( - OrderId int, - ProductName varchar(255), - OrderDate date -); -``` - -In this example, the OrderDate column uses the DATE data type to store the date of the order. - -## Insert a date value into a table - -```sql -INSERT INTO Orders (OrderId, ProductName, OrderDate) -VALUES (1, 'Product 1', '2022-01-01'); -``` - -This command inserts a new row into the Orders table with a date. - -## Retrieve data with a specific date - -```sql -SELECT * FROM Orders -WHERE OrderDate = '2022-01-01'; -``` - -This command retrieves all orders made on January 1, 2022. - -## Update a date value in a table - -```sql -UPDATE Orders -SET OrderDate = '2022-01-02' -WHERE OrderId = 1; -``` - -This command updates the date from January 1, 2022 to January 2, 2022, for the order with the order ID 1. - -## SQL Date Functions - -SQL also provides several built-in functions to work with the DATE data type: - -## CURRENT_DATE - -Returns the current date. - -```sql -SELECT CURRENT_DATE; -``` - -## DATEADD - -Add or subtract a specified time interval from a date. - -```sql -SELECT DATEADD(day, 5, OrderDate) AS "Due Date" -FROM Orders; -``` -In this example, we are adding 5 days to each OrderDate in the table Orders. - -## DATEDIFF - -Get the difference between two dates. - -```sql -SELECT DATEDIFF(day, '2022-01-01', '2022-01-06') AS "Difference"; -``` -It will return 5, that is the difference in days between the two dates. \ No newline at end of file +- [@article@SQL DATE](https://www.w3schools.com/sql/sql_dates.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/dateadd@1E1WdWOyqxbbdiIbw26dZ.md b/src/data/roadmaps/sql/content/dateadd@1E1WdWOyqxbbdiIbw26dZ.md index a2b7e7072..aa75c0ac8 100644 --- a/src/data/roadmaps/sql/content/dateadd@1E1WdWOyqxbbdiIbw26dZ.md +++ b/src/data/roadmaps/sql/content/dateadd@1E1WdWOyqxbbdiIbw26dZ.md @@ -1,45 +1,7 @@ # DATEADD -`DATEADD` is a built-in function in SQL that allows you to add or subtract units of time from a specified date. The function takes three parameters: +`DATEADD` is an SQL function used to add or subtract a specified time interval to a date or datetime value. It typically takes three arguments: the interval type (e.g., day, month, year), the number of intervals to add or subtract, and the date to modify. This function is useful for date calculations, such as finding future or past dates, calculating durations, or generating date ranges. The exact syntax and name of this function may vary slightly between different database management systems (e.g., `DATEADD` in SQL Server, `DATE_ADD` in MySQL). -- An interval type (such as day, month, year, hour, minute, second) -- A number (which can be either positive, for future dates, or negative, for past dates) -- A date from which calculation will be based. +Learn more from the following resources: -The usage of this function can be especially useful when you need to perform operations on dates, such as finding a date "n" days before or after a specified date, or getting the first or last day of a month. - -## Syntax - -The generic syntax for `DATEADD` is: - -```sql -DATEADD(interval, number, date) -``` -Here's what each param means: - -- `interval`: The part of date to which an integer value will be added. This could be a year, quarter, month, day, hour, minute, second, millisecond, microsecond, or nanosecond. - -- `number`: The value to add. The value can either be negative to get dates in the past or positive to get dates in the future. - -- `date`: The date or datetime expression to which the interval and number are added. - -For example, if we want to add three days to the date '2022-01-01', we would write: - -```sql -SELECT DATEADD(day, 3, '2022-01-01') as NewDate -``` - -The result would be: `2022-01-04`. - -You can substitute 'day' with any of the accepted interval types to add different units of time. - -## Sample Query - -If you have a table called `Orders` with a `DateTime` field `OrderDate` and you want to find all orders placed in the next seven days, you can use the `DATEADD` function as follows: - -```sql -SELECT * FROM Orders -WHERE OrderDate <= DATEADD(day, 7, GETDATE()) -``` - -This will return all orders from now until a week from now. +- [@article@DATEADD](https://www.mssqltips.com/sqlservertutorial/9380/sql-dateadd-function/) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/datepart@BJ4fQvagTO0B5UtXblyx8.md b/src/data/roadmaps/sql/content/datepart@BJ4fQvagTO0B5UtXblyx8.md index ae625ab75..f42c3d401 100644 --- a/src/data/roadmaps/sql/content/datepart@BJ4fQvagTO0B5UtXblyx8.md +++ b/src/data/roadmaps/sql/content/datepart@BJ4fQvagTO0B5UtXblyx8.md @@ -2,48 +2,6 @@ `DATEPART` is a useful function in SQL that allows you to extract a specific part of a date or time field. You can use it to get the year, quarter, month, day of the year, day, week, weekday, hour, minute, second, or millisecond from any date or time expression. -Here's the basic syntax of `DATEPART`: +Learn more from the following resources: -```sql -DATEPART(datepart, date) -``` - -Here `datepart` is the part of the date that you want to extract, and `date` is the date value from which the part should be extracted. - -Here are some examples: - -1. Extracting the year from a date: - -```sql -SELECT DATEPART(year, '2021-07-14') AS 'Year'; -``` - -In this example, it would return `2021`. - -2. Extracting the month: - -```sql -SELECT DATEPART(month, '2021-07-14') AS 'Month'; -``` - -The result of this command would be `7`. - -3. Extracting the day: - -```sql -SELECT DATEPART(day, '2021-07-14') AS 'Day'; -``` - -This would return `14`. - -4. Extracting the hour, minute, or second from a datetime: - -```sql -SELECT DATEPART(hour, '2021-07-14T13:30:15') AS 'Hour', - DATEPART(minute, '2021-07-14T13:30:15') AS 'Minute', - DATEPART(second, '2021-07-14T13:30:15') AS 'Second'; -``` - -This would return `13`, `30`, and `15` respectively. - -Remember, the `DATEPART` function returns an integer value. It is essential when you want to compare or group by a specific part of a date or time field in SQL. \ No newline at end of file +- [@article@DATEPART](https://www.w3schools.com/sql/func_sqlserver_datepart.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/db-security-best-practices@vhBZqqmUcEon6-Vwvla4q.md b/src/data/roadmaps/sql/content/db-security-best-practices@vhBZqqmUcEon6-Vwvla4q.md index a73c9220b..7f745fa33 100644 --- a/src/data/roadmaps/sql/content/db-security-best-practices@vhBZqqmUcEon6-Vwvla4q.md +++ b/src/data/roadmaps/sql/content/db-security-best-practices@vhBZqqmUcEon6-Vwvla4q.md @@ -42,4 +42,6 @@ Use a vulnerability scanner to assess the security posture of your SQL. SQL injection can be reduced by using parameterized queries or prepared statements. -These practices can significantly improve your SQL security posture. However, remember that security is not a one-time effort, but a continuous process. Regular assessment and necessary updates are key. Remember to keep an eye on security news concerning SQL Server and regularly check for new security risks or vulnerabilities. \ No newline at end of file +Learn more from the following resources: + +- [@article@What is database security?](https://azure.microsoft.com/en-us/resources/cloud-computing-dictionary/what-is-database-security) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/delete@ddtVaA4Ls6qRj-7OtTSIH.md b/src/data/roadmaps/sql/content/delete@ddtVaA4Ls6qRj-7OtTSIH.md deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/data/roadmaps/sql/content/delete@zWnvuHJLHr03PWkrW1wZZ.md b/src/data/roadmaps/sql/content/delete@zWnvuHJLHr03PWkrW1wZZ.md index 731bb9add..e233b06b8 100644 --- a/src/data/roadmaps/sql/content/delete@zWnvuHJLHr03PWkrW1wZZ.md +++ b/src/data/roadmaps/sql/content/delete@zWnvuHJLHr03PWkrW1wZZ.md @@ -1,37 +1,7 @@ # DELETE -The DELETE statement is used to delete existing records in a table. This is a straightforward process, but care must be taken because the DELETE statement is destructive and cannot be undone by default. +DELETE is an SQL statement used to remove one or more rows from a table. It allows you to specify which rows to delete using a WHERE clause, or delete all rows if no condition is provided. DELETE is part of the Data Manipulation Language (DML) and is used for data maintenance, removing outdated or incorrect information, or implementing business logic that requires data removal. When used without a WHERE clause, it empties the entire table while preserving its structure, unlike the TRUNCATE command. -## Syntax +Learn more from the following resources: -The basic syntax of a DELETE query with WHERE clause in SQL is as follows: -```sql -DELETE FROM table_name [WHERE condition] -``` - -- `table_name`: Specifies the table where you want to delete data. -- `WHERE condition`: It is optional. You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records would be deleted. - -## Examples - -1. **DELETE ALL Rows** - -Deletes all rows from a table named 'students'. -```sql -DELETE FROM students; -``` - -2. **DELETE Specified Rows** - -Deletes the student whose student_id is '1001' from the 'students' table. -```sql -DELETE FROM students WHERE student_id = '1001'; -``` - -**Caution:** Be very careful when using the DELETE statement. If you omit the WHERE clause, all records will be deleted! - -## Multi-table deletions - -Some database systems allow for deleting from multiple tables in a single DELETE statement. This is database-specific and beyond the scope of the basic SQL DELETE command. - -Remember, always make sure to have a backup and confirm you're deleting the correct data before running a DELETE command, especially in production environments. \ No newline at end of file +- [@article@DELETE](https://www.w3schools.com/sql/sql_delete.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/dense_rank@QM0ltgPu8lLLYc2MsTLj-.md b/src/data/roadmaps/sql/content/dense_rank@QM0ltgPu8lLLYc2MsTLj-.md index ea5b6fce5..72ebae893 100644 --- a/src/data/roadmaps/sql/content/dense_rank@QM0ltgPu8lLLYc2MsTLj-.md +++ b/src/data/roadmaps/sql/content/dense_rank@QM0ltgPu8lLLYc2MsTLj-.md @@ -2,43 +2,8 @@ `DENSE_RANK` is a window function in SQL that assigns a rank to each row within a window partition, with no gaps in the ranking numbers. -Unlike the `RANK` function, `DENSE_RANK` does not skip any rank (positions in the order). If you have, for example, 1st, 2nd, and 2nd, the next rank listed would be 3rd when using `DENSE_RANK`, whereas it would be 4th using the `RANK` function. +Unlike the `RANK` function, `DENSE_RANK` does not skip any rank (positions in the order). If you have, for example, 1st, 2nd, and 2nd, the next rank listed would be 3rd when using `DENSE_RANK`, whereas it would be 4th using the `RANK` function. The `DENSE_RANK` function operates on a set of rows, called a window, and in that window, values are compared to each other. -The `DENSE_RANK` function operates on a set of rows, called a window, and in that window, values are compared to each other. +Learn more from the following resources: -Here is a general syntax of `DENSE_RANK` function in SQL: -```sql -DENSE_RANK ( ) OVER ( - [ < partition_by_clause > ] - [ < order_by_clause > ] - ) -``` -- `partition_by_clause` - Divides the window into smaller sets or partitions. -- `order_by_clause` - Determines the order of data inside each partition to further work with the ranking functions. - -Let's say you have a table called 'Employees' with the following data: - -| ID | Name | Salary | -|---|---|---| -| 1 | John | 50000 | -| 2 | Mike | 60000 | -| 3 | Mary | 60000 | -| 4 | Alice | 55000 | - -Our task can be to rank these employees based on their salaries. The SQL query will be: - -```sql -SELECT Name, Salary, -DENSE_RANK () OVER (ORDER BY Salary Desc) AS Rank -FROM Employees -``` -When this query is run, the `DENSE_RANK` function will assign a rank to every row, with the highest salary being ranked as 1: - -| Name | Salary | Rank | -|---|---|---| -| Mike | 60000 | 1 | -| Mary | 60000 | 1 | -| Alice | 55000 | 2 | -| John | 50000 | 3 | - -This table clearly shows how the `DENSE_RANK` function provides rank without skipping any rank in case of a tie between the salaries of Mary and Mike. \ No newline at end of file +- [@article@SQL DENSE_RANK](https://www.sqltutorial.org/sql-window-functions/sql-dense_rank/) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/drop-table@YzJ6QmY2arMfRzMAPaI0T.md b/src/data/roadmaps/sql/content/drop-table@YzJ6QmY2arMfRzMAPaI0T.md index a4d0ce01b..571bf834d 100644 --- a/src/data/roadmaps/sql/content/drop-table@YzJ6QmY2arMfRzMAPaI0T.md +++ b/src/data/roadmaps/sql/content/drop-table@YzJ6QmY2arMfRzMAPaI0T.md @@ -4,44 +4,6 @@ The `DROP TABLE` statement is a Data Definition Language (DDL) operation that is When you execute the `DROP TABLE` statement, it eliminates both the table and its data, as well as any associated indexes, constraints, and triggers. Unlike the `TRUNCATE TABLE` statement, which only removes data but keeps the table structure, `DROP TABLE` removes everything associated with the table. -## Syntax +Learn more from the following resources: -In SQL, the `DROP TABLE` statement is quite simple: - -```sql -DROP TABLE table_name; -``` - -In this command, "table_name" refers to the name of the table you wish to remove. - -## Example - -If you have a table named `Orders` and you want to delete the entire table, you would use: - -```sql -DROP TABLE Orders; -``` - -After executing this statement, the `Orders` table would no longer exist in the database. - -## Considerations - -- **Irreversible Action**: Unlike `DELETE` and `TRUNCATE`, once a table is dropped, the action cannot be rolled back. Therefore, it should be used with extreme caution. -- **Cascading Effects**: Dropping a table that is referenced by a foreign key constraint will also drop that foreign key relationship. Similarly, any dependent objects like views, stored procedures, or functions that reference the table might be affected. -- **Permissions**: Ensure you have the appropriate permissions to drop the table. Typically, this requires `DROP` privilege on the table. - -## Limitations - -There are certain conditions and limitations to keep in mind when using `DROP TABLE`: - -- **Foreign Key Constraints**: If the table is referenced by foreign keys from other tables, dropping it might require using `CASCADE` to also drop the dependent foreign keys. -- **Replication**: Tables published using transactional or merge replication should be carefully considered before dropping, as this can impact replication. -- **Dependent Objects**: Dropping a table will invalidate any dependent objects such as views, stored procedures, and functions that reference the table. Ensure these are handled appropriately. - -For example, if a table `Orders` is referenced by a foreign key in another table `OrderDetails`, dropping `Orders` might require: - -```sql -DROP TABLE Orders CASCADE; -``` - -This ensures that any foreign key relationships are also removed along with the table. \ No newline at end of file +- [@article@DROP TABLE](https://www.w3schools.com/sql/sql_drop_table.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/dropping-views@MIOuWWcCjLAmgzog2DBC3.md b/src/data/roadmaps/sql/content/dropping-views@MIOuWWcCjLAmgzog2DBC3.md index ca8454acf..0f9cadc9b 100644 --- a/src/data/roadmaps/sql/content/dropping-views@MIOuWWcCjLAmgzog2DBC3.md +++ b/src/data/roadmaps/sql/content/dropping-views@MIOuWWcCjLAmgzog2DBC3.md @@ -1,31 +1,7 @@ # Dropping Views -"Dropping" in SQL is the process of deleting an existing database object. In the context of views, "dropping" refers to deleting an existing view from the database. Once a view is dropped, it cannot be used any longer until it is recreated with the same or new definition. If you're going to drop a view, ensure it's not being used anywhere in your application or it will lead to errors. +Dropping views in SQL involves using the `DROP VIEW` statement to remove an existing view from the database. This operation permanently deletes the view definition, but it doesn't affect the underlying tables from which the view was created. Dropping a view is typically done when the view is no longer needed, needs to be replaced with a different definition, or as part of database maintenance. It's important to note that dropping a view can impact other database objects or applications that depend on it, so caution should be exercised when performing this operation. -## Dropping Views +Learn more from the following resources: -You can drop a view in SQL using the `DROP VIEW` statement. The `DROP VIEW` statement removes one or more views from the database. You specify the name of the view that you want to remove after the `DROP VIEW` clause. - -Here is the basic syntax to drop an existing view: - -```sql -DROP VIEW view_name; -``` - -To drop multiple views in a single command, you use a list of comma-separated views. - -```sql -DROP VIEW view_name1, view_name2, ..., view_name_n; -``` - -**Note**: Be careful when dropping views. Once a view is dropped, all the permissions granted on it will also be dropped. - -Before dropping a view, you can check if the view exists by using the `IF EXISTS` parameter. If you drop a view that does not exist, you will get an error. To prevent this, you can use the `IF EXISTS` parameter. - -Here is how you do it: - -```sql -DROP VIEW IF EXISTS view_name; -``` - -In this case, if the view exists, it will be dropped. If the view does not exist, nothing happens and you don't get an error. \ No newline at end of file +- [@article@DROP VIEW](https://study.com/academy/lesson/sql-drop-view-tutorial-overview.html) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/dynamic-sql@z5Sf0VU14ZCQ80kL1qOqc.md b/src/data/roadmaps/sql/content/dynamic-sql@z5Sf0VU14ZCQ80kL1qOqc.md index 73b527f0d..cb2c667e4 100644 --- a/src/data/roadmaps/sql/content/dynamic-sql@z5Sf0VU14ZCQ80kL1qOqc.md +++ b/src/data/roadmaps/sql/content/dynamic-sql@z5Sf0VU14ZCQ80kL1qOqc.md @@ -1,50 +1,9 @@ # Dynamic SQL -**Dynamic SQL** - Dynamic SQL is a programming method that allows you to build SQL statements dynamically at runtime. It allows you to create more flexible and adaptable applications because you can manipulate the SQL statements on the fly, in response to inputs or changing conditions. -Consider an application where a user can choose multiple search conditions from a range of choices. You might not know how many conditions the user will choose, or what they'll be until runtime. With static SQL, you would have to include a large number of potential search conditions in your WHERE clause. With dynamic SQL, you can build the search string based on the user's actual choices. - -**Executing Dynamic SQL** - -There are two ways to execute dynamic SQL: - -1. `EXECUTE IMMEDIATE` statement -2. `OPEN-FOR, FETCH, CLOSE` statements - - -**Code Examples** - -1. Using `EXECUTE IMMEDIATE`: - -Here, a table name is passed as a variable to a PL/SQL block. The block concatenates the variable into a DELETE statement, which is executed dynamically. - -```sql -DECLARE - table_name VARCHAR(30) := 'employees'; - sql_stmt VARCHAR(100); -BEGIN - sql_stmt := 'DELETE FROM ' || table_name; - EXECUTE IMMEDIATE sql_stmt; -END; -``` - -2. Using `OPEN-FOR, FETCH, CLOSE` - -In this example, a dynamic SQL query is being built and executed using the `OPEN-FOR, FETCH, CLOSE` statements. +Consider an application where a user can choose multiple search conditions from a range of choices. You might not know how many conditions the user will choose, or what they'll be until runtime. With static SQL, you would have to include a large number of potential search conditions in your WHERE clause. With dynamic SQL, you can build the search string based on the user's actual choices. Note that while the use of Dynamic SQL offers greater flexibility, it also comes with potential security risks such as SQL Injection, and should be used judiciously. Always validate and sanitize inputs when building dynamic queries. -```sql -DECLARE - sql_stmt VARCHAR2(1000); - emp_id NUMBER(4) := 7566; - emp_rec emp%ROWTYPE; -BEGIN - sql_stmt := 'SELECT * FROM emp WHERE empno = :id'; - OPEN emp_cv FOR sql_stmt USING emp_id; - FETCH emp_cv INTO emp_rec; - CLOSE emp_cv; -END; -``` +Learn more from the following resources: -Note that while the use of Dynamic SQL offers greater flexibility, it also comes with potential security risks such as SQL Injection, and should be used judiciously. Always validate and sanitize inputs when building dynamic queries. \ No newline at end of file +- [@article@Dynamic SQL in SQL Server](https://www.sqlshack.com/dynamic-sql-in-sql-server/) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/floor@o2SH4iQn1Ap2yDZ7cVYLO.md b/src/data/roadmaps/sql/content/floor@o2SH4iQn1Ap2yDZ7cVYLO.md index 5159c0472..adc53d1a8 100644 --- a/src/data/roadmaps/sql/content/floor@o2SH4iQn1Ap2yDZ7cVYLO.md +++ b/src/data/roadmaps/sql/content/floor@o2SH4iQn1Ap2yDZ7cVYLO.md @@ -4,27 +4,6 @@ The SQL `FLOOR` function is used to round down any specific decimal or numeric v One important aspect to note is that the `FLOOR` function's argument must be a number and it always returns an integer. -## Syntax +Learn more from the following resources: -The syntax of using the `FLOOR` function in SQL is as follows: -```sql -FLOOR (number); -``` - -## Example Usage - -Here's a simple example of its usage: - -```sql -SELECT FLOOR(25.75); -``` -The above query will return `25` as the result, as that's the nearest integer less than `25.75`. - -Suppose we have a table called `Orders` with a column `SalePrice` that includes decimal values. If we wanted to round down the `SalePrice` values to the nearest whole numbers, we could use a query like this: - -```sql -SELECT FLOOR(SalePrice) AS RoundedSalePrice -FROM Orders; -``` - -This would output a new column `RoundedSalePrice` where all the sale prices have been rounded down to the nearest integers. \ No newline at end of file +- [@article@FLOOR](https://www.w3schools.com/sql/func_sqlserver_floor.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/foreign-key@DHz6sRLYhFeCbAcNJS8hm.md b/src/data/roadmaps/sql/content/foreign-key@DHz6sRLYhFeCbAcNJS8hm.md index acc557947..83668301f 100644 --- a/src/data/roadmaps/sql/content/foreign-key@DHz6sRLYhFeCbAcNJS8hm.md +++ b/src/data/roadmaps/sql/content/foreign-key@DHz6sRLYhFeCbAcNJS8hm.md @@ -1,37 +1,8 @@ # Foreign Key -A foreign key is a key used to link two tables together. It is a field (or collection of fields) in one table that refers to the primary key in another table. The table with the foreign key is called the child table, and the one with the primary key is called the referenced or parent table. +A foreign key in SQL is a column or group of columns in one table that refers to the primary key of another table. It establishes a link between two tables, enforcing referential integrity and maintaining relationships between related data. Foreign keys ensure that values in the referencing table correspond to valid values in the referenced table, preventing orphaned records and maintaining data consistency across tables. They are crucial for implementing relational database designs and supporting complex queries that join multiple tables. -## Basic Syntax +Learn more from the following resources: -The SQL used to add a foreign key constraint is: +- [@article@What is a foreign key?](https://www.cockroachlabs.com/blog/what-is-a-foreign-key/) -```sql -ALTER TABLE child_table -ADD FOREIGN KEY (fk_column) -REFERENCES parent_table (parent_key_column) -``` - -Where: -- `child_table` is the table where you want to add the foreign key -- `fk_column` is the field in the child table that you want to use as foreign key -- `parent_table` is the table being referenced by the foreign key -- `parent_key_column` is the column in `parent_table` that `fk_column` points to - -## Example - -Suppose we have two tables, `Orders` and `Customers` where `Orders` table has a column `customer_id` that should point to a Customer. If `Customers` has a `customer_id` column as the primary key then you can create a foreign key as follows - -```sql -ALTER TABLE Orders -ADD FOREIGN KEY (customer_id) -REFERENCES Customers (customer_id); -``` - -This means that for every row in `Orders`, the `customer_id` value must match a value in the `Customers` table, ensuring data integrity. - -## Note - -Please note that MySQL requires you to have the foreign key columns be indexed for performance reasons. If they aren't indexed already, the `FOREIGN KEY` constraint will implicitly index them for you. Also, a significant thing to note is, InnoDB does not support the 'foreign key check' in CREATE TABLE statements, instead, you must use ALTER TABLE after the table has been created. - -Not all database systems support all types of keys, and different systems support different syntax for them. The examples above are in SQL syntax, which is supported by most databases. diff --git a/src/data/roadmaps/sql/content/from@N1Racr3ZpU320gS545We8.md b/src/data/roadmaps/sql/content/from@N1Racr3ZpU320gS545We8.md index 0bc6e3cfb..50e00432c 100644 --- a/src/data/roadmaps/sql/content/from@N1Racr3ZpU320gS545We8.md +++ b/src/data/roadmaps/sql/content/from@N1Racr3ZpU320gS545We8.md @@ -4,44 +4,6 @@ The `FROM` clause in SQL specifies the tables from which the retrieval should be Typically, `FROM` is followed by space delimited list of tables in which the SELECT operation is to be executed. If you need to pull data from multiple tables, you would separate each table with a comma. -Here are some examples: +Learn more from the following resources: -**Example 1 - Simple Usage** - -If you've a table called `employees`, you can select all employees' data like this: - -```sql -SELECT * -FROM employees; -``` -In this example, `*` means "all columns". So, `SELECT * FROM employees;` will retrieve all data from the `employees` table. - -**Example 2 - FROM with Multiple Tables** - -If you've multiple tables, say `employees` and `departments`, and you want to select data from both, you can do the following: - -```sql -SELECT employees.name, departments.department -FROM employees, departments -WHERE employees.dept_id = departments.dept_id; -``` - -In this example, the `FROM` clause is following by two tables: `employees` and `departments`. `employees.name` and `departments.department` indicate that we're selecting the `name` column from the `employees` table and the `department` column from the `departments` table. - -Remember, always respect the order of operations in SQL. The `FROM` clause works only after tables are identified. - -In complex SQL queries where you might need to pull data from multiple tables, aliases are used to temporarily rename the tables within the individual SQL statement. - -**Example 3 - FROM with Aliases** - -Below is an example of a `FROM` clause with aliases: - -```sql -SELECT e.name, d.department -FROM employees AS e, departments AS d -WHERE e.dept_id = d.dept_id; -``` - -In this example, `employees` and `departments` tables are termed as `e` and `d` respectively. - -That's it! Remember that `FROM` is not limited only to `SELECT`. It is applicable to `UPDATE` and `DELETE` operations as well. \ No newline at end of file +- [@article@SQL FROM Keyword](https://www.w3schools.com/sql/sql_ref_from.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/full-outer-join@aS5zCyJRA779yHF0G2pje.md b/src/data/roadmaps/sql/content/full-outer-join@aS5zCyJRA779yHF0G2pje.md index 354342d39..3a8966e9a 100644 --- a/src/data/roadmaps/sql/content/full-outer-join@aS5zCyJRA779yHF0G2pje.md +++ b/src/data/roadmaps/sql/content/full-outer-join@aS5zCyJRA779yHF0G2pje.md @@ -1,63 +1,7 @@ # FULL OUTER JOIN -A `FULL OUTER JOIN` in SQL is a method to combine rows from two or more tables, based on a related column between them. It returns all rows from the left table (`table1`) and from the right table (`table2`). +A `FULL OUTER JOIN` in SQL combines the results of both `LEFT` and `RIGHT OUTER JOIN`s. It returns all rows from both tables, matching records where the join condition is met and including unmatched rows from both tables with `NULL` values in place of missing data. This join type is useful when you need to see all data from both tables, regardless of whether there are matching rows, and is particularly valuable for identifying missing relationships or performing data reconciliation between two tables. -The `FULL OUTER JOIN` keyword combines the results of both left and right outer joins and returns all (matched or unmatched) rows from the tables on both sides of the join clause. +Learn more from the following resources: -If there are records in the "Customers" table that do not have matches in the "Orders" table, those will be included. Also, if there are records in the "Orders" table that do not have matches in the "Customers" table, those will be included. - -## Syntax - -``` -SELECT column_name(s) -FROM table1 -FULL OUTER JOIN table2 -ON table1.column_name = table2.column_name; -``` - -## Code Example - -Consider the following two tables: - -**Table1: Customers** - -| ID | Name | -|----|-------| -| 1 | Tom | -| 2 | Lucy | -| 3 | Steve | -| 4 | Dave | - -**Table2: Orders** - -| OrderID | CustomerID | Product | -|---------|------------|----------| -| 1 | 3 | Apple | -| 2 | 3 | Banana | -| 3 | 1 | Orange | -| 4 | 2 | Mango | -| 5 | 7 | Blueberry| - -A `FULL OUTER JOIN` query would look like this: - -``` -SELECT Customers.Name, Orders.Product -FROM Customers -FULL OUTER JOIN Orders -ON Customers.ID = Orders.CustomerID -ORDER BY Customers.Name; -``` - -The result-set will look like this: - -| Name | Product | -|-------|----------| -| Tom | Orange | -| Lucy | Mango | -| Steve | Apple | -| Steve | Banana | -| NULL | Blueberry| -| Dave | NULL | - -This response includes all customers and all orders. If no matching orders exist for a customer, or if no matching customer exists for an order, the missing side will contain NULL. -For example, Dave made no orders (his details in the product column are NULL) and the Blueberry order was made by a non-existing customer (the customer's details are NULL in the name column). \ No newline at end of file +- [@article@FULL OUTER JOIN](https://www.w3schools.com/sql/sql_join_full.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/grant-and-revoke@03qMopxzjx_-dZbYw9b7J.md b/src/data/roadmaps/sql/content/grant-and-revoke@03qMopxzjx_-dZbYw9b7J.md index ac7f48499..194ab697e 100644 --- a/src/data/roadmaps/sql/content/grant-and-revoke@03qMopxzjx_-dZbYw9b7J.md +++ b/src/data/roadmaps/sql/content/grant-and-revoke@03qMopxzjx_-dZbYw9b7J.md @@ -1,46 +1,8 @@ # GRANT and REVOKE -In SQL, `GRANT` and `REVOKE` are Data Control Language (DCL) commands used for providing and removing user privileges respectively. +`GRANT` and `REVOKE` are SQL commands used to manage user permissions in a database. `GRANT` is used to give specific privileges (such as `SELECT`, `INSERT`, `UPDATE`, `DELETE`) on database objects to users or roles, while `REVOKE` is used to remove these privileges. These commands are essential for implementing database security, controlling access to sensitive data, and ensuring that users have appropriate permissions for their roles. By using `GRANT` and `REVOKE`, database administrators can fine-tune access control, adhering to the principle of least privilege in database management. -## GRANT +Learn more from the following resources: -The `GRANT` statement allows database administrators to grant permissions or privileges on a database object to users. There are various types of privileges like SELECT, INSERT, UPDATE, DELETE, REFERENCES, ALL. - -You can use the `GRANT` statement as follows: - -```sql -GRANT privilege_name -ON object_name -TO {user_name |PUBLIC |role_name} -[WITH GRANT OPTION]; -``` - -Example: - -```sql -GRANT SELECT ON employees TO user1; -``` - -In this example, `user1` is granted permission to read/perform SELECT operations on the `employees` table. - -## REVOKE - -The `REVOKE` statement can be used when we want to revoke some or all of the privileges that were assigned earlier to a user or a group of users. The syntax for using the `REVOKE` command is similar to the `GRANT` command. - -Here's the syntax: - -```sql -REVOKE privilege_name -ON object_name -FROM {user_name |PUBLIC |role_name} -``` - -Example: - -```sql -REVOKE SELECT ON employees FROM user1; -``` - -In this example, `user1` is revoked from the permission to read/perform SELECT operations on the `employees` table. - -Permission management is an important aspect of database management, understanding, and using `GRANT` and `REVOKE` operations help in maintaining the integrity and security of your data in SQL. \ No newline at end of file +- [@article@GRANT](https://www.ibm.com/docs/en/qmf/12.2.0?topic=privileges-sql-grant-statement) +- [@article@REVOKE](https://www.ibm.com/docs/en/qmf/12.2.0?topic=privileges-sql-revoke-statement) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/group-by@14TKE6KhrH1yFtHcSZSXq.md b/src/data/roadmaps/sql/content/group-by@14TKE6KhrH1yFtHcSZSXq.md index 80dc7757b..822c694f9 100644 --- a/src/data/roadmaps/sql/content/group-by@14TKE6KhrH1yFtHcSZSXq.md +++ b/src/data/roadmaps/sql/content/group-by@14TKE6KhrH1yFtHcSZSXq.md @@ -1,68 +1,7 @@ # GROUP BY -"Group By" is a clause in SQL that is used to arrange identical data into groups. This clause comes under the category of Group Functions, alongside the likes of Count, Sum, Average, etc. +`GROUP BY` is an SQL clause used in `SELECT` statements to arrange identical data into groups. It's typically used with aggregate functions (like `COUNT`, `SUM`, `AVG`) to perform calculations on each group of rows. `GROUP BY` collects data across multiple records and groups the results by one or more columns, allowing for analysis of data at a higher level of granularity. This clause is fundamental for generating summary reports, performing data analysis, and creating meaningful aggregations of data in relational databases. -The syntax for 'Group by' is: +Learn more from the following resources: -```sql -SELECT column1, column2 -FROM table_name -GROUP BY column1, column2; -``` - -Here, column1, column2, are the names of the columns based on which we want to group the results. - -## Example: - -Assume we have a "Sales" table. This table has three columns: ID, Item, and Amount. - -```sql -ID Item Amount ---- ------ ------ -1 A 150 -2 B 200 -3 A 100 -4 B 50 -5 A 200 -6 A 100 -7 B 150 -``` - -Execute the following SQL statement... - -```sql -SELECT Item, SUM(Amount) -FROM Sales -GROUP BY Item; -``` - -This will concatenate, or "group", all items that are the same into one row, applying the SUM() function on their respective Amounts. The output will then be: - -```sql -Item SUM(Amount) ------- ---------- -A 550 -B 400 -``` - -## Group By with Having Clause - -The Group By clause can also be used with the Having keyword. The Having keyword allows you to filter the results of the group function. - -For example: - -```sql -SELECT Item, SUM(Amount) -FROM Sales -GROUP BY Item -HAVING SUM(Amount) > 150; -``` - -This will return all grouped items where the total amount is more than 150. Hence, the result will be: - -```sql -Item SUM(Amount) ------- ---------- -A 550 -B 400 -``` \ No newline at end of file +- [@article@SQL GROUP BY](https://www.programiz.com/sql/group-by) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/group-by@Zw8IHfCCMSxmVjx5Ho5ff.md b/src/data/roadmaps/sql/content/group-by@Zw8IHfCCMSxmVjx5Ho5ff.md index b9be5b419..742586d66 100644 --- a/src/data/roadmaps/sql/content/group-by@Zw8IHfCCMSxmVjx5Ho5ff.md +++ b/src/data/roadmaps/sql/content/group-by@Zw8IHfCCMSxmVjx5Ho5ff.md @@ -1,57 +1,7 @@ # GROUP BY -**Group By** is an SQL clause that arranges identical data into groups. It is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or multiple columns. +GROUP BY is an SQL clause used in SELECT statements to arrange identical data into groups. It's typically used with aggregate functions (like COUNT, SUM, AVG) to perform calculations on each group of rows. GROUP BY collects data across multiple records and groups the results by one or more columns, allowing for analysis of data at a higher level of granularity. This clause is fundamental for generating summary reports, performing data analysis, and creating meaningful aggregations of data in relational databases. -## Syntax: +Learn more from the following resources: -```sql -SELECT column1, column2, ..., aggregate_function(column_name) -FROM table_name -WHERE condition -GROUP BY column1, column2, ...; -``` - -## Explanation: - -- **column1, column2**, these columns are not under the aggregate function or any operation. They will be used to group the data. -- **aggregate_function(column_name)**, Aggregate functions will apply on the group of the column_name specified, not individual rows. -- The **WHERE** clause is optional. It adds conditions to select which rows will be grouped. - -## Examples: - -Here's an example of the **Group By** clause in action. Given is a table **Sales**: - -| order_id | product_id | qty | -|----------|------------|-----| -| 1 | 1001 | 20 | -| 2 | 1002 | 10 | -| 3 | 1003 | 50 | -| 4 | 1001 | 10 | -| 5 | 1002 | 20 | -| 6 | 1003 | 50 | - -## Example 1: -```sql -SELECT product_id, SUM(qty) -FROM SALES -GROUP BY product_id; -``` - -The result will be: - -|product_id | SUM(qty) -|-----------|----------| -| 1001 | 30 | -| 1002 | 30 | -| 1003 | 100 | - -## Example 2: - -You can perform group by operation on multiple columns. In the below example, 'product_id' and 'order_id' are used to group the data. -```sql -SELECT product_id, order_id, SUM(qty) -FROM SALES -GROUP BY product_id, order_id; -``` - -**Group By** clause can be used with **HAVING** clause to add a condition on grouped data. \ No newline at end of file +- [@article@SQL GROUP BY](https://www.programiz.com/sql/group-by) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/having@HhICJpCK5__b-itUoEBES.md b/src/data/roadmaps/sql/content/having@HhICJpCK5__b-itUoEBES.md index 6458c9c82..7cb74173f 100644 --- a/src/data/roadmaps/sql/content/having@HhICJpCK5__b-itUoEBES.md +++ b/src/data/roadmaps/sql/content/having@HhICJpCK5__b-itUoEBES.md @@ -6,46 +6,6 @@ It's important to note that where `WHERE` clause introduces conditions on indivi Also note, `HAVING` applies to summarized group records, whereas `WHERE` applies to individual records. -Syntax: +Learn more from the following resources: -```sql -SELECT column_name(s) -FROM table_name -WHERE condition -GROUP BY column_name(s) -HAVING condition -ORDER BY column_name(s); -``` - -## Example - -Consider this "Orders" table: - -| OrderID | Customer | Amount | -|---------|----------|--------| -| 1 | John | 1000 | -| 2 | Mary | 1500 | -| 3 | John | 2000 | -| 4 | Jane | 1000 | -| 5 | Mary | 2000 | -| 6 | John | 3000 | -| 7 | Jane | 2000 | -| 8 | Mary | 2500 | - -For instance, if you wanted to find customers who have spent more than $3000 in total, you might use the `HAVING` clause as follows: - -```sql -SELECT Customer, SUM(Amount) -FROM Orders -GROUP BY Customer -HAVING SUM(Amount) > 3000; -``` - -As a result, the query returns: - -| Customer | SUM(Amount) | -|----------|-------------| -| John | 6000 | -| Mary | 6000 | - -In this case, the `HAVING` clause filters out all Customers with a total `Amount` less than or equal to $3000. Only John and Mary have the total sum of `Amount` more than $3000. Thus, only these records satisfy the `HAVING` clause and are included in the result. +- [@article@SQL HAVING Clause](https://www.programiz.com/sql/having) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/having@ytwCkSMTiTuemE0KVfAfy.md b/src/data/roadmaps/sql/content/having@ytwCkSMTiTuemE0KVfAfy.md index 59eb1bdb9..886143382 100644 --- a/src/data/roadmaps/sql/content/having@ytwCkSMTiTuemE0KVfAfy.md +++ b/src/data/roadmaps/sql/content/having@ytwCkSMTiTuemE0KVfAfy.md @@ -4,41 +4,6 @@ It’s similar to a `WHERE` clause, but operates on the results of a grouping. The `WHERE` clause places conditions on the selected columns, whereas the `HAVING` clause places conditions on groups created by the `GROUP BY` clause. -## Syntax +Learn more from the following resources: -The basic syntax is as follows: -```sql -SELECT column_name, function(column_name) -FROM table_name -WHERE condition -GROUP BY column_name -HAVING function(column_name) condition value; -``` - -## Example - -Suppose we have a `Sales` table with the following data: - -| SaleID | Product | Quantity | -|--------|---------|----------| -| 1 | A | 30 | -| 2 | B | 20 | -| 3 | A | 100 | -| 4 | B | 50 | -| 5 | C | 60 | -| 6 | A | 70 | - -And we want to find products which have total quantity sold more than 100. We can use the `HAVING` clause as follows: - -```sql -SELECT Product, SUM(Quantity) as TotalQuantity -FROM Sales -GROUP BY Product -HAVING TotalQuantity > 100; -``` - -In this query, - -- `GROUP BY Product` would group the sales figures by Product. -- `SUM(Quantity)` would calculate total quantity sold for each product. -- `HAVING TotalQuantity > 100` would filter out the groups which have total quantity sold less than or equal to 100.- \ No newline at end of file +- [@article@SQL HAVING Clause](https://www.programiz.com/sql/having) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/indexes@LcljR70T-OnzSrJJDqOWf.md b/src/data/roadmaps/sql/content/indexes@LcljR70T-OnzSrJJDqOWf.md index 4c51ba409..b43a3891b 100644 --- a/src/data/roadmaps/sql/content/indexes@LcljR70T-OnzSrJJDqOWf.md +++ b/src/data/roadmaps/sql/content/indexes@LcljR70T-OnzSrJJDqOWf.md @@ -1,72 +1,7 @@ # Indexes -An index in SQL is a database object which is used to improve the speed of data retrieval operations on a database table. Similarly to how an index in a book helps you find information quickly without reading the entire book, an index in a database helps the database software find data quickly without scanning the entire table. +Indexes in SQL are database objects that improve the speed of data retrieval operations on database tables. They work similarly to book indexes, providing a quick lookup mechanism for finding rows with specific column values. Indexes create a separate data structure that allows the database engine to locate data without scanning the entire table. While they speed up `SELECT` queries, indexes can slow down `INSERT`, `UPDATE`, and `DELETE` operations because the index structure must be updated. Proper index design is crucial for optimizing database performance, especially for large tables or frequently queried columns. -## Clustered Index +Learn more from the following resources: -A clustered index determines the physical order of data inside a table. It sorts and stores the data rows in the table based on their key values. There can be only one clustered index per table. - -Creating a clustered index: - -```sql -CREATE CLUSTERED INDEX index_name -ON table_name (column_name); -``` - -## Non-Clustered Index - -A non-clustered index doesn’t sort the physical data inside the table. Instead, it creates a separate object within a table which points back to the original table rows after creating. You can create numerous non-clustered indexes per table. - -Creating a non-clustered index: - -```sql -CREATE NONCLUSTERED INDEX index_name -ON table_name (column_name); -``` - -## Indexes on Multiple Columns - -An index can be built on more than one column of a table, which results in index entries having values of multiple columns. This is known as a composite index. - -Creating a composite index: - -```sql -CREATE INDEX index_name -ON table_name (column1, column2); -``` - -## Unique Indexes - -A unique index doesn't allow any field to have duplicate values if the field is unique indexed. If a primary key is defined, a unique index can be applied automatically. - -Creating a unique index: - -```sql -CREATE UNIQUE INDEX index_name -ON table_name (column_name); -``` - -## Explicit vs Implicit Indexes - -Indexes explicitly created by users are known as explicit indexes, while indexes automatically created by SQL Server when a primary key or unique constraint is defined are known as implicit indexes. - -Creating an explicit index: - -```sql -CREATE INDEX index_name -ON table_name (column_name); -``` - -## Full-Text Indexes - -If you're dealing with text searching within a large string of text, full-text indexes are especially helpful. These indexes do not work using a standard comparison search but instead use word-breakers, filters, and noise-words (stop words). - -Creating a full-text index: - -```sql -CREATE FULLTEXT INDEX ON table_name -(column_name) -KEY INDEX index_name; -``` - -Please note that the creation and maintenance of indexes involve a trade-off between query speed and update costs. Indexes speed up retrieval at the expense of slower updates and increased storage space. +- [@article@Create SQL Index Statement](https://www.w3schools.com/sql/sql_create_index.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/inner-join@aaua13CkTxLOYXr8cAgPm.md b/src/data/roadmaps/sql/content/inner-join@aaua13CkTxLOYXr8cAgPm.md index d80a2ba1d..f8bc1d90e 100644 --- a/src/data/roadmaps/sql/content/inner-join@aaua13CkTxLOYXr8cAgPm.md +++ b/src/data/roadmaps/sql/content/inner-join@aaua13CkTxLOYXr8cAgPm.md @@ -8,51 +8,7 @@ Few things to consider in case of `INNER JOIN`: - It returns only the matching rows from both the tables. - If there is no match, the returned is an empty result. -## Syntax +Learn more from the following resources: -Here is the syntax for an SQL `INNER JOIN`: - -```sql -SELECT column_name(s) -FROM table1 -INNER JOIN table2 -ON table1.column_name = table2.column_name; -``` - -The `INNER JOIN` keyword selects records that have matching values in both tables. - -## Example - -Consider two tables: - -**Table1: `Orders`** - -|OrderID|CustomerID|OrderAmount| -|-------|----------|-----------| -|1 |100 |30 | -|2 |101 |40 | -|3 |102 |50 | - -**Table2: `Customers`** - -|CustomerID|Name |Country | -|----------|--------|---------| -|100 |Ana |Germany | -|101 |Ben |USA | -|103 |Charlie |Australia| - -Now, if you want to select all orders, and any matching customer information: - -```sql -SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderAmount -FROM Orders -INNER JOIN Customers -ON Orders.CustomerID = Customers.CustomerID; -``` - -This would produce the following result: - -|OrderID|Name|OrderAmount| -|-------|----|-----------| -|1 |Ana |30 | -|2 |Ben |40 | +- [@article@SQL INNER JOIN](https://www.w3schools.com/sql/sql_join_inner.asp) +- [@article@SQL INNER JOIN Clause](https://www.programiz.com/sql/inner-join) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/insert@-Hew0y53ziZK3epQnGA0O.md b/src/data/roadmaps/sql/content/insert@-Hew0y53ziZK3epQnGA0O.md index 0f062163e..f5591a3c8 100644 --- a/src/data/roadmaps/sql/content/insert@-Hew0y53ziZK3epQnGA0O.md +++ b/src/data/roadmaps/sql/content/insert@-Hew0y53ziZK3epQnGA0O.md @@ -2,47 +2,6 @@ The "INSERT" statement is used to add new rows of data to a table in a database. There are two main forms of the INSERT command: `INSERT INTO` which, if columns are not named, expects a full set of columns, and `INSERT INTO table_name (column1, column2, ...)` where only named columns will be filled with data. -## Usage +Learn more from the following resources: -1. **Insert full set of columns:** - -Code example: - -```sql -INSERT INTO table_name -VALUES (value1, value2, ..., valueN); -``` - -In the example above, you need to provide values for all columns available in the table. - -2. **Selectively insert data:** - -Code example: - -```sql -INSERT INTO table_name (column1, column2, ..., columnN) -VALUES (value1, value2, ..., valueN); -``` - -Here, you only provide values for certain columns of the table. Other columns will take on their default values (if any). - -3. **Insert data from another table:** - -Another useful form of the `INSERT` command is `INSERT INTO SELECT`, which allows you to copy data from one table and add it into another table. - -Code example: - -```sql -INSERT INTO table1 (column1, column2, ... , columnN) -SELECT column1, column2, ... , columnN -FROM table2 -WHERE condition; -``` - -In this scenario, `table2` should already have the data we need and the WHERE clause can be used to select only those rows that satisfy certain conditions. - -> Note: The crucial point is that your columns in both SELECT and INSERT INTO command must be in same order and their datatypes must be compatible. -> -> Kindly ensure that database table has enough space to hold inserted data, else it will resulting in OVERFLOW error. - -**Note**: Always make sure to provide correct and compatible data types for the columns. The SQL engine won't allow you to add data that doesn't match the column's declared data type. \ No newline at end of file +- [@article@SQL INSERT](https://www.w3schools.com/sql/sql_insert.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/insert@mPj6BiK5FKKkIQ9WsWEo6.md b/src/data/roadmaps/sql/content/insert@mPj6BiK5FKKkIQ9WsWEo6.md deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/data/roadmaps/sql/content/join-queries@8V6yw7kLaow-VVcv_K_pL.md b/src/data/roadmaps/sql/content/join-queries@8V6yw7kLaow-VVcv_K_pL.md index eef300fae..f15c9f529 100644 --- a/src/data/roadmaps/sql/content/join-queries@8V6yw7kLaow-VVcv_K_pL.md +++ b/src/data/roadmaps/sql/content/join-queries@8V6yw7kLaow-VVcv_K_pL.md @@ -1,69 +1,7 @@ # SQL JOIN Queries -JOIN clause is used to combine rows from two or more tables, based on a related column between them. +SQL `JOIN` queries combine rows from two or more tables based on a related column between them. There are several types of JOINs, including INNER JOIN (returns matching rows), `LEFT JOIN` (returns all rows from the left table and matching rows from the right), `RIGHT JOIN` (opposite of `LEFT JOIN`), and `FULL JOIN` (returns all rows when there's a match in either table). `JOIN`s are fundamental for working with relational databases, allowing users to retrieve data from multiple tables in a single query, establish relationships between tables, and perform complex data analysis across related datasets. -## INNER JOIN: +Learn more from the following resources: -Inner join returns records that have matching values in both tables. For example: - -```sql -SELECT Orders.OrderID, Customers.CustomerName -FROM Orders -INNER JOIN Customers -ON Orders.CustomerID = Customers.CustomerID; -``` - -## LEFT (OUTER) JOIN: - -Returns all records from the left table, and the matched records from the right table. Also returns NULL if there is no match. Example: - -```sql -SELECT Customers.CustomerName, Orders.OrderID -FROM Customers -LEFT JOIN Orders -ON Customers.CustomerID = Orders.CustomerID; -``` - -## RIGHT (OUTER) JOIN: - -Returns all records from the right table, and the matched records from the left table. Also returns null if there is no match. Example: - -```sql -SELECT Orders.OrderID, Customers.CustomerName -FROM Orders -RIGHT JOIN Customers -ON Orders.CustomerID = Customers.CustomerID; -``` -## FULL (OUTER) JOIN: - -Returns all records when there is a match in either left (table1) or right (table2) table records. Also returns null if there is no match. Example: - -```sql -SELECT Customers.CustomerName, Orders.OrderID -FROM Customers -FULL OUTER JOIN Orders -ON Customers.CustomerID = Orders.CustomerID; -``` -## SELF JOIN: - -Self join is a regular join, but the table is joined with itself. Example: - -```sql -SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, A.City -FROM Customers A, Customers B -WHERE A.CustomerID <> B.CustomerID -AND A.City = B.City; -``` - -## NATURAL JOIN: - -The natural join is akin to an inner join, automatically linking two columns based on identical names. -Note: Columns should have same data type in both tables - -```sql -SELECT * -FROM Customers -NATURAL JOIN Orders; -``` - -**Note**: JOINS can be used with SELECT, UPDATE, and DELETE statements. +- [@article@7 SQL JOIN Examples With Detailed Explanations](https://learnsql.com/blog/sql-join-examples-with-explanations/) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/joins@4UQQYbjzwVxZOAxBuXKQS.md b/src/data/roadmaps/sql/content/joins@4UQQYbjzwVxZOAxBuXKQS.md index 00cbd89a2..d465ea4c9 100644 --- a/src/data/roadmaps/sql/content/joins@4UQQYbjzwVxZOAxBuXKQS.md +++ b/src/data/roadmaps/sql/content/joins@4UQQYbjzwVxZOAxBuXKQS.md @@ -1,50 +1,7 @@ # JOINs -SQL Joins are used to retrieve data from two or more data tables, based on a related column between them. The key types of JOINs include: +SQL `JOINs` are clauses used to combine rows from two or more tables based on a related column between them. They allow retrieval of data from multiple tables in a single query, enabling complex data analysis and reporting. The main types of `JOINs` include `INNER JOIN` (returns matching rows from both tables), `LEFT JOIN` (returns all rows from the left table and matching rows from the right), `RIGHT JOIN` (opposite of `LEFT JOIN`), and `FULL JOIN` (returns all rows when there's a match in either table). `JOINs` are fundamental to relational database operations, facilitating data integration and exploration across related datasets. -1. INNER JOIN: This type of join returns records with matching values in both tables. +Learn more from the following resources: -```sql -SELECT table1.column1, table2.column2... -FROM table1 -INNER JOIN table2 -ON table1.matching_column = table2.matching_column; -``` -2. LEFT (OUTER) JOIN: Returns all records from the left table, and matched records from the right table. - -```sql -SELECT table1.column1, table2.column2... -FROM table1 -LEFT JOIN table2 -ON table1.matching_column = table2.matching_column; -``` -3. RIGHT (OUTER) JOIN: Returns all records from the right table, and matched records from the left table. - -```sql -SELECT table1.column1, table2.column2... -FROM table1 -RIGHT JOIN table2 -ON table1.matching_column = table2.matching_column; -``` -4. FULL (OUTER) JOIN: Returns all records when either a match is found in either left (table1) or right (table2) table records. - -```sql -SELECT table1.column1, table2.column2... -FROM table1 -FULL JOIN table2 -ON table1.matching_column = table2.matching_column; -``` -5. SELF JOIN: A self join is a join in which a table is joined with itself. - -```sql -SELECT a.column_name, b.column_name... -FROM table_name AS a, table_name AS b -WHERE condition; -``` -6. CARTESIAN JOIN: If WHERE clause is omitted, the join operation produces a Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. - -```sql -SELECT table1.column1, table2.column2... -FROM table1, table2; -``` -Each type of JOIN allows for the retrieval of data in different situations, making them flexible and versatile for different SQL queries. \ No newline at end of file +- [@article@SQL JOINs Cheat Sheet](https://www.datacamp.com/cheat-sheet/sql-joins-cheat-sheet) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/lag@BcXdxY6bld5c0YNFSKkh-.md b/src/data/roadmaps/sql/content/lag@BcXdxY6bld5c0YNFSKkh-.md index 2de9db2c4..76b45db14 100644 --- a/src/data/roadmaps/sql/content/lag@BcXdxY6bld5c0YNFSKkh-.md +++ b/src/data/roadmaps/sql/content/lag@BcXdxY6bld5c0YNFSKkh-.md @@ -1,50 +1,7 @@ # lag -`LAG` is a window function provided by SQL that allows us to fetch data from a previous row in the same result set without using a self-join. This function is commonly used in data analysis, for instance, comparing sales in a certain period with sales in a previous period. +`LAG` is a window function in SQL that provides access to a row at a specified offset prior to the current row within a partition. It allows you to compare the current row's values with previous rows' values without using self-joins. LAG is particularly useful for calculating running differences, identifying trends, or comparing sequential data points in time-series analysis. The function takes the column to offset, the number of rows to offset (default is 1), and an optional default value to return when the offset goes beyond the partition's boundary. -The general syntax for using the `LAG` function is as follows: +Learn more from the following resources: -```sql -LAG (expression [, offset [, default]]) -OVER ( - [PARTITION BY partition_expression, ... ] - ORDER BY sort_expression [ASC | DESC], ... -) -``` - -Let's break down this syntax: - -- `expression`: This is the value to return from a previous row. If you specify multiple expressions, `LAG` treats them as a single compound expression. -- `offset`: This is an optional section where you specify the number of steps to reachback. By default, the `offset` is 1, meaning that it gets the value from a previous row. -- `default`: This is another optional section where you define a value to return if the `LAG` function accesses beyond the scope of partition. By default, it returns NULL. - -## Example - -Suppose we have the following 'sales' table: - -| Year | Sales | -| ---- | ----- | -| 2017 | 200 | -| 2018 | 250 | -| 2019 | 300 | -| 2020 | 350 | - -You'd like to compare the sales of each year to the sales of the previous year. Here's how you can do it using the `LAG` function: - -```sql -SELECT Year, - Sales, - LAG(Sales) OVER (ORDER BY Year) AS PrevYearSales -FROM sales; -``` - -This should produce: - -| Year | Sales | PrevYearSales | -| ---- | ----- | ------------- | -| 2017 | 200 | NULL | -| 2018 | 250 | 200 | -| 2019 | 300 | 250 | -| 2020 | 350 | 300 | - -In this example, `LAG` fetched the sales of the previous year ordered by the 'Year' column. The sales in 2017 do not have a previous year, so `LAG` returns NULL. \ No newline at end of file +- [@article@Understanding the LAG function in SQL](https://www.datacamp.com/tutorial/sql-lag) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/lead@aJJjaGunRrwyh9MjQfJt-.md b/src/data/roadmaps/sql/content/lead@aJJjaGunRrwyh9MjQfJt-.md index eb463cafb..1e9ad07cd 100644 --- a/src/data/roadmaps/sql/content/lead@aJJjaGunRrwyh9MjQfJt-.md +++ b/src/data/roadmaps/sql/content/lead@aJJjaGunRrwyh9MjQfJt-.md @@ -1,34 +1,7 @@ # lead -In SQL, the `LEAD` function is a kind of window function that allows you to look at a row after a certain row, and use its value in calculations. `LEAD` function returns the value from the next row (or a subsequent row) of the current row in the table. +`LEAD` is a window function in SQL that provides access to a row at a specified offset after the current row within a partition. It's the counterpart to the `LAG` function, allowing you to look ahead in your dataset rather than behind. `LEAD` is useful for comparing current values with future values, calculating forward-looking metrics, or analyzing trends in sequential data. Like `LAG`, it takes arguments for the column to offset, the number of rows to look ahead (default is 1), and an optional default value when the offset exceeds the partition's boundary. -## Usage +Learn more from the following resources: -The `LEAD` function takes three arguments: - -1. `value_expression` - the column or expression whose next value will be returned. -2. `offset` - determines how many rows ahead to retrieve the value from. If it's omitted, then its default value is 1. -3. `default_value` - the value returned when the `LEAD` function navigates past the last row. If it's omitted, it returns NULL. - -The syntax of the `LEAD` function is as follows: - -```sql -LEAD(value_expression, [offset], [default_value]) OVER ([PARTITION BY partition_expression] ORDER BY sort_expression [ASC | DESC]) -``` - -## Example - -Consider a simple example where you have a "sales" table and you want to compare each monthly sale with the sale of the next month. - -```sql -SELECT - month, - sale, - LEAD(sale) OVER (ORDER BY month) NextMonthSale -FROM - sales; -``` - -This SQL command will give an output where each row displays the sale of the current month and the sale amount of the next month. - -Please note that 'LEAD' function might return 'NULL' if there are no subsequent rows in window frame to fetch. \ No newline at end of file +- [@article@SQL LEAD](https://www.codecademy.com/resources/docs/sql/window-functions/lead) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/left-join@X9cJJ8zLZCF2cOoqxwFfY.md b/src/data/roadmaps/sql/content/left-join@X9cJJ8zLZCF2cOoqxwFfY.md index 6523aba53..8fb0c7ca8 100644 --- a/src/data/roadmaps/sql/content/left-join@X9cJJ8zLZCF2cOoqxwFfY.md +++ b/src/data/roadmaps/sql/content/left-join@X9cJJ8zLZCF2cOoqxwFfY.md @@ -1,30 +1,7 @@ # LEFT JOIN -The SQL LEFT JOIN combines rows from two or more tables based on a related column between them and returns all rows from the left table (table1) and the matched rows from the right table (table2). If there is no match, the result is `NULL` on the right side. +A `LEFT JOIN` in SQL returns all rows from the left (first) table and the matching rows from the right (second) table. If there's no match in the right table, `NULL` values are returned for those columns. This join type is useful when you want to see all records from one table, regardless of whether they have corresponding entries in another table. `LEFT JOIN`s are commonly used for finding missing relationships, creating reports that include all primary records, or when working with data where not all entries have corresponding matches in related tables. -## Syntax -``` -SELECT column_name(s) -FROM table1 -LEFT JOIN table2 -ON table1.column_name = table2.column_name; -``` +Learn more from the following resources: -## How SQL LEFT JOIN Works - -The `LEFT JOIN` keyword returns all records from the left table (table1), and the matched records from the right table (table2). The result is `NULL` from the right side, if there is no match. - -![LEFT JOIN Diagram](https://www.w3schools.com/sql/img_leftjoin.gif) - -## SQL LEFT JOIN Example - -Let's assume we have two tables: `Orders` and `Customers`. - -```sql -SELECT Orders.OrderID, Customers.CustomerName -FROM Orders -LEFT JOIN Customers -ON Orders.CustomerID = Customers.CustomerID; -``` - -This SQL statement would return all OrderID and the matching CustomerName. If there is no match, the result is `NULL`. \ No newline at end of file +- [@article@SQL LEFT JOIN](https://www.w3schools.com/sql/sql_join_left.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/length@RH8DLiQpDUWqw3U1522q5.md b/src/data/roadmaps/sql/content/length@RH8DLiQpDUWqw3U1522q5.md index 0bbf66797..7c43a07e6 100644 --- a/src/data/roadmaps/sql/content/length@RH8DLiQpDUWqw3U1522q5.md +++ b/src/data/roadmaps/sql/content/length@RH8DLiQpDUWqw3U1522q5.md @@ -1,53 +1,7 @@ # LENGTH -In SQL, `LENGTH` is a built-in function that allows you to find the number of characters in a string or the length of a string. +The `LENGTH` function in SQL returns the number of characters in a string. It's used to measure the size of text data, which can be helpful for data validation, formatting, or analysis. In some database systems, `LENGTH` may count characters differently for multi-byte character sets. Most SQL dialects support `LENGTH`, but some may use alternative names like LEN (in SQL Server) or `CHAR_LENGTH`. This function is particularly useful for enforcing character limits, splitting strings, or identifying anomalies in string data. -Syntax: +Learn more from the following resources: -```sql -LENGTH ( string ) -``` -Here, `string` can be any string literal, column or expression resulting in a string. - -## Examples - -Consider an "employees" table: - -| id | first_name | last_name | -|----|------------|-----------| -| 1 | John | Doe | -| 2 | Jane | Smith | -| 3 | Alice | Murphy | - -To compute the length of the first_name field for all records, use the following SQL statement: -```sql -SELECT first_name, LENGTH(first_name) as length_of_first_name -FROM employees; -``` -Output: - -| first_name | length_of_first_name | -|------------|----------------------| -| John | 4 | -| Jane | 4 | -| Alice | 5 | - -## Usage with DISTINCT -`LENGTH` can also be used in conjunction with `DISTINCT` to find the number of distinct lengths of a specific field. -```sql -SELECT DISTINCT LENGTH(first_name) as distinct_length_of_first_name -FROM employees; -``` - -## Usage with WHERE Clause - -It can work in the WHERE clause to return only those records where the length of a specific field meets a certain condition. -```sql -SELECT * -FROM employees -WHERE LENGTH(first_name) > 4; -``` - -Do note that the `LENGTH` function may return different results in different SQL systems due to character set and collation differences. In some systems, `LENGTH()` returns length in characters while in others it could return length in bytes. - -For example, MySQL has separate `CHAR_LENGTH()` and `LENGTH()` functions. `CHAR_LENGTH()` returns the length of the string in characters, while `LENGTH()` in MySQL returns the length of the string in bytes. This can make a difference if your string includes multibyte characters (like UTF-8). In such scenarios, it's always recommended to be sure how your specific SQL system implements `LENGTH` function. \ No newline at end of file +- [@article@How to Check the Length of a String in SQL](https://learnsql.com/cookbook/how-to-check-the-length-of-a-string-in-sql/) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/lower@knTG6pAq2mYP24WMa29xI.md b/src/data/roadmaps/sql/content/lower@knTG6pAq2mYP24WMa29xI.md index d608bd836..778b950c9 100644 --- a/src/data/roadmaps/sql/content/lower@knTG6pAq2mYP24WMa29xI.md +++ b/src/data/roadmaps/sql/content/lower@knTG6pAq2mYP24WMa29xI.md @@ -1,38 +1,7 @@ # LOWER -`LOWER` is a built-in function in SQL used to return all uppercase character(s) in a string to lowercase. It can be quite useful when performing case-insensitive comparisons or searches in your queries. +The `LOWER` function in SQL converts all characters in a specified string to lowercase. It's a string manipulation function that takes a single argument (the input string) and returns the same string with all alphabetic characters converted to their lowercase equivalents. `LOWER` is useful for standardizing data, making case-insensitive comparisons, or formatting output. It doesn't affect non-alphabetic characters or numbers in the string. `LOWER` is commonly used in data cleaning, search operations, and ensuring consistent data representation across different systems. -## Syntax: +Learn more from the following resources: -The basic syntax for `LOWER` in SQL is: - -``` -LOWER(string) -``` - -Here, 'string' can be a literal string or a column of a table, and the function will return the string with all alphabetic characters converted to lowercase. - -## Example: - -Let's take a look at a very basic example. Assuming we have the following string "SQL is BAE!" and we want to convert it to lower case. - -```sql -SELECT LOWER('SQL is BAE!') AS LowerCaseString; -``` - -Output: -```sql -lowercasestring ----------------- -sql is bae! -``` - -If you are using a column from a table, let's say we have a table 'students' with a column 'Name' and we want to convert all the entries in that column to lowercase: - -```sql -SELECT LOWER(Name) AS LowerCaseName FROM students; -``` - -Here, the LOWER function will return all the names from the 'Name' column in the 'students' table in their lowercase forms. - -Remember, the `LOWER` function doesn't affect the numbers and special characters in the input string, it only converts uppercase alphabetical characters to lowercase. \ No newline at end of file +- [@article@How to change text to lowercase in SQL](https://learnsql.com/cookbook/how-to-change-text-to-lowercase-in-sql/) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/managing-indexes@NtxGd6Vx-REBclry7lZuE.md b/src/data/roadmaps/sql/content/managing-indexes@NtxGd6Vx-REBclry7lZuE.md index 2e82a0058..46c4dbf84 100644 --- a/src/data/roadmaps/sql/content/managing-indexes@NtxGd6Vx-REBclry7lZuE.md +++ b/src/data/roadmaps/sql/content/managing-indexes@NtxGd6Vx-REBclry7lZuE.md @@ -1,48 +1,7 @@ # Managing Indexes -Indexes can drastically speed up data retrieval in SQL databases by allowing the database to immediately locate the data needed without having to scan the entire database. However, these additional data structures also consume storage, and maintaining them can slow down any create, update, or delete operations, hence the need to manage them appropriately. +Managing indexes in SQL involves creating, modifying, and dropping indexes to optimize database performance. This process includes identifying columns that benefit from indexing (frequently queried or used in JOIN conditions), creating appropriate index types (e.g., single-column, composite, unique), and regularly analyzing index usage and effectiveness. Database administrators must balance the improved query performance that indexes provide against the overhead they introduce for data modification operations. Proper index management also includes periodic maintenance tasks like rebuilding or reorganizing indexes to maintain their efficiency as data changes over time. -## Creating Indexes +Learn more from the following resources: -To create an index, you use the `CREATE INDEX` command followed by the index name, the table name, and the columns you want to use in the index. - -```sql -CREATE INDEX index_name -ON table_name(column_name); -``` - -## Removing Indexes - -If an index is no longer required or if it's causing performance issues due to too much storage consumption, it can be dropped using the `DROP INDEX` command. - -```sql -DROP INDEX index_name; -``` - -## Listing Indexes - -You can get a list of all the indexes on a table using the `SHOW INDEXES` command. - -```sql -SHOW INDEXES IN table_name; -``` - -Remember that most SQL databases automatically create indexes for primary keys, and they do not need to be managed manually. - -## Modifying Indexes - -Modifying an existing index often means dropping the old index and creating a new one. PostgreSQL, MySQL, and MS SQL Server provide a way to reindex without dropping and recreating them manually. - -For example, in PostgreSQL: - -```sql -REINDEX INDEX index_name; -``` - -## Indexes and Performance - -While indexes can improve read speed, they also slow down write operations because each write must also update the index. That's why it's essential to find a balance between the number of indexes and database performance. Too many indexes can negatively impact performance. - -Therefore, you should only create indexes when they are likely to be needed and when they will have a significant impact on improving query performance. You can use the SQL Server Profiler, MySQL's slow query log, or other database-specific tools to identify the queries that are running slow, and then create indexes to optimize those queries. Regularly monitor your database performance to make sure that the indexes are still needed and that they are providing the expected improvements. - -Add indexes strategically and purposefully, and do regular cleanups of any unnecessary indexes. \ No newline at end of file +- [@article@SQL Server Indexes](https://www.sqlservercentral.com/articles/sql-server-indexes) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/max@YqDJq3fPxUZlwsdq0kJg7.md b/src/data/roadmaps/sql/content/max@YqDJq3fPxUZlwsdq0kJg7.md index f744089f2..7ee3d2a90 100644 --- a/src/data/roadmaps/sql/content/max@YqDJq3fPxUZlwsdq0kJg7.md +++ b/src/data/roadmaps/sql/content/max@YqDJq3fPxUZlwsdq0kJg7.md @@ -1,37 +1,7 @@ # MAX -The `MAX()` function in SQL is used to return the maximum value of an expression in a SELECT statement. +`MAX` is an aggregate function in SQL that returns the highest value in a set of values. It can be used with numeric, date, or string data types, selecting the maximum value from a specified column. `MAX` is often used in combination with `GROUP` BY to find the highest value within each group. This function is useful for various data analysis tasks, such as finding the highest salary, the most recent date, or the alphabetically last name in a dataset. -It can be used for numeric, character, and datetime column data types. If there are null values, then they are not considered for comparison. +Learn more from the following resources: -## Syntax - -```sql -SELECT MAX(column_name) -FROM table_name -WHERE condition; -``` - -In this syntax, the `column_name` argument is the column in the `table_name` that you wish to find the maximum value of. - -## Example - -Consider the following Employee table: - -| ID | NAME | SALARY | -|----|----------|--------| -| 1 | John | 1000 | -| 2 | Robert | 2000 | -| 3 | Jim | 3000 | -| 4 | Jessica | 2500 | - -To find the highest salary amongst all the employees, you would use the `MAX()` function as follows: - -```sql -SELECT MAX(SALARY) AS "Highest Salary" -FROM Employee; -``` - -The above SQL returns `3000` as it’s the highest salary in the Employee table. - -Warning: SQL `MAX()` function will only return a single row as a result. If multiple rows hold the highest value and if you want to get all these rows, you should not use `MAX()`. A better option would be sorting the column and then `LIMIT` the result just to the first row. \ No newline at end of file +- [@article@MAX](https://www.techonthenet.com/sql/max.php) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/min@bFEYMlqPZtTUYtDQxqHzT.md b/src/data/roadmaps/sql/content/min@bFEYMlqPZtTUYtDQxqHzT.md index f89c7c8e4..345620552 100644 --- a/src/data/roadmaps/sql/content/min@bFEYMlqPZtTUYtDQxqHzT.md +++ b/src/data/roadmaps/sql/content/min@bFEYMlqPZtTUYtDQxqHzT.md @@ -1,57 +1,7 @@ # MIN -`MIN` is an SQL aggregate function used to return the smallest value in a selected column. It is useful in querying tables where users want to identify the smallest or least available value in datasets. `MIN` ignores any null values in the dataset. +`MIN` is an aggregate function in SQL that returns the lowest value in a set of values. It works with numeric, date, or string data types, selecting the minimum value from a specified column. Often used in conjunction with `GROUP BY`, `MIN` can find the smallest value within each group. This function is useful for various data analysis tasks, such as identifying the lowest price, earliest date, or alphabetically first name in a dataset. -Syntax: +Learn more from the following resources: -```sql -SELECT MIN(column_name) -FROM table_name -WHERE condition; -``` - -In the case where `column_name` belongs to a numeric data type (Integers, Float, etc.), `MIN` returns the smallest numeric value in the column. - -If `column_name` belongs to datetime types (Date, Time, etc.), `MIN` returns the earliest date or time. - -If `column_name` belongs to string types (Char, Text, etc.), `MIN` returns the lowest value in lexicographic order (similar to alphabetic order). - -## Examples: - -Consider a table, named `Orders`, with the following layout: - -| OrderID | CustomerID | OrderDate | -|---------|-------------|------------| -| 1 | C01 | 2020-10-10 | -| 2 | C02 | 2020-09-05 | -| 3 | C01 | 2020-08-21 | - -1. To find the earliest order date in the `Orders` table, the `MIN` function is used in the following way: - -```sql -SELECT MIN(OrderDate) AS EarliestOrder -FROM Orders; -``` - -The result of this query will be `2020-08-21`. - -2. Suppose we have a Prices table with items and their prices. To find the lowest price, use: - -```sql -SELECT MIN(price) AS LowestPrice -FROM Prices; -``` - -This query will return the smallest value in the price column. - -One important usage is when it is used along with the `GROUP BY` clause to find the minimum value in each group. - -Example, to find the earliest order date for each customer: - -```sql -SELECT CustomerID, MIN(OrderDate) AS EarliestOrder -FROM Orders -GROUP BY CustomerID; -``` - -This query will return the earliest order date for each customer. \ No newline at end of file +- [@article@SQL MAX & MIN](https://www.programiz.com/sql/min-and-max) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/mod@OUw--8zEq6lk5-6oySVHe.md b/src/data/roadmaps/sql/content/mod@OUw--8zEq6lk5-6oySVHe.md index aea1da18b..a960d0748 100644 --- a/src/data/roadmaps/sql/content/mod@OUw--8zEq6lk5-6oySVHe.md +++ b/src/data/roadmaps/sql/content/mod@OUw--8zEq6lk5-6oySVHe.md @@ -1,33 +1,7 @@ # MOD -The SQL `MOD()` function is a mathematical function that returns the remainder of the values from the division of two numbers. It calculates the modulo operation. This function is very useful when you want to find the remainder value after one number is divided by another. +The `MOD` function in SQL calculates the remainder when one number is divided by another. It takes two arguments: the dividend and the divisor. `MOD` returns the remainder of the division operation, which is useful for various mathematical operations, including checking for odd/even numbers, implementing cyclic behaviors, or distributing data evenly. The syntax and exact behavior may vary slightly between different database systems, with some using the % operator instead of the `MOD` keyword. -## Syntax +Learn more from the following resources: -The syntax of the MOD function in SQL is: -```sql -MOD(expression1, expression2) -``` - -- `Expression1` and `Expression2` are the values that you want to apply the function to. - -## Basic Usage - -For instance, if you want to find the remainder of the division of 15 by 4 you would write: -```sql -SELECT MOD(15, 4) as result; -``` -The result would be `3` because 3 is the remainder after dividing 15 by 4. - -## Usage with Table Columns - -The `MOD()` function can also be applied to table columns. Let's imagine that you have a table named "Orders" with an "OrderNumber" column and you want to find the remainder of every order number when divided by 7, you would do: - -```sql -SELECT OrderNumber, MOD(OrderNumber, 7) as result -FROM Orders; -``` - -This will return a list of all order numbers, along with the remainder when each order number is divided by 7. - -Keep in mind that the SQL `MOD()` function may not work in the same way, or might not support all features, in every SQL database. Always refer to the documentation specific to the SQL database you are using. \ No newline at end of file +- [@article@MOD](https://www.w3schools.com/sql/func_mysql_mod.asp) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/modifying-views@3eE-l-P93nOXoWfLr8PSW.md b/src/data/roadmaps/sql/content/modifying-views@3eE-l-P93nOXoWfLr8PSW.md index d8f0aaf8d..a823e5e3a 100644 --- a/src/data/roadmaps/sql/content/modifying-views@3eE-l-P93nOXoWfLr8PSW.md +++ b/src/data/roadmaps/sql/content/modifying-views@3eE-l-P93nOXoWfLr8PSW.md @@ -1,82 +1,11 @@ # Modifying Views -In SQL, you can modify a VIEW in two ways: +In SQL, you can modify a `VIEW` in two ways: -- Using CREATE OR REPLACE VIEW: This command helps you modify a VIEW but keeps the VIEW name intact. This is beneficial when you want to change the definition of the VIEW but do not want to change the VIEW name. +- Using `CREATE` OR `REPLACE VIEW`: This command helps you modify a VIEW but keeps the VIEW name intact. This is beneficial when you want to change the definition of the `VIEW` but do not want to change the VIEW name. -- Using the DROP VIEW and then CREATE VIEW: In this method, you first remove the VIEW using the DROP VIEW command and then recreate the view using the new definition with the CREATE VIEW command. +- Using the `DROP VIEW` and then `CREATE VIEW`: In this method, you first remove the `VIEW` using the `DROP VIEW` command and then recreate the view using the new definition with the `CREATE VIEW` command. -## Modifying VIEW Using CREATE OR REPLACE VIEW +Learn more from the following resources: -Syntax: - -```sql -CREATE OR REPLACE VIEW view_name AS -SELECT column1, column2, ... -FROM table_name -WHERE condition; -``` - -Example: - -```sql -CREATE OR REPLACE VIEW customer_view AS -SELECT customer_name, country -FROM customers -WHERE country='USA'; -``` -In this example, 'customer_view' will show the names and countries of customers only from the USA. - -## Modifying VIEW Using DROP VIEW and CREATE VIEW - -Syntax: -Drop the VIEW: -```sql -DROP VIEW view_name; -``` -Create a new VIEW: -```sql -CREATE VIEW view_name AS -SELECT column1, column2, ... -FROM table_name -WHERE condition; -``` - -Example: -Drop the VIEW -```sql -DROP VIEW customer_view; -``` -Create a new VIEW: -```sql -CREATE VIEW customer_view AS -SELECT customer_name, country -FROM customers -WHERE country='UK'; -``` -In this example, we first removed 'customer_view'. Then, we created it again with the new definition where it now shows the names and countries of the customers only from the UK. - -**CAUTION**: If other views, stored procedures, or programs depend on this view, they will be affected after you drop the view. For this reason, using CREATE OR REPLACE VIEW is generally safer. - -## Modifying Data through VIEW - -In some cases, you can modify the data of the underlying tables via a VIEW. - -Syntax: - -```sql -UPDATE view_name -SET column1 = value1, column2 = value2, ... -WHERE condition; -``` - -Example: - -```sql -UPDATE customer_view -SET country = 'USA' -WHERE customer_name = 'John Doe'; -``` -This command will update the country of 'John Doe' to 'USA' in both the VIEW and the underlying table. - -However, not every VIEW is updatable. You can only modify the data if the VIEW you're modifying is a simple VIEW that returns results from a single table without any aggregation or complex clauses. If you attempt to modify a complex view (i.e., it includes JOIN, GROUP BY, HAVING, DISTINCT), you will get an error. \ No newline at end of file +- [@article@Modify Views in SQL Server](https://www.sqlshack.com/create-view-sql-modifying-views-in-sql-server/) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/nested-subqueries@xkPJ2MYiXmzC4yqQWyB_7.md b/src/data/roadmaps/sql/content/nested-subqueries@xkPJ2MYiXmzC4yqQWyB_7.md index fa11ba0e5..3452870e7 100644 --- a/src/data/roadmaps/sql/content/nested-subqueries@xkPJ2MYiXmzC4yqQWyB_7.md +++ b/src/data/roadmaps/sql/content/nested-subqueries@xkPJ2MYiXmzC4yqQWyB_7.md @@ -4,39 +4,6 @@ In SQL, a subquery is a query that is nested inside a main query. If a subquery Nested subqueries can get complicated quickly, but they are essential for performing complex database tasks. -## Basic Syntax: +Learn more from the following resources: -```sql -SELECT column_name [, column_name ] -FROM table1 [, table2 ] -WHERE column_name OPERATOR - (SELECT column_name [, column_name ] - FROM table1 [, table2 ] - [WHERE]) -``` - -## How They Work: - -In a nested subquery, the inner subquery will run first and its result will be used to run the outer query. - -## Example: - -Here's an example where we want to find the customer names who made orders above the average order amount. - -```sql -SELECT CustomerName,Country -FROM Customers -WHERE CustomerID IN - (SELECT CustomerID - FROM Orders - WHERE Amount>(SELECT AVG(Amount) - FROM Orders)) -``` - -In the above code: - -- The innermost query calculates the average order amount. -- The middle subquery finds the `CustomerID`s from the `Orders` table where the order `Amount` is greater than the average. -- The outer query then gets the `CustomerName` from the `Customers` table where the `CustomerID` is in the list of `CustomerID`s fetched from the middle subquery. - -These are the basic aspects of nested subqueries in SQL. They can go as deep as the task requires, but keep in mind that too many nested subqueries can cause performance issues. \ No newline at end of file +- [@article@Nested Subqueries](https://www.studysmarter.co.uk/explanations/computer-science/databases/nested-subqueries-in-sql/) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/not-null@M4M_-vjM9GNy0NmXZneDA.md b/src/data/roadmaps/sql/content/not-null@M4M_-vjM9GNy0NmXZneDA.md index f45812c8f..fa5e17e10 100644 --- a/src/data/roadmaps/sql/content/not-null@M4M_-vjM9GNy0NmXZneDA.md +++ b/src/data/roadmaps/sql/content/not-null@M4M_-vjM9GNy0NmXZneDA.md @@ -4,37 +4,6 @@ The `NOT NULL` constraint in SQL ensures that a column cannot have a NULL value. For instance, if you're designing a table for employee data, you might want to ensure that the employee's `id` and `name` are always provided. In this case, you'd use the `NOT NULL` constraint. -## Creating a table with NOT NULL +Learn more from the following resources: -Here's an example of how you would define a `NOT NULL` constraint when creating a table: - -```sql -CREATE TABLE Employees ( - ID int NOT NULL, - Name varchar(255) NOT NULL, - Age int, - Address varchar(255) -); -``` - -In this example, the `ID` and `Name` fields are mandatory for each record. - -## Adding NOT NULL to an existing table - -You can also add a `NOT NULL` constraint to an existing table using the `ALTER TABLE` statement. However, make sure there are no NULL values in the column before adding the `NOT NULL` constraint. - -Here's an example: - -```sql -ALTER TABLE Employees -MODIFY Address varchar(255) NOT NULL; -``` - -This command will modify the table `Employees` and set the `Address` column to be `NOT NULL`. - -**Note:** In some SQL systems like PostgreSQL, you use the `ALTER TABLE` command followed by `SET NOT NULL`. - ---- - -Be aware that if you try to insert a record without a value for a `NOT NULL` column, the database will return an error and the operation will fail. -Ensure data compatibility before setting the `NOT NULL` constraint. \ No newline at end of file +- [@article@SQL IS NULL and IS NOT NULL](https://www.programiz.com/sql/is-null-not-null) \ No newline at end of file diff --git a/src/data/roadmaps/sql/content/nullif@KI6vngoYcHsnpIk8ErhhS.md b/src/data/roadmaps/sql/content/nullif@KI6vngoYcHsnpIk8ErhhS.md index 5efd161ce..ac5e25ac8 100644 --- a/src/data/roadmaps/sql/content/nullif@KI6vngoYcHsnpIk8ErhhS.md +++ b/src/data/roadmaps/sql/content/nullif@KI6vngoYcHsnpIk8ErhhS.md @@ -1,40 +1,7 @@ # NULLIF -`NULLIF` is a built-in conditional function in SQL Server. The `NULLIF` function compares two expressions and returns NULL if they are equal or the first expression if they are not. +`NULLIF` is an SQL function that compares two expressions and returns NULL if they are equal, otherwise it returns the first expression. It's particularly useful for avoiding division by zero errors or for treating specific values as `NULL` in calculations or comparisons. `NULLIF` takes two arguments and is often used in combination with aggregate functions or in `CASE` statements to handle special cases in data processing or reporting. -## Syntax +Learn more from the following resources: -Here's the syntax of the `NULLIF` function: - -```sql -NULLIF(expression1, expression2); -``` -`NULLIF` compares `expression1` to `expression2`. If `expression1` and `expression2` are equal, the function returns NULL. Otherwise, it returns `expression1`. Both expressions must have the same data type. - -## Example - -Consider the following example: - -```sql -SELECT - first_name, - last_name, - NULLIF(email, 'NA') AS email -FROM - users; -``` -In this SQL Server `NULLIF` function example, if the field email is 'NA', then NULL would be returned. Otherwise the actual `email` field value is returned. - -In another example, consider a division operation: - -```sql -SELECT - avg_salary, - NULLIF(avg_salary, 0) AS avg_salary_no_zero -FROM - positions; -``` - -In this SQL Server `NULLIF` function example, if `avg_salary` field is 0, then NULL would be returned. This is useful to avoid division by zero errors. - -In nutshell, the SQL `NULLIF` function can be handy in many scenarios such as to circumvent division by zero errors or to translate known sentinel values into NULL values that can be handled by SQL's NULL handling functions. \ No newline at end of file +- [@article@NULLIF](https://www.w3schools.com/sql/func_sqlserver_nullif.asp) \ No newline at end of file