Add content to SQL Roadmap (#6873)
* complete sql content * add links to topics --------- Co-authored-by: Kamran Ahmed <kamranahmed.se@gmail.com>pull/6972/head
parent
f96201cbbd
commit
1859e94184
91 changed files with 281 additions and 2075 deletions
@ -1 +1,7 @@ |
||||
# Delete |
||||
# Delete |
||||
|
||||
DELETE is an SQL statement used to remove one or more rows from a table. It allows you to specify which rows to delete using a WHERE clause, or delete all rows if no condition is provided. DELETE is part of the Data Manipulation Language (DML) and is used for data maintenance, removing outdated or incorrect information, or implementing business logic that requires data removal. When used without a WHERE clause, it empties the entire table while preserving its structure, unlike the TRUNCATE command. |
||||
|
||||
Learn more from the following resources: |
||||
|
||||
- [@article@DELETE](https://www.w3schools.com/sql/sql_delete.asp) |
@ -1,7 +1,8 @@ |
||||
# GROUP BY |
||||
|
||||
GROUP BY is an SQL clause used in SELECT statements to arrange identical data into groups. It's typically used with aggregate functions (like COUNT, SUM, AVG) to perform calculations on each group of rows. GROUP BY collects data across multiple records and groups the results by one or more columns, allowing for analysis of data at a higher level of granularity. This clause is fundamental for generating summary reports, performing data analysis, and creating meaningful aggregations of data in relational databases. |
||||
`GROUP BY` is an SQL clause used in `SELECT` statements to arrange identical data into groups. It's typically used with aggregate functions (like `COUNT`, `SUM`, `AVG`) to perform calculations on each group of rows. `GROUP BY` collects data across multiple records and groups the results by one or more columns, allowing for analysis of data at a higher level of granularity. This clause is fundamental for generating summary reports, performing data analysis, and creating meaningful aggregations of data in relational databases. |
||||
|
||||
Learn more from the following resources: |
||||
|
||||
- [@article@SQL GROUP BY](https://www.programiz.com/sql/group-by) |
||||
- [@article@SQL GROUP BY](https://www.programiz.com/sql/group-by) |
||||
- [@video@Advanced Aggregate Functions in SQL](https://www.youtube.com/watch?v=nNrgRVIzeHg) |
@ -1,9 +1,12 @@ |
||||
# HAVING |
||||
|
||||
`HAVING` is a clause in SQL that allows you to filter result sets in a `GROUP BY` clause. It is used to mention conditions on the groups being selected. In other words, `HAVING` is mainly used with the `GROUP BY` clause to filter the results that a `GROUP BY` returns. |
||||
The `HAVING` clause is used in combination with the `GROUP BY` clause to filter the results of `GROUP BY`. It is used to mention conditions on the group functions, like `SUM`, `COUNT`, `AVG`, `MAX` or `MIN`. |
||||
|
||||
It’s similar to a `WHERE` clause, but operates on the results of a grouping. The `WHERE` clause places conditions on the selected columns, whereas the `HAVING` clause places conditions on groups created by the `GROUP BY` clause. |
||||
It's important to note that where `WHERE` clause introduces conditions on individual rows, `HAVING` introduces conditions on groups created by the `GROUP BY` clause. |
||||
|
||||
Also note, `HAVING` applies to summarized group records, whereas `WHERE` applies to individual records. |
||||
|
||||
Learn more from the following resources: |
||||
|
||||
- [@article@SQL HAVING Clause](https://www.programiz.com/sql/having) |
||||
- [@article@SQL HAVING Clause](https://www.programiz.com/sql/having) |
||||
- [@video@HAVING Clause](https://www.youtube.com/watch?v=tYBOMw7Ob8E) |
@ -1 +1,8 @@ |
||||
# Insert |
||||
# Insert |
||||
|
||||
The "INSERT" statement is used to add new rows of data to a table in a database. There are two main forms of the INSERT command: `INSERT INTO` which, if columns are not named, expects a full set of columns, and `INSERT INTO table_name (column1, column2, ...)` where only named columns will be filled with data. |
||||
|
||||
Learn more from the following resources: |
||||
|
||||
- [@article@SQL INSERT](https://www.w3schools.com/sql/sql_insert.asp) |
||||
- [@video@SQL INSERT Statement](https://www.youtube.com/watch?v=Yp1MKeIG-M4) |
@ -1,61 +1,8 @@ |
||||
# Operators |
||||
|
||||
SQL operators are used to perform operations like comparisons and arithmetic calculations. They are very crucial in |
||||
forming queries. SQL operators are divided into the following types: |
||||
SQL operators are symbols or keywords used to perform operations on data within a database. They are essential for constructing queries that filter, compare, and manipulate data. Common types of operators include arithmetic operators (e.g., `+`, `-`, `*`, `/`), which perform mathematical calculations; comparison operators (e.g., `=`, `!=`, `<`, `>`), used to compare values; logical operators (e.g., `AND`, `OR`, `NOT`), which combine multiple conditions in a query; and set operators (e.g., `UNION`, `INTERSECT`, `EXCEPT`), which combine results from multiple queries. These operators enable precise control over data retrieval and modification. |
||||
|
||||
1. **Arithmetic Operators**: These are used to perform mathematical operations. Here is a list of these operators: |
||||
Learn more from the following resources: |
||||
|
||||
- `+` : Addition |
||||
- `-` : Subtraction |
||||
- `*` : Multiplication |
||||
- `/` : Division |
||||
- `%` : Modulus |
||||
|
||||
Example: |
||||
|
||||
```sql |
||||
SELECT product, price, (price * 0.18) as tax |
||||
FROM products; |
||||
``` |
||||
|
||||
2. **Comparison Operators**: These are used in the where clause to compare one expression with another. Some of these |
||||
operators are: |
||||
|
||||
- `=` : Equal |
||||
- `!=` or `<>` : Not equal |
||||
- `>` : Greater than |
||||
- `<` : Less than |
||||
- `>=`: Greater than or equal |
||||
- `<=`: Less than or equal |
||||
|
||||
Example: |
||||
|
||||
```sql |
||||
SELECT name, age |
||||
FROM students |
||||
WHERE age > 18; |
||||
``` |
||||
|
||||
3. **Logical Operators**: They are used to combine the result set of two different component conditions. These include: |
||||
|
||||
- `AND`: Returns true if both components are true. |
||||
- `OR` : Returns true if any one of the component is true. |
||||
- `NOT`: Returns the opposite boolean value of the condition. |
||||
|
||||
Example: |
||||
|
||||
```sql |
||||
SELECT * |
||||
FROM employees |
||||
WHERE salary > 50000 AND age < 30; |
||||
``` |
||||
|
||||
4. **Bitwise Operators**: These perform bit-level operations on the inputs. Here is a list of these operators: |
||||
|
||||
- `&` : Bitwise AND |
||||
- `|` : Bitwise OR |
||||
- `^` : Bitwise XOR |
||||
|
||||
Bitwise operators are much less commonly used in SQL than the other types of operators. |
||||
|
||||
Remember, the datatype of the result is dependent on the types of the operands. |
||||
- [@article@SQL Operators](https://www.w3schools.com/sql/sql_operators.asp) |
||||
- [@article@SQL Operators: 6 Different Types](https://www.dataquest.io/blog/sql-operators/) |
@ -1,58 +1,8 @@ |
||||
# Optimizing Joins |
||||
|
||||
Query optimization for joins is an essential aspect in improving the execution speed of your SQL commands and reduce the response time. Joins, particularly the ones involving multiple tables, can be quite costly in terms of database performance. Here are some methods to optimize joins in SQL: |
||||
Optimizing joins in SQL involves techniques to improve the performance of queries that combine data from multiple tables. Key strategies include using appropriate join types (e.g., `INNER JOIN` for matching rows only, `LEFT JOIN` for all rows from one table), indexing the columns used in join conditions to speed up lookups, and minimizing the data processed by filtering results with `WHERE` clauses before the join. Additionally, reducing the number of joins, avoiding unnecessary columns in the `SELECT` statement, and ensuring that the join conditions are based on indexed and selective columns can significantly enhance query efficiency. Proper join order and using database-specific optimization hints are also important for performance tuning. |
||||
|
||||
## 1. Minimize the Number of Tables in the Join |
||||
Learn more from the following resources: |
||||
|
||||
Try to keep the number of tables in each join operation as low as possible. Remove any tables which are not necessary to retrieve the requested data. |
||||
|
||||
```sql |
||||
SELECT Customers.CustomerName, Orders.OrderID |
||||
FROM Customers |
||||
JOIN Orders |
||||
ON Customers.CustomerID = Orders.CustomerID |
||||
ORDER BY Customers.CustomerName; |
||||
``` |
||||
|
||||
## 2. Check the Order of Tables in the Join |
||||
|
||||
The order in which tables are joined can have a considerable impact on the execution time. As a general rule, join the tables that have the most rows last. If you are joining more than two tables, and aren’t certain of the best order, you can try different orders to see which gives the best performance. |
||||
|
||||
```sql |
||||
SELECT * |
||||
FROM Table1 -- smallest table |
||||
JOIN Table2 ON Table1.ID = Table2.ID -- larger table |
||||
JOIN Table3 ON Table1.ID = Table3.ID -- largest table |
||||
``` |
||||
|
||||
## 3. Always Use Indexes |
||||
|
||||
Using indexes helps improve the speed at which SQL can execute a join. Indexes are particularly useful if your join involves columns that are often involved in where clauses or sort operations. SQL can utilize indexes to quickly locate the rows it needs, and this can drastically improve performance. |
||||
|
||||
```sql |
||||
CREATE INDEX idx_columnname |
||||
ON table_name (column_name); |
||||
``` |
||||
|
||||
## 4. Use Subqueries |
||||
|
||||
Sometimes, it would be faster to retrieve the data in multiple steps using subqueries. In the below example, instead of joining, we are retrieving IDs using a subquery and then fetching the data using those IDs. |
||||
|
||||
```sql |
||||
SELECT column_name(s) |
||||
FROM table1 |
||||
WHERE column_name IN (SELECT column_name FROM table2); |
||||
``` |
||||
|
||||
## 5. Use Explicit JOIN Syntax |
||||
|
||||
Use of explicit syntax helps in better understanding of the relations between the tables, thus enabling the SQL execution engine to get optimized plans. |
||||
|
||||
```sql |
||||
SELECT Orders.OrderID, Customers.CustomerName |
||||
FROM Orders |
||||
INNER JOIN Customers |
||||
ON Orders.CustomerID = Customers.CustomerID; |
||||
``` |
||||
|
||||
In conclusion, the optimization of joins is an art that requires some level of knowledge about database design and how SQL works under the hood. A performance-efficient SQL code needs thorough testing and trial-n-run for different scenarios. |
||||
- [@article@How to Optimize a SQL Query with Multiple Joins](https://dezbor.com/blog/optimize-sql-query-with-multiple-joins) |
||||
- [@video@Secret to optimizing SQL queries](https://www.youtube.com/watch?v=BHwzDmr6d7s) |
@ -1,55 +1,8 @@ |
||||
# ORDER BY |
||||
|
||||
The `ORDER BY` clause in SQL is used to sort the result-set from a SELECT statement in ascending or descending order. It sorts the records in ascending order by default. If you want to sort the records in descending order, you have to use the `DESC` keyword. |
||||
The `ORDER BY` clause in SQL is used to sort the result set of a query by one or more columns. By default, the sorting is in ascending order, but you can specify descending order using the `DESC` keyword. The clause can sort by numeric, date, or text values, and multiple columns can be sorted by listing them in the `ORDER BY` clause, each with its own sorting direction. This clause is crucial for organizing data in a meaningful sequence, such as ordering by a timestamp to show the most recent records first, or alphabetically by name. |
||||
|
||||
## Syntax for Ascending Order: |
||||
```sql |
||||
SELECT column1, column2, ... |
||||
FROM table_name |
||||
ORDER BY column1, column2, ... ASC; |
||||
``` |
||||
Here, `ASC` is used for ascending order. If you use `ORDER BY` without `ASC` or `DESC`, `ASC` is used by default. |
||||
Learn more from the following resources: |
||||
|
||||
## Syntax for Descending Order: |
||||
```sql |
||||
SELECT column1, column2, ... |
||||
FROM table_name |
||||
ORDER BY column1, column2, ... DESC; |
||||
``` |
||||
Here, `DESC` is used for descending order. |
||||
|
||||
## Usage Example |
||||
|
||||
Consider the following `Customers` table: |
||||
|
||||
| ID | NAME | AGE | ADDRESS | SALARY | |
||||
|----|-------|-----|-----------|--------| |
||||
| 1 | Ramesh| 32 | Ahmedabad | 2000.0 | |
||||
| 2 | Khilan| 25 | Delhi | 1500.0 | |
||||
| 3 | kaushik | 23 | Kota | 2000.0 | |
||||
| 4 | Chaitali | 25 | Mumbai | 6500.0 | |
||||
| 5 | Hardik | 27 | Bhopal | 8500.0 | |
||||
| 6 | Komal | 22 | MP | 4500.0 | |
||||
|
||||
**Example 1 - Ascending Order:** |
||||
|
||||
Sort the table by the `NAME` column in ascending order: |
||||
```sql |
||||
SELECT * FROM Customers |
||||
ORDER BY NAME ASC; |
||||
``` |
||||
**Example 2 - Descending Order:** |
||||
|
||||
Sort the table by the `SALARY` column in descending order: |
||||
```sql |
||||
SELECT * FROM Customers |
||||
ORDER BY SALARY DESC; |
||||
``` |
||||
**Example 3 - Multiple Columns:** |
||||
|
||||
You can also sort by multiple columns. Sort the table by the `AGE` column in ascending order and then `SALARY` in descending order: |
||||
```sql |
||||
SELECT * FROM Customers |
||||
ORDER BY AGE ASC, SALARY DESC; |
||||
``` |
||||
In this instance, the `ORDER BY` clause first sorts the `Customers` table by the `AGE` column and then sorts the sorted result further by the `SALARY` column. |
||||
- [@article@SQL ORDER BY Keyword](https://www.w3schools.com/sql/sql_orderby.asp) |
||||
- [@video@SQL ORDER BY Sorting Clause](https://www.youtube.com/watch?v=h_HHTNjAgS8) |
@ -1,67 +1,8 @@ |
||||
# Performance Optimization |
||||
|
||||
SQL performance optimization is crucial for accelerating SQL queries and improving overall database performance. Most importantly, it ensures smooth and efficient execution of SQL statements, which can result in better application performance and user experience. |
||||
Performance optimization in SQL involves a set of practices aimed at improving the efficiency and speed of database queries and overall system performance. Key strategies include indexing critical columns to speed up data retrieval, optimizing query structure by simplifying or refactoring complex queries, and using techniques like query caching to reduce redundant database calls. Other practices include reducing the use of resource-intensive operations like `JOINs` and `GROUP BY`, selecting only necessary columns (`SELECT *` should be avoided), and leveraging database-specific features such as partitioning, query hints, and execution plan analysis. Regularly monitoring and analyzing query performance, along with maintaining database health through routine tasks like updating statistics and managing indexes, are also vital to sustaining high performance. |
||||
|
||||
## 1. Indexes |
||||
Learn more from the following resources: |
||||
|
||||
Creating indexes is one of the prominent ways to optimize SQL performance. They accelerate lookup and retrieval of data from a database. |
||||
|
||||
```sql |
||||
CREATE INDEX index_name |
||||
ON table_name (column1, column2, ...); |
||||
``` |
||||
Remember, though indexes speed up data retrieval, they can slow down data modification such as `INSERT`, `UPDATE`, and `DELETE`. |
||||
|
||||
## 2. Avoid SELECT * |
||||
|
||||
Get only the required columns instead of fetching all columns using `SELECT *`. It reduces the amount of data that needs to be read from the disk. |
||||
|
||||
```sql |
||||
SELECT required_column FROM table_name; |
||||
``` |
||||
|
||||
## 3. Use Join Instead of Multiple Queries |
||||
|
||||
Using join clauses can combine rows from two or more tables in a single query based on a related column between them. This reduces the number of queries hitting the database, improving performance. |
||||
|
||||
```sql |
||||
SELECT Orders.OrderID, Customers.CustomerName |
||||
FROM Orders |
||||
INNER JOIN Customers |
||||
ON Orders.CustomerID=Customers.CustomerID; |
||||
``` |
||||
|
||||
## 4. Use LIMIT |
||||
|
||||
If only a certain number of rows are necessary, use the LIMIT keyword to restrict the number of rows returned by the query. |
||||
|
||||
```sql |
||||
SELECT column FROM table LIMIT 10; |
||||
``` |
||||
|
||||
## 5. Avoid using LIKE Operator with Wildcards at the Start |
||||
|
||||
Using wildcard at the start of a query (`LIKE '%search_term'`) can lead to full table scans. |
||||
|
||||
```sql |
||||
SELECT column FROM table WHERE column LIKE 'search_term%'; |
||||
``` |
||||
|
||||
## 6. Optimize Database Schema |
||||
|
||||
Database schema involves how data is organized and should be optimized for better performance. |
||||
|
||||
## 7. Use EXPLAIN |
||||
|
||||
Many databases have 'explain plan' functionality that shows the plan of the database engine to execute the query. |
||||
|
||||
```sql |
||||
EXPLAIN SELECT * FROM table_name WHERE column = 'value'; |
||||
``` |
||||
This can give insight into performance bottlenecks like full table scans, missing indices, etc. |
||||
|
||||
## 8. Denormalization |
||||
|
||||
In some cases, it might be beneficial to denormalize the database to a certain extent to reduce complex joins and queries. Keep in mind that this is usually the last resort and may not always yield the desired results. |
||||
|
||||
Remember, each query and database is unique, so what might work in one scenario might not work in another. It is always crucial to test the queries in a controlled and isolated environment before pushing them into production. |
||||
- [@article@Performance Tuning SQL Queries](https://mode.com/sql-tutorial/sql-performance-tuning) |
||||
- [@article@SQL performance tuning](https://stackify.com/performance-tuning-in-sql-server-find-slow-queries/) |
@ -1,62 +1,8 @@ |
||||
# Pivot and Unpivot Operations |
||||
|
||||
## PIVOT |
||||
Pivot and Unpivot operations in SQL are used to transform and reorganize data, making it easier to analyze in different formats. The `PIVOT` operation converts rows into columns, allowing you to summarize data and present it in a more readable, table-like format. For example, it can take sales data by month and convert the months into individual columns. Conversely, the `UNPIVOT` operation does the opposite—it converts columns back into rows, which is useful for normalizing data that was previously pivoted or to prepare data for certain types of analysis. These operations are particularly useful in reporting and data visualization scenarios, where different perspectives on the same data set are required. |
||||
|
||||
The PIVOT operator is used in SQL to rotate the table data from rows to columns, essentially transforming the data into a matrix format. This operator allows you to create a crosstab view of the data, with selected columns as rows and others as columns, providing a summary view. |
||||
Learn more from the following resources: |
||||
|
||||
Here is a general example of the syntax: |
||||
|
||||
```sql |
||||
SELECT ... |
||||
FROM ... |
||||
PIVOT (aggregate_function(column_to_aggregate) |
||||
FOR column_to_pivot |
||||
IN (list_of_values)) |
||||
``` |
||||
|
||||
__Example__: Let's assume we have a 'Sales' table with 'Year', 'Quarter' and 'Amount' columns. If we want to turn 'Quarter' values into columns, we might use: |
||||
|
||||
```sql |
||||
SELECT * FROM |
||||
( |
||||
SELECT Year, Quarter, Amount |
||||
FROM Sales |
||||
) |
||||
PIVOT |
||||
( |
||||
SUM(Amount) |
||||
FOR Quarter IN ('Q1' 'Q2' 'Q3' 'Q4') |
||||
) |
||||
``` |
||||
|
||||
This would give us each year as a row and each quarter as a column, with the total sales for each quarter in the cells. |
||||
|
||||
## UNPIVOT |
||||
|
||||
The UNPIVOT operator performs the reverse operation to PIVOT, rotating columns into rows. If the columns you're converting have a certain relationship, this can be factored into a single column instead. |
||||
|
||||
Here is a general example of the syntax: |
||||
|
||||
```sql |
||||
SELECT ... |
||||
FROM ... |
||||
UNPIVOT (column_for_values |
||||
FOR column_for_names IN (list_of_columns)) |
||||
``` |
||||
|
||||
__Example__: Conversely, if we want to transform the quarter columns back into rows from the previous 'Sales' pivot table, we would use: |
||||
|
||||
```sql |
||||
SELECT * FROM |
||||
( |
||||
SELECT Year, Q1, Q2, Q3, Q4 |
||||
FROM Sales |
||||
) |
||||
UNPIVOT |
||||
( |
||||
Amount |
||||
FOR Quarter IN (Q1, Q2, Q3, Q4) |
||||
) |
||||
``` |
||||
|
||||
This would result in each combination of year and quarter as a row, with the amount sold in that quarter as the 'Amount' column. Keep in mind, the UNPIVOTed data isn't equivalent to the original data as the original data might have had multiple rows for each year/quarter. |
||||
- [@article@SQL PIVOT](https://builtin.com/articles/sql-pivot) |
||||
- [@article@SQL UNPIVOT](https://duckdb.org/docs/sql/statements/unpivot.html) |
@ -1,52 +1,8 @@ |
||||
# Primary Key |
||||
|
||||
A primary key is a special relational database table field (or combination of fields) designated to uniquely identify all table records. |
||||
A primary key in SQL is a unique identifier for each record in a database table. It ensures that each row in the table is uniquely identifiable, meaning no two rows can have the same primary key value. A primary key is composed of one or more columns, and it must contain unique values without any `NULL` entries. The primary key enforces entity integrity by preventing duplicate records and ensuring that each record can be precisely located and referenced, often through foreign key relationships in other tables. Using a primary key is fundamental for establishing relationships between tables and maintaining the integrity of the data model. |
||||
|
||||
A primary key's main features are: |
||||
Learn more from the following resources: |
||||
|
||||
- It must contain a unique value for each row of data. |
||||
- It cannot contain null values. |
||||
|
||||
## Usage of Primary Key |
||||
|
||||
You define a primary key for a table using the `PRIMARY KEY` constraint. A table can have only one primary key. You can define a primary key in SQL when you create or modify a table. |
||||
|
||||
## Create Table With Primary Key |
||||
|
||||
In SQL, you can create a table with a primary key by using `CREATE TABLE` syntax. |
||||
|
||||
```sql |
||||
CREATE TABLE Employees ( |
||||
ID INT PRIMARY KEY, |
||||
NAME TEXT, |
||||
AGE INT, |
||||
ADDRESS CHAR(50) |
||||
); |
||||
``` |
||||
|
||||
In this example, `ID` is the primary key which must consist of unique values and can't be null. |
||||
|
||||
## Modify Table to Add Primary Key |
||||
|
||||
If you want to add a primary key to an existing table, you can use `ALTER TABLE` syntax. |
||||
|
||||
```sql |
||||
ALTER TABLE Employees |
||||
ADD PRIMARY KEY (ID); |
||||
``` |
||||
|
||||
This will add a primary key to `ID` column in the `Employees` table. |
||||
|
||||
## Composite Primary Key |
||||
|
||||
We can also use multiple columns to define a primary key. Such key is known as composite key. |
||||
|
||||
```sql |
||||
CREATE TABLE Customers ( |
||||
CustomerID INT, |
||||
StoreID INT, |
||||
CONSTRAINT pk_CustomerID_StoreID PRIMARY KEY (CustomerID,StoreID) |
||||
); |
||||
``` |
||||
|
||||
In this case, each combination of `CustomerID` and `StoreID` must be unique across the whole table. |
||||
- [@article@SQL PRIMARY KEY Constraint](https://www.w3schools.com/sql/sql_primarykey.ASP) |
||||
- [@article@SQL Primary Key](https://www.tutorialspoint.com/sql/sql-primary-key.htm) |
@ -1,39 +1,8 @@ |
||||
# Query Analysis Techniques |
||||
|
||||
Query analysis is a critical part of performance optimization in SQL. It involves critically examining your SQL queries to determine potential bottlenecks, unnecessary computations or data fetch operations, and areas where you can implement performance optimization techniques. |
||||
Query analysis techniques in SQL involve examining and optimizing queries to improve performance and efficiency. Key techniques include using `EXPLAIN` or `EXPLAIN PLAN` commands to understand the query execution plan, which reveals how the database processes the query, including join methods, index usage, and data retrieval strategies. Analyzing `execution plans` helps identify bottlenecks such as full table scans or inefficient joins. Other techniques include `profiling queries` to measure execution time, `examining indexes` to ensure they are effectively supporting query operations, and `refactoring queries` by breaking down complex queries into simpler, more efficient components. Additionally, monitoring `database performance metrics` like CPU, memory usage, and disk I/O can provide insights into how queries impact overall system performance. Regularly applying these techniques allows for the identification and resolution of performance issues, leading to faster and more efficient database operations. |
||||
|
||||
## Explain Plan |
||||
Learn more from the following resources: |
||||
|
||||
SQL provides an "EXPLAIN PLAN" statement that can be utilized to understand the execution plan of a query. This is used to analyze the performance of SQL commands before actually executing them. |
||||
|
||||
When running the command, the output shows the steps involved in executing the query and an estimation of the cost involved with each step. The cost is a unitless value representing the resources required to perform the operation. |
||||
|
||||
```sql |
||||
EXPLAIN PLAN FOR SELECT * FROM table_name; |
||||
``` |
||||
|
||||
## Index Usage |
||||
|
||||
Using appropriate indexes is crucial for query performance. Unnecessary full table scans can be avoided if the correct indexes are present. Even though SQL will automatically determine the appropriate index to use, it can be helpful to manually specify which index to use for complex queries. |
||||
|
||||
```sql |
||||
CREATE INDEX idx_column ON table_name(column_name); |
||||
``` |
||||
|
||||
## Join Optimization |
||||
|
||||
The order in which tables are joined can have a large impact on query performance. In general, you should join tables in a way that results in the smallest result set as early as possible. |
||||
|
||||
Look out for "Nested Loops" in your explain plan. These can be a cause of slow performance if a large number of rows are being processed. |
||||
|
||||
```sql |
||||
SELECT * |
||||
FROM table1 |
||||
INNER JOIN table2 ON table1.id = table2.id; |
||||
``` |
||||
|
||||
## Regular Performance Tests |
||||
|
||||
Regular query performance testing can catch slow queries before they become a problem. Utilizing tools that can monitor and report query performance can help you keep an eye on your database's performance. |
||||
|
||||
Also, continual analysis of the query performance should be done as your data grows. A query that performs well with a small dataset may not do so when the dataset grows. |
||||
- [@article@EXPLAIN](https://docs.snowflake.com/en/sql-reference/sql/explain) |
||||
- [@article@EXPLAIN PLAN](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/EXPLAIN-PLAN.html) |
@ -1,66 +1,8 @@ |
||||
# Query Optimization |
||||
|
||||
Query optimization is a function of SQL that involves tuning and optimizing a SQL statement so that the system executes it in the fastest and most efficient way possible. It includes optimizing the costs of computation, communication, and disk I/O. |
||||
Query optimization in SQL involves refining queries to enhance their execution speed and reduce resource consumption. Key strategies include indexing columns used in `WHERE`, `JOIN`, and `ORDER BY` clauses to accelerate data retrieval, minimizing data processed by limiting the number of columns selected and filtering rows early in the query. Using appropriate join types and arranging joins in the most efficient order are crucial. Avoiding inefficient patterns like `SELECT`, replacing subqueries with joins or common table expressions (CTEs), and leveraging query hints or execution plan analysis can also improve performance. Regularly updating statistics and ensuring that queries are structured to take advantage of database-specific optimizations are essential practices for maintaining optimal performance. |
||||
|
||||
The primary approaches of query optimization involve the following: |
||||
Learn more from the following resources: |
||||
|
||||
## Rewriting Queries |
||||
|
||||
This means changing the original SQL query to an equivalent one which requires fewer system resources. It's usually done automatically by the database system. |
||||
|
||||
For instance, let's say we have a query as follows: |
||||
|
||||
```sql |
||||
SELECT * |
||||
FROM Customers |
||||
WHERE state = 'New York' AND city = 'New York'; |
||||
``` |
||||
|
||||
The above query can be rewritten using a subquery for better optimization: |
||||
|
||||
```sql |
||||
SELECT * |
||||
FROM Customers |
||||
WHERE state = 'New York' |
||||
AND city IN (SELECT city |
||||
FROM Customers |
||||
WHERE city = 'New York'); |
||||
``` |
||||
|
||||
## Choosing the right index |
||||
|
||||
Indexes are used to find rows with specific column values quickly. Without an index, SQL has to begin with the first row and then read through the entire table to find the appropriate rows. The larger the table, the more costly the operation. Choosing a right and efficient index greatly influence on query performance. |
||||
|
||||
For example, |
||||
|
||||
```sql |
||||
CREATE INDEX index_name |
||||
ON table_name (column1, column2, ...); |
||||
``` |
||||
|
||||
## Fine-tuning Database Design |
||||
|
||||
Improper database schema designs could result in poor query performances. While not strictly a part of query optimization, tuning the database design can speed up the query execution time drastically. |
||||
|
||||
Changes such as the separation of specific data to different tables (Normalization), combining redundant data (Denormalization), or changing the way how tables are linked (Optimized Join Operations), can be implemented to optimize the schema. |
||||
|
||||
## Use of SQL Clauses wisely |
||||
|
||||
The usage of certain SQL clauses can help in query optimization like LIMIT, BETWEEN etc. |
||||
|
||||
Example, |
||||
|
||||
```sql |
||||
SELECT column1, column2 |
||||
FROM table_name |
||||
WHERE condition |
||||
LIMIT 10; |
||||
``` |
||||
|
||||
## System Configuration |
||||
|
||||
Many database systems allow you to configure system parameters that control its behavior during query execution. For instance, in MySQL, you can set parameters like `sort_buffer_size` or `join_buffer_size` to tweak how MySQL would use memory during sorting and joining operations. |
||||
|
||||
In PostgreSQL, you can set `work_mem` to control how much memory is utilized during operations such as sorting and hashing. |
||||
|
||||
Always remember the goal of query optimization is to lessen the system resources usage in terms of memory, CPU time, and thus improve the query performance. |
||||
- [@video@SQL Query Optimization](https://www.youtube.com/watch?v=GA8SaXDLdsY) |
||||
- [@article@12 Ways to Optimize SQL Queries](https://www.developernation.net/blog/12-ways-to-optimize-sql-queries-in-database-management/) |
@ -1,50 +1,8 @@ |
||||
# rank |
||||
|
||||
`RANK()` is a window function in SQL that assigns a unique rank to each distinct row within a partition of a result set. The rank of the first row within each partition is one. The `RANK()` function adds the number of tied rows to the tied rank to calculate the next rank. So the ranks may not be consecutive numbers. |
||||
The `RANK` function in SQL is a window function that assigns a rank to each row within a partition of a result set, based on the order specified by the `ORDER BY` clause. Unlike the `ROW_NUMBER` function, `RANK` allows for the possibility of ties—rows with equal values in the ordering column(s) receive the same rank, and the next rank is skipped accordingly. For example, if two rows share the same rank of 1, the next rank will be 3. This function is useful for scenarios where you need to identify relative positions within groups, such as ranking employees by salary within each department. |
||||
|
||||
## Parameters of RANK Function |
||||
Learn more from the following resources: |
||||
|
||||
There are no arguments for the `RANK()` function. However, since it's a window function, the function operates on a set of rows (window) defined by the `OVER` clause, which is mandatory. |
||||
|
||||
## Syntax |
||||
|
||||
The syntax of `RANK` function is: |
||||
|
||||
```sql |
||||
RANK () OVER ( |
||||
[PARTITION BY column_1, column_2,…] |
||||
ORDER BY column_3,column_4,… |
||||
) |
||||
``` |
||||
|
||||
`PARTITION BY`: This clause divides the rows into multiple groups or partitions upon which the `RANK()` function is applied. |
||||
|
||||
`ORDER BY`: This clause sorts the rows in each partition. |
||||
|
||||
If `PARTITION BY` is not specified, the function treats all rows in the result set as a single partition. |
||||
|
||||
## Examples |
||||
|
||||
Here's an example query using the `RANK()` function: |
||||
|
||||
```sql |
||||
SELECT |
||||
product_name, |
||||
brand, |
||||
RANK () OVER ( |
||||
PARTITION BY brand |
||||
ORDER BY product_name ASC |
||||
) Product_rank |
||||
FROM |
||||
products; |
||||
``` |
||||
|
||||
In this example, it generates a list of products, grouped by brand, and ranked by product_name within each brand. The `product_name` with the smallest value (alphabetically first when sorting ASC) gets a rank of 1 within its partition. |
||||
|
||||
## Important Notes |
||||
- `RANK()` function may return duplicate rankings if the column on which the function is applied contains duplicate values. |
||||
- The `RANK()` function will leave a gap and create a non-consecutive ranking if there are equal rankings (ties). |
||||
- `RANK()` function offers a very efficient way to solve top-N problems. |
||||
|
||||
|
||||
You might also be interested in looking at other similar ranking functions in SQL like `DENSE_RANK()`, `ROW_NUMBER()`, etc. |
||||
- [@article@Overview of SQL RANK Functions](https://www.sqlshack.com/overview-of-sql-rank-functions/) |
||||
- [@video@RANK, DENSE_RANK, ROW_NUMBER SQL Analytical Functions Simplified](https://www.youtube.com/watch?v=xMWEVFC4FOk) |
@ -1,54 +1,8 @@ |
||||
# Recursive Queries |
||||
|
||||
Recursive queries are advanced SQL queries used for data analysis, especially when working with hierarchical or tree-structured data. These queries are implemented using Common Table Expressions (CTEs). CTEs have the same structure as a standard SELECT statement but are prefixed with `WITH`, followed by the CTE name and an optional list of columns. |
||||
Recursive queries in SQL allow for the repeated execution of a query within itself, enabling the traversal of hierarchical or tree-like data structures. This powerful feature is particularly useful for handling nested relationships, such as organizational hierarchies, bill of materials, or network topologies. By using a combination of an anchor member (initial query) and a recursive member (the part that refers to itself), recursive queries can iterate through multiple levels of data, retrieving information that would be difficult or impossible to obtain with standard SQL constructs. This technique simplifies complex queries and improves performance when dealing with self-referential data. |
||||
|
||||
CTEs can be recursive and non-recursive. The non-recursive CTE is a query that is executed once and then goes out of scope. |
||||
Learn more from the following resources: |
||||
|
||||
## Recursive CTE |
||||
|
||||
A recursive CTE is a CTE that references itself. Recursive CTEs have a minimum of two queries, an anchor member (runs only once), and a recursive member (runs repeatedly). Include a UNION ALL statement between these queries. |
||||
|
||||
Here's a sample of a recursive CTE: |
||||
|
||||
```sql |
||||
WITH RECURSIVE ancestors AS ( |
||||
SELECT employee_id, manager_id, full_name |
||||
FROM employees |
||||
WHERE manager_id IS NULL |
||||
|
||||
UNION ALL |
||||
|
||||
SELECT e.employee_id, e.manager_id, e.full_name |
||||
FROM employees e |
||||
INNER JOIN ancestors a ON a.employee_id = e.manager_id |
||||
) |
||||
SELECT * FROM ancestors; |
||||
``` |
||||
|
||||
In this code snippet, the first query is the anchor member that fetches the employees with no manager. The second part is the recursive member, continuously fetching managers until none are left. |
||||
|
||||
## Syntax of Recursive CTE |
||||
|
||||
Here's the general structure of a recursive CTE: |
||||
|
||||
```sql |
||||
WITH RECURSIVE cte_name (column_list) AS ( |
||||
|
||||
-- Anchor member |
||||
SELECT column_list |
||||
FROM table_name |
||||
WHERE condition |
||||
|
||||
UNION ALL |
||||
|
||||
-- Recursive member |
||||
SELECT column_list |
||||
FROM table_name |
||||
INNER JOIN cte_name ON condition |
||||
) |
||||
SELECT * FROM cte_name; |
||||
``` |
||||
|
||||
Note: some database systems such as MySQL, PostgreSQL, and SQLite use `WITH RECURSIVE` for recursive CTEs. Others like SQL Server, Oracle, and DB2 use just `WITH`. |
||||
|
||||
Remember to be careful when setting the conditions for your recursive query to avoid infinite loops. |
||||
- [@article@Recursive Queries in SQL](https://codedamn.com/news/sql/recursive-queries-in-sql) |
||||
- [@article@Recursive SQL Expression Visually Explained](https://builtin.com/data-science/recursive-sql) |
@ -1,57 +1,5 @@ |
||||
# Reducing Subqueries |
||||
|
||||
SQL subqueries allow you to nest a SELECT statement inside another query. However, while this can sometimes simplify the code, the drawback is they can result in long-running queries and reduced performance. Therefore, optimizing queries often involves reducing subqueries. Two common ways to achieve this include using JOINS and 'EXISTS' clause. |
||||
Recursive queries in SQL allow for iterative processing of hierarchical or tree-structured data within a single query. They consist of an anchor member (the base case) and a recursive member that references the query itself, enabling the exploration of parent-child relationships, traversal of graphs, or generation of series data. This powerful feature is particularly useful for tasks like querying organizational hierarchies, bill of materials structures, or navigating complex relationships in data that would otherwise require multiple separate queries or procedural code. |
||||
|
||||
1. **JOIN:** A JOIN clause combines rows from two or more tables based on a related column. In many cases, a JOIN can replace a subquery with equivalent logic, but with improved performance. |
||||
|
||||
An example would be a scenario where you have two tables `Orders` and `Customers`, and you want to find orders made by a specific customer: |
||||
|
||||
Subquery could be: |
||||
|
||||
```sql |
||||
SELECT OrderNumber |
||||
FROM Orders |
||||
WHERE CustomerID IN ( |
||||
SELECT CustomerID |
||||
FROM Customers |
||||
WHERE CustomerName = 'John Doe' |
||||
); |
||||
``` |
||||
|
||||
Equivalent JOIN: |
||||
|
||||
```sql |
||||
SELECT o.OrderNumber |
||||
FROM Orders o |
||||
JOIN Customers c ON o.CustomerID = c.CustomerID |
||||
WHERE c.CustomerName = 'John Doe'; |
||||
``` |
||||
|
||||
2. **EXISTS:** The EXISTS operator checks for the existence of rows returned by the subquery. Many times, a subquery can be replaced with an EXISTS clause which would greatly increase performance as EXISTS will stop processing once it hits a true condition and does not need to check all results like IN would. |
||||
|
||||
Consider you want to find all customers who have placed at least one order: |
||||
|
||||
Subquery might be: |
||||
|
||||
```sql |
||||
SELECT * |
||||
FROM Customers |
||||
WHERE CustomerID IN ( |
||||
SELECT CustomerID |
||||
FROM Orders |
||||
); |
||||
``` |
||||
|
||||
Equivalent EXISTS use case: |
||||
|
||||
```sql |
||||
SELECT * |
||||
FROM Customers c |
||||
WHERE EXISTS ( |
||||
SELECT 1 |
||||
FROM Orders o |
||||
WHERE c.CustomerID = o.CustomerID |
||||
); |
||||
``` |
||||
|
||||
While it's important to minimize subqueries whenever possible, there may be cases where you cannot replace a subquery, especially when dealing with correlated subqueries or complex queries where rewriting might be nontrivial or not feasible. |
||||
Learn more from the following resources: |
@ -1,45 +1,8 @@ |
||||
# REPLACE |
||||
|
||||
You can use the `REPLACE()` function in SQL to substitute all occurrences of a specified string. |
||||
The `REPLACE` function in SQL is used to substitute all occurrences of a specified substring within a string with a new substring. It takes three arguments: the original string, the substring to be replaced, and the substring to replace it with. If the specified substring is found in the original string, `REPLACE` returns the modified string with all instances of the old substring replaced by the new one. If the substring is not found, the original string is returned unchanged. This function is particularly useful for data cleaning tasks, such as correcting typos, standardizing formats, or replacing obsolete data. |
||||
|
||||
**Synopsis** |
||||
Learn more from the following resources: |
||||
|
||||
`REPLACE(input_string, string_to_replace, replacement_string)` |
||||
|
||||
**Parameters** |
||||
|
||||
- `input_string`: This is the original string where you want to replace some characters. |
||||
- `string_to_replace`: This is the string that will be searched for in the original string. |
||||
- `replacement_string`: This is the string that will replace the `string_to_replace` in the original string. |
||||
|
||||
The `REPLACE()` function is handy when it comes to manipulating and modifying data in various ways, particularly when used in combination with other SQL data-manipulation functions. |
||||
|
||||
**Examples** |
||||
|
||||
Suppose we have the following table, `Employees`: |
||||
|
||||
| EmpId | EmpName | |
||||
|-------|---------------------| |
||||
| 1 | John Doe | |
||||
| 2 | Jane Doe | |
||||
| 3 | Jim Smith Doe | |
||||
| 4 | Jennifer Doe Smith | |
||||
|
||||
Here's how you can use the `REPLACE()` function: |
||||
|
||||
```sql |
||||
SELECT EmpId, EmpName, |
||||
REPLACE(EmpName, 'Doe', 'Roe') as ModifiedName |
||||
FROM Employees; |
||||
``` |
||||
|
||||
After the execution of the above SQL, we will receive: |
||||
|
||||
| EmpId | EmpName | ModifiedName | |
||||
|-------|--------------------|---------------------| |
||||
| 1 | John Doe | John Roe | |
||||
| 2 | Jane Doe | Jane Roe | |
||||
| 3 | Jim Smith Doe | Jim Smith Roe | |
||||
| 4 | Jennifer Doe Smith | Jennifer Roe Smith | |
||||
|
||||
You can see that all occurrences of 'Doe' are replaced with 'Roe'. |
||||
- [@article@SQL REPLACE Function](https://www.w3schools.com/sql/func_sqlserver_replace.asp) |
||||
- [@article@How to use the SQL REPLACE Function](https://www.datacamp.com/tutorial/sql-replace) |
@ -1,63 +1,8 @@ |
||||
# RIGHT JOIN |
||||
|
||||
The `RIGHT JOIN` keyword returns all records from the right table (table2), and the matched records from the left table (table1). If there is no match, the result is `NULL` on the left side. |
||||
A `RIGHT JOIN` in SQL is a type of outer join that returns all rows from the right (second) table and the matching rows from the left (first) table. If there's no match in the left table, `NULL` values are returned for the left table's columns. This join type is less commonly used than LEFT JOIN but is particularly useful when you want to ensure all records from the second table are included in the result set, regardless of whether they have corresponding matches in the first table. `RIGHT JOIN` is often used to identify missing relationships or to include all possible values from a lookup table. |
||||
|
||||
## Syntax |
||||
Learn more from the following resources: |
||||
|
||||
Below is the common syntax used for writing a `RIGHT JOIN`: |
||||
|
||||
```sql |
||||
SELECT column_name(s) |
||||
FROM table1 |
||||
RIGHT JOIN table2 |
||||
ON table1.column_name = table2.column_name; |
||||
``` |
||||
|
||||
## Example |
||||
|
||||
Consider two tables: |
||||
|
||||
**Table "Orders":** |
||||
|
||||
| OrderID | CustomerID | OrderDate | |
||||
|--|--|--| |
||||
| 1 | 3 | 2017/11/11 | |
||||
| 2 | 1 | 2017/10/23 | |
||||
| 3 | 2 | 2017/9/15 | |
||||
| 4 | 4 | 2017/9/03 | |
||||
|
||||
**Table "Customers":** |
||||
|
||||
| CustomerID | CustomerName | ContactName | Country | |
||||
|--|--|--|--| |
||||
| 1 | Alfreds Futterkiste | Maria Anders | Germany | |
||||
| 2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Mexico | |
||||
| 3 | Antonio Moreno Taquería | Antonio Moreno | Mexico | |
||||
| 5 | Berglunds snabbköp | Christina Berglund | Sweden | |
||||
|
||||
Now, we want to select all customers and any matching records in orders table. If there is no match, the result is null in order table: |
||||
|
||||
```sql |
||||
SELECT |
||||
Customers.CustomerName, |
||||
Orders.OrderID |
||||
FROM |
||||
Orders |
||||
RIGHT JOIN |
||||
Customers |
||||
ON |
||||
Orders.CustomerID = Customers.CustomerID; |
||||
``` |
||||
|
||||
**Result:** |
||||
|
||||
| CustomerName | OrderID | |
||||
|--|--| |
||||
| Alfreds Futterkiste | 2 | |
||||
| Ana Trujillo Emparedados y helados | 3 | |
||||
| Antonio Moreno Taquería | 1 | |
||||
| Berglunds snabbköp | NULL | |
||||
| Around the Horn | NULL | |
||||
| Bottom-Dollar Markets | NULL | |
||||
|
||||
As you can see, the `RIGHT JOIN` keyword returned all the records from the Customers table and all matched records from the Orders table. For those customers who have no orders (like "Berglunds snabbköp"), the result is `NULL`. |
||||
- [@article@SQL RIGHT JOIN](https://www.w3schools.com/sql/sql_join_right.asp) |
||||
- [@article@SQL RIGHT JOIN With Examples](https://www.programiz.com/sql/right-join) |
@ -1,49 +1,8 @@ |
||||
# ROLLBACK |
||||
|
||||
The `ROLLBACK` command is a transactional control language (TCL) instruction that undoes an unsuccessful or unsatisfactory running transaction. This process also applies to SQL Server where all individual statements in SQL Server are treated as a single atomic transaction. |
||||
`ROLLBACK` is a SQL command used to undo transactions that have not yet been committed to the database. It reverses all changes made within the current transaction, restoring the database to its state before the transaction began. This command is crucial for maintaining data integrity, especially when errors occur during a transaction or when implementing conditional logic in database operations. `ROLLBACK` is an essential part of the ACID (Atomicity, Consistency, Isolation, Durability) properties of database transactions, ensuring that either all changes in a transaction are applied, or none are, thus preserving data consistency. |
||||
|
||||
When a `ROLLBACK` command is issued, all the operations (such as Insert, Delete, Update, etc.) are undone and the database is restored to its initial state before the transaction started. |
||||
Learn more from the following resources: |
||||
|
||||
## When to use `ROLLBACK` |
||||
|
||||
1. If the transaction is unacceptable or unsuccessful. |
||||
2. If you want to revert the unwanted changes. |
||||
|
||||
Here is a basic example: |
||||
|
||||
```sql |
||||
BEGIN TRANSACTION; |
||||
|
||||
-- This would delete all rows from the table. |
||||
DELETE FROM Employee; |
||||
|
||||
-- Oh no! That's not what I wanted. Let's roll that back. |
||||
ROLLBACK; |
||||
``` |
||||
|
||||
In this example, the `ROLLBACK` command would restore all deleted data into the `Employee` table. |
||||
|
||||
SQL also allows the usage of `SAVEPOINT`s along with the `ROLLBACK` command, which allows rolling back to a specific point in a transaction, instead of rolling back the entire transaction. |
||||
|
||||
Here is an example of using `SAVEPOINT`s: |
||||
|
||||
```sql |
||||
BEGIN TRANSACTION; |
||||
|
||||
-- Adding new employee. |
||||
INSERT INTO Employee(ID, Name) VALUES(1, 'John'); |
||||
|
||||
-- Create a savepoint to be able to roll back to this point. |
||||
SAVEPOINT SP1; |
||||
|
||||
-- Oh no! I made a mistake creating this employee. Let's roll back to the savepoint. |
||||
ROLLBACK TO SAVEPOINT SP1; |
||||
|
||||
-- Now I can try again. |
||||
INSERT INTO Employee(ID, Name) VALUES(1, 'Jack'); |
||||
|
||||
-- Commit the changes. |
||||
COMMIT; |
||||
``` |
||||
|
||||
In this example, `ROLLBACK TO SAVEPOINT SP1` would undo the first insert into the `Employee` table while preserving the state of the database as it was at the savepoint `SP1`. So, the second insert command would properly add 'Jack' in place of 'John'. |
||||
- [@video@How to undo a mistake a in SQL: Rollback and Commit](https://www.youtube.com/watch?v=jomsdMLiIZM) |
||||
- [@article@Difference between COMMIT and ROLLBACK in SQL](https://byjus.com/gate/difference-between-commit-and-rollback-in-sql/) |
@ -1,45 +1,8 @@ |
||||
# ROUND |
||||
|
||||
The `ROUND` function in SQL is used to round a numeric field to the nearest specified decimal or integer. |
||||
The `ROUND` function in SQL is used to round a numeric value to a specified number of decimal places. It takes two arguments: the number to be rounded and the number of decimal places to round to. If the second argument is omitted, the function rounds the number to the nearest whole number. For positive values of the second argument, the number is rounded to the specified decimal places; for negative values, it rounds to the nearest ten, hundred, thousand, etc. The `ROUND` function is useful for formatting numerical data for reporting or ensuring consistent precision in calculations. |
||||
|
||||
Most usually, `ROUND` accepts two arguments. The first one is the value that needs to be rounded, and the second is the number of decimal places to which the first argument will be rounded off. When dealing with decimals, SQL will round up when the number after the decimal point is 5 or higher, whereas it will round down if it's less than 5. |
||||
Learn more from the following resources: |
||||
|
||||
## Syntax |
||||
|
||||
The basic syntax for `ROUND` can be described as follows: |
||||
|
||||
```sql |
||||
ROUND ( numeric_expression, length [ , function ] ) |
||||
``` |
||||
- `numeric_expression`: A floating point number to round. |
||||
- `length`: The precision to which `numeric_expression` is to be rounded. When `length` is a positive number, rounding affects the right side of the decimal point. If `length` is negative, rounding affects the left side of the decimal point. |
||||
- `function`: Optional parameter to determine the operation to perform. If this is omitted or 0, the `numeric_expression` is rounded. If this is 1, the `numeric_expression` is truncated. |
||||
|
||||
## Example 1: |
||||
|
||||
Round off a decimal to the nearest whole number. |
||||
|
||||
```sql |
||||
SELECT ROUND(125.215); |
||||
``` |
||||
This will result in `125`. |
||||
|
||||
## Example 2: |
||||
|
||||
Round off a number to a specified decimal place. |
||||
|
||||
```sql |
||||
SELECT ROUND(125.215, 1); |
||||
``` |
||||
This will result in `125.2` as the second decimal place (5) is less than 5. |
||||
|
||||
## Example 3: |
||||
|
||||
Round off the left side of the decimal. |
||||
|
||||
```sql |
||||
SELECT ROUND(125.215, -2); |
||||
``` |
||||
This will result in `100` as rounding now affects digits before the decimal point. |
||||
|
||||
Whenever you need to round off numeric data in SQL, the `ROUND` function is a valuable tool to have in your kit. It proficiently handles both positive and negative rounding, and its simple syntax makes it extremely user-friendly. |
||||
- [@article@SQL ROUND](https://www.w3schools.com/sql/func_sqlserver_round.asp) |
||||
- [@article@What is the SQL ROUND Function and how does it work?](https://www.datacamp.com/tutorial/mastering-sql-round) |
@ -1,43 +1,8 @@ |
||||
# Row |
||||
|
||||
In SQL, a "row" refers to a record in a table. Each row in a table represents a set of related data, and every row in the table has the same structure. |
||||
In SQL, a row (also called a record or tuple) represents a single, implicitly structured data item in a table. Each row contains a set of related data elements corresponding to the table's columns. Rows are fundamental to the relational database model, allowing for the organized storage and retrieval of information. Operations like INSERT, UPDATE, and DELETE typically work at the row level. |
||||
|
||||
For instance, in a table named "customers", a row may represent one customer, with columns containing information like ID, name, address, email, etc. |
||||
Learn more from the following resources: |
||||
|
||||
Here is a conceptual SQL table: |
||||
|
||||
| ID | NAME | ADDRESS | EMAIL | |
||||
|----|------|---------|-------| |
||||
| 1 | John | NY | john@example.com | |
||||
| 2 | Jane | LA | jane@example.com | |
||||
| 3 | Jim | Chicago | jim@example.com | |
||||
|
||||
Each of these line of data is referred to as a 'row' in the SQL table. |
||||
|
||||
To select a row, you would use a `SELECT` statement. Here's an example of how you might select a row: |
||||
|
||||
```sql |
||||
SELECT * |
||||
FROM customers |
||||
WHERE ID = 1; |
||||
``` |
||||
|
||||
This would output: |
||||
|
||||
| ID | Name | ADDRESS | Email | |
||||
|---|------|---------|--------| |
||||
| 1 | John | NY | john@example.com | |
||||
|
||||
The `*` in the statement refers to all columns. If you want to only select specific columns, you can replace `*` with the column name(s): |
||||
|
||||
```sql |
||||
SELECT NAME, EMAIL |
||||
FROM customers |
||||
WHERE ID = 1; |
||||
``` |
||||
|
||||
In this case, the output would be: |
||||
|
||||
| Name | Email | |
||||
|-----|--------| |
||||
| John | john@example.com | |
||||
- [@article@Row - Database](https://en.wikipedia.org/wiki/Row_(database)) |
||||
- [@article@Database Row: Definition, Examples](https://www.devx.com/terms/database-row/) |
@ -1,43 +1,8 @@ |
||||
# Row_number |
||||
|
||||
**ROW_NUMBER()** is a SQL window function that assigns a unique number to each row in the result set. |
||||
ROW_NUMBER() is a SQL window function that assigns a unique, sequential integer to each row within a partition of a result set. It's useful for creating row identifiers, implementing pagination, or finding the nth highest/lowest value in a group. The numbering starts at 1 for each partition and continues sequentially, allowing for versatile data analysis and manipulation tasks. |
||||
|
||||
Syntax: |
||||
Learn more from the following resources: |
||||
|
||||
```sql |
||||
ROW_NUMBER() OVER ( |
||||
[ORDER BY column_name] |
||||
) |
||||
``` |
||||
|
||||
## Features: |
||||
|
||||
- Numbers are assigned based on the `ORDER BY` clause of `ROW_NUMBER()`. |
||||
- In case of identical values in the `ORDER BY` clause, the function assigns numbers arbitrarily. |
||||
- In other words, the sequence of numbers generated by `ROW_NUMBER()` is not guaranteed to be the same for the same set of data. |
||||
|
||||
## Examples: |
||||
|
||||
**Example 1:** Basic usage of ROW_NUMBER() on a single column |
||||
```sql |
||||
SELECT |
||||
name, |
||||
ROW_NUMBER() OVER (ORDER BY name) row_number |
||||
FROM |
||||
employees; |
||||
``` |
||||
In this example, `ROW_NUMBER()` is used to assign a unique number to each row in the employees table, ordered by the employee names alphabetically. |
||||
|
||||
**Example 2:** Using ROW_NUMBER() to rank rows in each partition |
||||
```sql |
||||
SELECT |
||||
department_id, |
||||
first_name, |
||||
salary, |
||||
ROW_NUMBER() OVER ( |
||||
PARTITION BY department_id |
||||
ORDER BY salary DESC) row_number |
||||
FROM |
||||
employees; |
||||
``` |
||||
In this example, `ROW_NUMBER()` is used to rank employee salaries within each department (i.e., partitioned by `department_id`). In each department, employees with higher salaries are assigned lower row numbers. |
||||
- [@article@SQL ROW_NUMBER](https://www.sqltutorial.org/sql-window-functions/sql-row_number/) |
||||
- [@article@How to Use ROW_NUMBER OVER() in SQL to Rank Data](https://learnsql.com/blog/row-number-over-in-sql/) |
@ -1,58 +1,8 @@ |
||||
# SAVEPOINT |
||||
|
||||
A savepoint is a way of implementing subtransactions (nested transactions) within a relational database management system by indicating a particular point within a transaction that a user can "roll back" to in case of failure. The main property of a savepoint is that it enables you to create a rollback segment within a transaction. This allows you to revert the changes made to the database after the Savepoint without having to discard the entire transaction. |
||||
A `SAVEPOINT` in SQL is a point within a transaction that can be referenced later. It allows for more granular control over transactions by creating intermediate points to which you can roll back without affecting the entire transaction. This is particularly useful in complex transactions where you might want to undo part of the work without discarding all changes. `SAVEPOINT` enhances transaction management flexibility. |
||||
|
||||
A Savepoint might be used in instances where if a particular operation fails, you would like to revert the database to the state it was in before the operation was attempted, but you do not want to give up on the entire transaction. |
||||
Learn more from the following resources: |
||||
|
||||
## Savepoint Syntax |
||||
|
||||
The general syntax for `SAVEPOINT`: |
||||
|
||||
```sql |
||||
SAVEPOINT savepoint_name; |
||||
``` |
||||
|
||||
## Use of Savepoint |
||||
|
||||
Here is the basic usage of savepoint: |
||||
|
||||
```sql |
||||
START TRANSACTION; |
||||
INSERT INTO Table1 (Column1) VALUES ('Value1'); |
||||
|
||||
SAVEPOINT SP1; |
||||
|
||||
INSERT INTO Table1 (Column1) VALUES ('Value2'); |
||||
|
||||
ROLLBACK TO SP1; |
||||
|
||||
COMMIT; |
||||
``` |
||||
|
||||
In this example, an initial `INSERT` statement is performed before a Savepoint named `SP1` is created. Another `INSERT` statement is called and then `ROLLBACK TO SP1` is executed. This means all changes between the creation of `SP1` and `ROLLBACK TO SP1` are reverted. After that, 'COMMIT' is used to permanently store the changes made by the first `INSERT` statement. |
||||
|
||||
## Release Savepoint |
||||
|
||||
The `RELEASE SAVEPOINT` deletes a savepoint within a transaction. |
||||
|
||||
Here’s the syntax: |
||||
|
||||
```sql |
||||
RELEASE SAVEPOINT savepoint_name; |
||||
``` |
||||
|
||||
The action of releasing a savepoint removes the named savepoint from the set of savepoints of the current transaction. No changes are undone. |
||||
|
||||
## Remove Savepoint |
||||
|
||||
The `ROLLBACK TO SAVEPOINT` removes a savepoint within a transaction. |
||||
|
||||
Here’s the syntax: |
||||
|
||||
```sql |
||||
ROLLBACK TRANSACTION TO savepoint_name; |
||||
``` |
||||
|
||||
This statement rolls back a transaction to the named savepoint without terminating the transaction. |
||||
|
||||
Please note, savepoint names are not case sensitive and must obey the syntax rules of the server. |
||||
- [@article@SQL SAVEPOINT](https://www.ibm.com/docs/pl/informix-servers/12.10?topic=statements-savepoint-statement) |
||||
- [@video@DBMS - Save Point](https://www.youtube.com/watch?v=30ldSUkswGM) |
@ -1,74 +1,8 @@ |
||||
# Scalar |
||||
|
||||
In SQL, a scalar type is a type that holds a single value as opposed to composite types that hold multiple values. In simpler terms, scalar types represent a single unit of data. |
||||
A scalar value is a single data item, as opposed to a set or array of values. Scalar subqueries are queries that return exactly one column and one row, often used in `SELECT` statements, `WHERE` clauses, or as part of expressions. Scalar functions in SQL return a single value based on input parameters. Understanding scalar concepts is crucial for writing efficient and precise SQL queries. |
||||
|
||||
Some common examples of scalar types in SQL include: |
||||
Learn more from the following resources: |
||||
|
||||
- Integers (`INT`) |
||||
- Floating-point numbers (`FLOAT`) |
||||
- Strings (`VARCHAR`, `CHAR`) |
||||
- Date and Time (`DATE`, `TIME`) |
||||
- Boolean (`BOOL`) |
||||
|
||||
## Examples |
||||
|
||||
Here is how you can define different scalar types in SQL: |
||||
|
||||
## Integers |
||||
|
||||
An integer can be defined using the INT type. Here is an example of how to declare an integer: |
||||
|
||||
```sql |
||||
CREATE TABLE Employees ( |
||||
EmployeeID INT, |
||||
FirstName VARCHAR(50), |
||||
LastName VARCHAR(50) |
||||
); |
||||
``` |
||||
|
||||
## Floating-Point Numbers |
||||
|
||||
Floating-point numbers can be defined using the FLOAT or REAL type. Here is an example of how to declare a floating-point number: |
||||
|
||||
```sql |
||||
CREATE TABLE Products ( |
||||
ProductID INT, |
||||
Price FLOAT |
||||
); |
||||
``` |
||||
|
||||
## Strings |
||||
|
||||
Strings can be defined using the CHAR, VARCHAR, or TEXT type. Here is an example of how to declare a string: |
||||
|
||||
```sql |
||||
CREATE TABLE Employees ( |
||||
EmployeeID INT, |
||||
FirstName VARCHAR(50), |
||||
LastName VARCHAR(50) |
||||
); |
||||
``` |
||||
|
||||
## Date and Time |
||||
|
||||
The DATE, TIME or DATETIME type can be used to define dates and times: |
||||
|
||||
```sql |
||||
CREATE TABLE Orders ( |
||||
OrderID INT, |
||||
OrderDate DATE |
||||
); |
||||
``` |
||||
|
||||
## Boolean |
||||
|
||||
Booleans can be declared using the BOOL or BOOLEAN type. They hold either `TRUE` or `FALSE`. |
||||
|
||||
```sql |
||||
CREATE TABLE Employees ( |
||||
EmployeeID INT, |
||||
IsActive BOOL |
||||
); |
||||
``` |
||||
|
||||
Remember, the way these types are declared might slightly differ based on the SQL dialect you are using. It's crucial to refer to the specific documentation of the SQL flavor you're working with for the precise syntax and behavior. |
||||
- [@video@Using Scalar SQL to boost performance](https://www.youtube.com/watch?v=v8X5FGzzc9A) |
||||
- [@article@Creating SQL Scalar Functions](https://www.ibm.com/docs/en/db2/11.5?topic=functions-creating-sql-scalar) |
@ -1,27 +1,3 @@ |
||||
# Selective Projection |
||||
|
||||
Selective projection in SQL is a concept related to retrieving only specific columns from a table rather than retrieving all columns. It's one of the most basic ways to optimize your queries in SQL and make them more efficient. |
||||
|
||||
In SQL, a projection refers to the operation in which we choose certain columns (instead of all columns) from the table for our query results. If a table has numerous columns, and we only need data from a few of them, it's more efficient to only select those specific columns in the SQL query. This reduces the amount of data that needs to be scanned and fetched from the database, thereby improving performance. |
||||
|
||||
## Examples |
||||
|
||||
Let's take an example where you have a "students" table with the following columns: Id, Name, Age, Gender, Department, and City. If you only need Name and Department information, you should use a selective projection to specify only these columns in your SELECT statement: |
||||
|
||||
```sql |
||||
SELECT Name, Department |
||||
FROM students |
||||
``` |
||||
|
||||
This query returns just the Name and Department columns, rather than all fields in the students table. |
||||
|
||||
In contrast, if you used a `SELECT *` statement: |
||||
|
||||
```sql |
||||
SELECT * |
||||
FROM students |
||||
``` |
||||
|
||||
This would return all columns from the "students" table which can be inefficient if you don't need all that data. |
||||
|
||||
Selective projection can greatly optimize your SQL queries by minimizing the amount of data handled. It's especially beneficial when tables have large amounts of data and many columns, but only a subset of information is required. |
||||
Selective projection in SQL refers to the practice of choosing only specific columns (attributes) from a table or query result, rather than selecting all available columns. This technique is crucial for optimizing query performance and reducing unnecessary data transfer. By using SELECT with explicitly named columns instead of `SELECT *`, developers can improve query efficiency and clarity, especially when dealing with large tables or complex joins. |
||||
|
@ -1,60 +1,8 @@ |
||||
# SQL keywords |
||||
|
||||
SQL employs a number of standard command keywords that are integral to interact with databases. Keywords in SQL provide |
||||
instructions as to what action should be performed. |
||||
SQL keywords are reserved words that have special meanings within SQL statements. These include commands (like `SELECT`, `INSERT`, `UPDATE`), clauses (such as `WHERE`, `GROUP BY`, `HAVING`), and other syntax elements that form the structure of SQL queries. Understanding SQL keywords is fundamental to writing correct and effective database queries. Keywords are typically case-insensitive but are often written in uppercase by convention for better readability. |
||||
|
||||
Here are some of the primary SQL keywords: |
||||
Learn more from the following resources: |
||||
|
||||
**SELECT**: This keyword retrieves data from a database. For example, |
||||
|
||||
```sql |
||||
SELECT * FROM Customers; |
||||
``` |
||||
|
||||
In the above statement `*` indicates that all records should be retrieved from the `Customers` table. |
||||
|
||||
**FROM**: Used in conjunction with `SELECT` to specify the table from which to fetch data. |
||||
|
||||
**WHERE**: Used to filter records. Incorporating a WHERE clause, you might specify conditions that must be met. For |
||||
example, |
||||
|
||||
```sql |
||||
SELECT * FROM Customers WHERE Country='Germany'; |
||||
``` |
||||
|
||||
**INSERT INTO**: This command is used to insert new data into a database. |
||||
|
||||
```sql |
||||
INSERT INTO Customers (CustomerID, CustomerName, ContactName, Address, City, PostalCode, Country) |
||||
VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway'); |
||||
``` |
||||
|
||||
**UPDATE**: This keyword updates existing data within a table. For example, |
||||
|
||||
```sql |
||||
UPDATE Customers SET ContactName='Alfred Schmidt', City='Frankfurt' WHERE CustomerID=1; |
||||
``` |
||||
|
||||
**DELETE**: This command removes one or more records from a table. For example, |
||||
|
||||
```sql |
||||
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste'; |
||||
``` |
||||
|
||||
**CREATE DATABASE**: As implied by its name, this keyword creates a new database. |
||||
|
||||
```sql |
||||
CREATE DATABASE mydatabase; |
||||
``` |
||||
|
||||
**ALTER DATABASE**, **DROP DATABASE**, **CREATE TABLE**, **ALTER TABLE**, **DROP TABLE**: These keywords are used to |
||||
modify databases and tables. |
||||
|
||||
Remember that SQL is not case sensitive, meaning keywords can be written in lower case. The convention is to write them |
||||
in ALL CAPS for readability. There are many more keywords in SQL, but these are some of the most common. |
||||
|
||||
Learn more about SQL from the following resources: |
||||
|
||||
- [@article@SQL Tutorial - Mode](https://mode.com/sql-tutorial/) |
||||
- [@article@SQL Tutorial](https://www.sqltutorial.org/) |
||||
- [@article@SQL Tutorial - W3Schools](https://www.w3schools.com/sql/default.asp) |
||||
- [@article@SQL Keywords Reference](https://www.w3schools.com/sql/sql_ref_keywords.asp) |
||||
- [@article@SQL Keywords, Operators and Statements](https://blog.hubspot.com/website/sql-keywords-operators-statements) |
@ -1,46 +1,8 @@ |
||||
# SQL vs NoSQL |
||||
|
||||
When discussing databases, it's essential to understand the difference between SQL and NoSQL databases, as each has its own set of advantages and limitations. In this section, we'll briefly compare and contrast the two, so you can determine which one suits your needs better. |
||||
SQL (relational) and NoSQL (non-relational) databases represent two different approaches to data storage and retrieval. SQL databases use structured schemas and tables, emphasizing data integrity and complex queries through joins. NoSQL databases offer more flexibility in data structures, often sacrificing some consistency for scalability and performance. The choice between SQL and NoSQL depends on factors like data structure, scalability needs, consistency requirements, and the nature of the application. |
||||
|
||||
## SQL Databases |
||||
Learn more from the following resources: |
||||
|
||||
SQL (Structured Query Language) databases are also known as relational databases. They have a predefined schema, and data is stored in tables consisting of rows and columns. SQL databases follow the ACID (Atomicity, Consistency, Isolation, Durability) properties to ensure reliable transactions. Some popular SQL databases include MySQL, PostgreSQL, and Microsoft SQL Server. |
||||
|
||||
**Advantages of SQL databases:** |
||||
|
||||
- **Predefined schema**: Ideal for applications with a fixed structure. |
||||
- **ACID transactions**: Ensures data consistency and reliability. |
||||
- **Support for complex queries**: Rich SQL queries can handle complex data relationships and aggregation operations. |
||||
- **Scalability**: Vertical scaling by adding more resources to the server (e.g., RAM, CPU). |
||||
|
||||
**Limitations of SQL databases:** |
||||
|
||||
- **Rigid schema**: Data structure updates are time-consuming and can lead to downtime. |
||||
- **Scaling**: Difficulties in horizontal scaling and sharding of data across multiple servers. |
||||
- **Not well-suited for hierarchical data**: Requires multiple tables and JOINs to model tree-like structures. |
||||
|
||||
## NoSQL Databases |
||||
|
||||
NoSQL (Not only SQL) databases refer to non-relational databases, which don't follow a fixed schema for data storage. Instead, they use a flexible and semi-structured format like JSON documents, key-value pairs, or graphs. MongoDB, Cassandra, Redis, and Couchbase are some popular NoSQL databases. |
||||
|
||||
**Advantages of NoSQL databases:** |
||||
|
||||
- **Flexible schema**: Easily adapts to changes without disrupting the application. |
||||
- **Scalability**: Horizontal scaling by partitioning data across multiple servers (sharding). |
||||
- **Fast**: Designed for faster read and writes, often with a simpler query language. |
||||
- **Handling large volumes of data**: Better suited to managing big data and real-time applications. |
||||
- **Support for various data structures**: Different NoSQL databases cater to various needs, like document, graph, or key-value stores. |
||||
|
||||
**Limitations of NoSQL databases:** |
||||
|
||||
- **Limited query capabilities**: Some NoSQL databases lack complex query and aggregation support or use specific query languages. |
||||
- **Weaker consistency**: Many NoSQL databases follow the BASE (Basically Available, Soft state, Eventual consistency) properties that provide weaker consistency guarantees than ACID-compliant databases. |
||||
|
||||
## MongoDB: A NoSQL Database |
||||
|
||||
This guide focuses on MongoDB, a popular NoSQL database that uses a document-based data model. MongoDB has been designed with flexibility, performance, and scalability in mind. With its JSON-like data format (BSON) and powerful querying capabilities, MongoDB is an excellent choice for modern applications dealing with diverse and large-scale data. |
||||
|
||||
- [@article@SQL vs NoSQL: The Differences](https://www.sitepoint.com/sql-vs-nosql-differences/) |
||||
- [@article@SQL vs. NoSQL Databases: What’s the Difference?](https://www.ibm.com/blog/sql-vs-nosql/) |
||||
- [@article@NoSQL vs. SQL Databases](https://www.mongodb.com/nosql-explained/nosql-vs-sql) |
||||
- [@feed@Explore top posts about NoSQL](https://app.daily.dev/tags/nosql?ref=roadmapsh) |
||||
- [@article@Understanding SQL vs NoSQL Databases](https://www.mongodb.com/resources/basics/databases/nosql-explained/nosql-vs-sql) |
||||
- [@video@SQL vs NoSQL Databases in 4 mins](https://www.youtube.com/watch?v=_Ss42Vb1SU4) |
@ -1,60 +1,7 @@ |
||||
# Stored Procedures and Functions |
||||
|
||||
A SQL stored procedure is a set of SQL code that can be saved and reused. In other words, it's a precompiled object because it's compiled at a time when it's created on the database. Stored procedures can take parameters, process the tasks or query the database, and return a result. |
||||
Stored procedures and functions are precompiled database objects that encapsulate a set of SQL statements and logic. Stored procedures can perform complex operations and are typically used for data manipulation, while functions are designed to compute and return values. Both improve performance by reducing network traffic and allowing code reuse. They also enhance security by providing a layer of abstraction between the application and the database. |
||||
|
||||
Here's a basic example: |
||||
Learn more from the following resources: |
||||
|
||||
```sql |
||||
CREATE PROCEDURE getEmployeesBySalary |
||||
@minSalary int |
||||
AS |
||||
BEGIN |
||||
SELECT firstName, lastName |
||||
FROM Employees |
||||
WHERE salary > @minSalary |
||||
END |
||||
GO |
||||
``` |
||||
|
||||
To call this stored procedure, we would use: |
||||
|
||||
```sql |
||||
EXEC getEmployeesBySalary 50000 |
||||
``` |
||||
|
||||
## Functions |
||||
|
||||
A SQL function is a set of SQL statements that perform a specific task. Functions must return a value or result. We can use these functions in SELECT, INSERT, DELETE, UPDATE statements. |
||||
|
||||
There are two types of functions in SQL: |
||||
|
||||
- **Scalar functions**, which return a single value and can be used where single expressions are used. For instance: |
||||
|
||||
```sql |
||||
CREATE FUNCTION addNumbers(@a int, @b int) |
||||
RETURNS int |
||||
AS |
||||
BEGIN |
||||
RETURN @a + @b |
||||
END |
||||
``` |
||||
|
||||
- **Table-valued functions**, which return a table. They can be used in JOIN clauses as if they were a normal table. For example: |
||||
|
||||
```sql |
||||
CREATE FUNCTION getBooks (@authorID INT) |
||||
RETURNS TABLE |
||||
AS |
||||
RETURN ( |
||||
SELECT books.title, books.publicationYear |
||||
FROM books |
||||
WHERE books.authorID = @authorID |
||||
) |
||||
``` |
||||
|
||||
To call this function: |
||||
|
||||
```sql |
||||
SELECT title, publicationYear |
||||
FROM getBooks(3) |
||||
``` |
||||
- [@article@Stored Procedure vs Functions](https://www.shiksha.com/online-courses/articles/stored-procedure-vs-function-what-are-the-differences/) |
@ -1,60 +1,8 @@ |
||||
# Sub Queries |
||||
|
||||
In SQL, a subquery is a query embedded within another SQL query. You can alternately call it a nested or an inner query. The containing query is often referred to as the outer query. Subqueries are utilized to retrieve data that will be used in the main query as a condition to further restrict the data to be retrieved. |
||||
Subqueries, also known as nested queries or inner queries, are SQL queries embedded within another query. They can be used in various parts of SQL statements, such as SELECT, FROM, WHERE, and HAVING clauses. Subqueries allow for complex data retrieval and manipulation by breaking down complex queries into more manageable parts. They're particularly useful for creating dynamic criteria, performing calculations, or comparing sets of results. |
||||
|
||||
Subqueries can be used in various parts of a query, including: |
||||
Learn more from the following resources: |
||||
|
||||
- **SELECT** statement |
||||
- **FROM** clause |
||||
- **WHERE** clause |
||||
- **GROUP BY** clause |
||||
- **HAVING** clause |
||||
|
||||
## Syntax |
||||
|
||||
In general, the syntax can be written as: |
||||
|
||||
```sql |
||||
SELECT column_name [, column_name] |
||||
FROM table1 [, table2 ] |
||||
WHERE column_name OPERATOR |
||||
(SELECT column_name [, column_name] |
||||
FROM table1 [, table2 ] |
||||
[WHERE]) |
||||
``` |
||||
|
||||
## Types of Subqueries |
||||
|
||||
1. **Scalar Subquery**: It returns single value. |
||||
|
||||
```sql |
||||
SELECT name |
||||
FROM student |
||||
WHERE roll_id = (SELECT roll_id FROM student WHERE name='John'); |
||||
``` |
||||
|
||||
2. **Row subquery**: It returns a single row or multiple rows of two or more values. |
||||
|
||||
```sql |
||||
SELECT * FROM student |
||||
WHERE (roll_id, age)=(SELECT MIN(roll_id),MIN(age) FROM student); |
||||
``` |
||||
|
||||
3. **Column subquery**: It returns single column value with multiple rows and one column. |
||||
|
||||
```sql |
||||
SELECT name, age FROM student |
||||
WHERE name in (SELECT name FROM student); |
||||
``` |
||||
|
||||
4. **Table subquery**: It returns more than one row and more than one column. |
||||
|
||||
```sql |
||||
SELECT name, age |
||||
FROM student |
||||
WHERE (name, age) IN (SELECT name, age FROM student); |
||||
``` |
||||
|
||||
## General Note |
||||
|
||||
Subqueries can be either correlated or uncorrelated. A correlated subquery is a subquery that uses values from the outer query. Conversely, an uncorrelated subquery is a subquery that can be run independently of the outer query. |
||||
- [@article@SQL Sub Queries](https://www.tutorialspoint.com/sql/sql-sub-queries.htm) |
||||
- [@video@Advanced SQL Tutorial | Subqueries](https://www.youtube.com/watch?v=m1KcNV-Zhmc) |
@ -1,61 +1,8 @@ |
||||
# SUBSTRING |
||||
|
||||
The SQL `SUBSTRING` function is used to extract a part of a string, where you can specify the start position and the length of the text. This function can be very beneficial when you only need a specific part of a string. |
||||
SUBSTRING is a SQL function used to extract a portion of a string. It allows you to specify the starting position and length of the substring you want to extract. This function is valuable for data manipulation, parsing, and formatting tasks. The exact syntax may vary slightly between database systems, but the core functionality remains consistent, making it a versatile tool for working with string data in databases. |
||||
|
||||
## Syntax |
||||
Learn more from the following resources: |
||||
|
||||
The standardized SQL syntax for `SUBSTRING` is as follows: |
||||
|
||||
```sql |
||||
SUBSTRING(string, start, length) |
||||
``` |
||||
|
||||
Where: |
||||
|
||||
- `string` is the source string from which you want to extract. |
||||
- `start` is the position to start extraction from. The first position in the string is always 1. |
||||
- `length` is the number of characters to extract. |
||||
|
||||
## Usage |
||||
|
||||
For instance, if you want to extract the first 5 characters from the string 'Hello World': |
||||
|
||||
```sql |
||||
SELECT SUBSTRING('Hello World', 1, 5) as ExtractedString; |
||||
``` |
||||
|
||||
Result: |
||||
|
||||
```sql |
||||
| ExtractedString | |
||||
| --------------- | |
||||
| Hello | |
||||
``` |
||||
|
||||
You can also use `SUBSTRING` on table columns, like so: |
||||
|
||||
```sql |
||||
SELECT SUBSTRING(column_name, start, length) FROM table_name; |
||||
``` |
||||
|
||||
## SUBSTRING with FROM and FOR |
||||
|
||||
In some database systems (like PostgreSQL and SQL Server), the `SUBSTRING` function uses a different syntax: |
||||
|
||||
```sql |
||||
SUBSTRING(string FROM start FOR length) |
||||
``` |
||||
|
||||
This format functions the same way as the previously mentioned syntax. |
||||
|
||||
For example: |
||||
|
||||
```sql |
||||
SELECT SUBSTRING('Hello World' FROM 1 FOR 5) as ExtractedString; |
||||
``` |
||||
|
||||
This would yield the same result as the previous example - 'Hello'. |
||||
|
||||
## Note |
||||
|
||||
SQL is case-insensitive, meaning `SUBSTRING`, `substring`, and `Substring` will all function the same way. |
||||
- [@video@Advanced SQL Tutorial | String Functions + Use Cases](https://www.youtube.com/watch?v=GQj6_6V_jVA) |
||||
- [@article@SQL SUBSTRING](https://www.w3schools.com/sql/func_sqlserver_substring.asp) |
@ -1,58 +1,8 @@ |
||||
# SUM |
||||
|
||||
The `SUM()` function in SQL is used to calculate the sum of a column. This function allows you to add up a column of numbers in an SQL table. |
||||
SUM is an aggregate function in SQL used to calculate the total of a set of values. It's commonly used with numeric columns in combination with GROUP BY clauses to compute totals for different categories or groups within the data. SUM is essential for financial calculations, statistical analysis, and generating summary reports from database tables. It ignores NULL values and can be used in conjunction with other aggregate functions for complex data analysis. |
||||
|
||||
The syntax for SUM is as follows: |
||||
Learn more from the following resources: |
||||
|
||||
```sql |
||||
SELECT SUM(column_name) FROM table_name; |
||||
``` |
||||
|
||||
Where `column_name` is the name of the column you want to calculate the sum of, and `table_name` is the name of the table where the column is. |
||||
|
||||
For example, consider the following `ORDER` table: |
||||
|
||||
``` |
||||
| OrderID | Company | Quantity | |
||||
|------------|---------|----------| |
||||
| 1 | A | 30 | |
||||
| 2 | B | 15 | |
||||
| 3 | A | 20 | |
||||
``` |
||||
|
||||
If you want to find the total quantity, you can use `SUM()`: |
||||
|
||||
```sql |
||||
SELECT SUM(Quantity) AS TotalQuantity FROM Order; |
||||
``` |
||||
|
||||
Output will be: |
||||
|
||||
``` |
||||
| TotalQuantity | |
||||
|---------------| |
||||
| 65 | |
||||
``` |
||||
|
||||
**Note:** The `SUM()` function skips NULL values. |
||||
|
||||
One of the common use cases of `SUM()` function is in conjunction with `GROUP BY` to get the sum for each group of rows. |
||||
|
||||
Example: |
||||
|
||||
```sql |
||||
SELECT Company, SUM(Quantity) AS TotalQuantity |
||||
FROM Order |
||||
GROUP BY Company; |
||||
``` |
||||
|
||||
This will give us the sum of `Quantity` for each `Company` in the `Order` table. |
||||
|
||||
``` |
||||
| Company | TotalQuantity | |
||||
|-----------|----------------| |
||||
| A | 50 | |
||||
| B | 15 | |
||||
``` |
||||
|
||||
Notably, in all databases, including MySQL, PostgreSQL, and SQLite, the `SUM()` function operates the same way. |
||||
- [@article@SQL SUM Function](https://www.w3schools.com/sql/sql_sum.asp) |
||||
- [@article@SQL SUM](https://www.studysmarter.co.uk/explanations/computer-science/databases/sql-sum/) |
@ -1,48 +1,8 @@ |
||||
# Table |
||||
|
||||
In SQL, a table is a collection of related data held in a structured format within a database. It consists of rows (records) and columns (fields). |
||||
A table is a fundamental structure for organizing data in a relational database. It consists of rows (records) and columns (fields), representing a collection of related data entries. Tables define the schema of the data, including data types and constraints. They are the primary objects for storing and retrieving data in SQL databases, and understanding table structure is crucial for effective database design and querying. |
||||
|
||||
A table is defined by its name and the nature of data it will hold, i.e., each field has a name and a specific data type. |
||||
Learn more from the following resources: |
||||
|
||||
## Table Creation |
||||
|
||||
You can create a table using the `CREATE TABLE` SQL statement. The syntax is as follows: |
||||
|
||||
```sql |
||||
CREATE TABLE table_name ( |
||||
column1 datatype, |
||||
column2 datatype, |
||||
column3 datatype, |
||||
.... |
||||
); |
||||
``` |
||||
Here, `table_name` is the name of the table, `column1`, `column2`... are the names of the columns, and `datatype` specifies the type of data the column can hold (e.g., varchar, integer, date, etc.). |
||||
|
||||
## Table Manipulation |
||||
|
||||
Once a table has been created, the `INSERT INTO` statement is used to insert new rows of data into the table. |
||||
|
||||
```sql |
||||
INSERT INTO table_name (column1, column2, column3,...) |
||||
VALUES (value1, value2, value3,...); |
||||
``` |
||||
The `SELECT` statement is used to select data from the table. |
||||
|
||||
```sql |
||||
SELECT column1, column2,... |
||||
FROM table_name; |
||||
``` |
||||
The `UPDATE` statement is used to modify existing records. |
||||
|
||||
```sql |
||||
UPDATE table_name |
||||
SET column1 = value1, column2 = value2,... |
||||
WHERE condition; |
||||
``` |
||||
And, finally, the `DELETE` statement is used to delete existing records. |
||||
|
||||
```sql |
||||
DELETE FROM table_name WHERE condition; |
||||
``` |
||||
|
||||
These basic operations allow for full manipulation of tables in SQL, letting users to manage their data effectively. |
||||
- [@article@Table (Database)](https://en.wikipedia.org/wiki/Table_(database)) |
||||
- [@article@Introduction to Tables](https://support.microsoft.com/en-gb/office/introduction-to-tables-78ff21ea-2f76-4fb0-8af6-c318d1ee0ea7) |
@ -1,65 +1,6 @@ |
||||
# TIME |
||||
|
||||
In SQL, TIME data type is used to store time values in the database. It allows you to store hours, minutes, and seconds. The format of a TIME is 'HH:MI:SS'. |
||||
The TIME data type in SQL is used to store time values, typically in the format of hours, minutes, and seconds. It's useful for recording specific times of day without date information. SQL provides various functions for manipulating and comparing TIME values, allowing for time-based calculations and queries. The exact range and precision of TIME can vary between different database management systems. |
||||
|
||||
## Syntax |
||||
Learn more from the following resources: |
||||
|
||||
Here is the basic syntax to create a field with TIME data type in SQL: |
||||
```sql |
||||
CREATE TABLE table_name ( |
||||
column_name TIME |
||||
); |
||||
``` |
||||
|
||||
You can store data using the following syntax: |
||||
```sql |
||||
INSERT INTO table_name (column_name) values ('17:34:20'); |
||||
``` |
||||
|
||||
## Range |
||||
|
||||
The time range in SQL is '00:00:00' to '23:59:59'. |
||||
|
||||
## Fetching Data |
||||
|
||||
To fetch the data you can use the SELECT statement. For example: |
||||
|
||||
```sql |
||||
SELECT column_name FROM table_name; |
||||
``` |
||||
It will return the time values from the table. |
||||
|
||||
## Functions |
||||
|
||||
SQL provides several functions to work with the TIME data type. Some of them include: |
||||
|
||||
## CURTIME() |
||||
|
||||
Return the current time. |
||||
```sql |
||||
SELECT CURTIME(); |
||||
``` |
||||
|
||||
## ADDTIME() |
||||
|
||||
Add time values. |
||||
```sql |
||||
SELECT ADDTIME('2007-12-31 23:59:59','1 1:1:1'); |
||||
``` |
||||
|
||||
## TIMEDIFF() |
||||
|
||||
Subtract time values. |
||||
```sql |
||||
SELECT TIMEDIFF('2000:01:01 00:00:00', '2000:01:01 00:01:01'); |
||||
``` |
||||
|
||||
## Conversion |
||||
|
||||
Conversion of TIME data type is also possible in SQL. It can be converted into other data types, like INT, and vice versa. Here is a conversion example of TIME to INT: |
||||
|
||||
```sql |
||||
SELECT TIME_TO_SEC('22:23:00'); |
||||
``` |
||||
|
||||
This was a brief summary about "TIME" in SQL. |
@ -1,45 +1,8 @@ |
||||
# Transaction Isolation Levels |
||||
|
||||
SQL supports four transaction isolation levels, each differing in how it deals with concurrency and locks to protect the integrity of the data. Each level makes different trade-offs between consistency and performance. Here is a brief of these isolation levels with relevant SQL statements. |
||||
Transaction isolation levels in SQL define the degree to which the operations in one transaction are visible to other concurrent transactions. There are typically four standard levels: Read Uncommitted, Read Committed, Repeatable Read, and Serializable. Each level provides different trade-offs between data consistency and concurrency. Understanding and correctly setting isolation levels is crucial for maintaining data integrity and optimizing performance in multi-user database environments. |
||||
|
||||
1. **READ UNCOMMITTED** |
||||
This is the lowest level of isolation. One transaction may read not yet committed changes made by other transaction, also known as "Dirty Reads". Here's an example of how to set this level: |
||||
Learn more from the following resources: |
||||
|
||||
```sql |
||||
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; |
||||
BEGIN TRANSACTION; |
||||
-- Execute your SQL commands here |
||||
COMMIT; |
||||
``` |
||||
|
||||
2. **READ COMMITTED** |
||||
A transaction only sees data changes committed before it started, averting "Dirty Reads". However, it may experience "Non-repeatable Reads", i.e. if a transaction reads the same row multiple times, it might get a different result each time. Here's how to set this level: |
||||
|
||||
```sql |
||||
SET TRANSACTION ISOLATION LEVEL READ COMMITTED; |
||||
BEGIN TRANSACTION; |
||||
-- Execute your SQL commands here |
||||
COMMIT; |
||||
``` |
||||
|
||||
3. **REPEATABLE READ** |
||||
Here, once a transaction reads a row, any other transaction's writes (changes) onto those rows are blocked until the first transaction is finished, preventing "Non-repeatable Reads". However, "Phantom Reads" may still occur. Here's how to set this level: |
||||
|
||||
```sql |
||||
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; |
||||
BEGIN TRANSACTION; |
||||
-- Execute your SQL commands here |
||||
COMMIT; |
||||
``` |
||||
|
||||
4. **SERIALIZABLE** |
||||
This is the highest level of isolation. It avoids "Dirty Reads", "Non-repeatable Reads" and "Phantom Reads". This is done by fully isolating one transaction from others: read and write locks are acquired on data that are used in a query, preventing other transactions from accessing the respective data. Here's how to set this level: |
||||
|
||||
```sql |
||||
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; |
||||
BEGIN TRANSACTION; |
||||
-- Execute your SQL commands here |
||||
COMMIT; |
||||
``` |
||||
|
||||
Remember, higher levels of isolation usually provide more consistency but can potentially decrease performance due to increased waiting times for locks. |
||||
- [@article@Everything you always wanted to know about SQL isolation levels](https://www.cockroachlabs.com/blog/sql-isolation-levels-explained/) |
||||
- [@article@Isolation Levels in SQL Server](https://www.sqlservercentral.com/articles/isolation-levels-in-sql-server) |
@ -1,52 +1,8 @@ |
||||
# Transactions |
||||
|
||||
A `transaction` in SQL is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program. |
||||
Transactions in SQL are units of work that group one or more database operations into a single, atomic unit. They ensure data integrity by following the ACID properties: Atomicity (all or nothing), Consistency (database remains in a valid state), Isolation (transactions don't interfere with each other), and Durability (committed changes are permanent). Transactions are essential for maintaining data consistency in complex operations and handling concurrent access to the database. |
||||
|
||||
Transactions are used to ensure data integrity and to handle database errors while processing. SQL transactions are controlled by the following commands: |
||||
Learn more from the following resources: |
||||
|
||||
- `BEGIN TRANSACTION` |
||||
- `COMMIT` |
||||
- `ROLLBACK` |
||||
|
||||
## BEGIN TRANSACTION |
||||
|
||||
This command is used to start a new transaction. |
||||
|
||||
```sql |
||||
BEGIN TRANSACTION; |
||||
``` |
||||
|
||||
## COMMIT |
||||
|
||||
The `COMMIT` command is the transactional command used to save changes invoked by a transaction to the database. |
||||
|
||||
```sql |
||||
COMMIT; |
||||
``` |
||||
When you commit the transaction, the changes are permanently saved in the database. |
||||
|
||||
## ROLLBACK |
||||
|
||||
The `ROLLBACK` command is the transactional command used to undo transactions that have not already been saved to the database. |
||||
|
||||
```sql |
||||
ROLLBACK; |
||||
``` |
||||
|
||||
When you roll back a transaction, all changes made since the last commit in the database are undone, and the database is rolled back to the state it was in at the last commit. |
||||
|
||||
## Transaction Example |
||||
```sql |
||||
BEGIN TRANSACTION; |
||||
|
||||
UPDATE Accounts SET Balance = Balance - 100 WHERE id = 1; |
||||
UPDATE Accounts SET Balance = Balance + 100 WHERE id = 2; |
||||
|
||||
IF @@ERROR = 0 |
||||
COMMIT; |
||||
ELSE |
||||
ROLLBACK; |
||||
``` |
||||
In this example, we are transferring 100 units from account 1 to account 2 inside a transaction. If any errors occurred during any of the update statements (captured by `@@ERROR`), the transaction is rolled back, otherwise, it is committed. |
||||
|
||||
Remember that for the transaction to be successful, all commands must execute successfully. If any command fails, the transaction fails, the database state is left unchanged and an error is returned. |
||||
- [@articles@Transactions](https://www.tutorialspoint.com/sql/sql-transactions.htm) |
||||
- [@article@A Guide to ACID Properties in Database Management Systems](https://www.mongodb.com/resources/basics/databases/acid-transactions) |
@ -1,54 +1,7 @@ |
||||
# Unique |
||||
|
||||
The `UNIQUE` constraint ensures that all values in a column are different; that is, each value in the column should occur only once. |
||||
`UNIQUE` is a constraint in SQL used to ensure that all values in a column or a set of columns are distinct. When applied to a column or a combination of columns, it prevents duplicate values from being inserted into the table. This constraint is crucial for maintaining data integrity, especially for fields like email addresses, usernames, or product codes where uniqueness is required. `UNIQUE` constraints can be applied during table creation or added later, and they automatically create an index on the specified column(s) for improved query performance. Unlike `PRIMARY KEY` constraints, `UNIQUE` columns can contain `NULL` values (unless explicitly disallowed), and a table can have multiple `UNIQUE` constraints. |
||||
|
||||
Both the `UNIQUE` and `PRIMARY KEY` constraints provide a guarantee for uniqueness for a column or set of columns. However, a primary key cannot contain `NULL` since it uniquely identifies each row, and each table can have only one primary key. On the other hand, a `UNIQUE` constraint allows for one `NULL` value, and a table can have multiple `UNIQUE` constraints. |
||||
Learn more from the following resources: |
||||
|
||||
## Syntax |
||||
```sql |
||||
CREATE TABLE table_name ( |
||||
column1 data_type UNIQUE, |
||||
column2 data_type, |
||||
column3 data_type, |
||||
.... |
||||
); |
||||
``` |
||||
|
||||
Here, `UNIQUE` is the constraint's name, whereas `column1` and `data_type` refer to the column and data type for which we're setting the constraint, respectively. |
||||
|
||||
## Example |
||||
|
||||
Suppose, for instance, we are creating a table named "Employees". We want the "Email" column to contain only unique values to avoid any duplication in email addresses. |
||||
|
||||
Here's how we can impose a `UNIQUE` constraint on the "Email" column: |
||||
|
||||
```sql |
||||
CREATE TABLE Employees ( |
||||
ID int NOT NULL, |
||||
Name varchar (255) NOT NULL, |
||||
Email varchar (255) UNIQUE |
||||
); |
||||
``` |
||||
|
||||
In this SQL command, we are telling the SQL server that the "Email" column cannot have the same value in two or more rows. |
||||
|
||||
## Adding a Unique Constraint to an Existing Table |
||||
|
||||
To add a `UNIQUE` constraint to an existing table, you would use the `ALTER TABLE` command. Here is the syntax: |
||||
|
||||
```sql |
||||
ALTER TABLE table_name |
||||
ADD UNIQUE (column1, column2, ...); |
||||
``` |
||||
Here, `table_name` is the name of the table on which we're defining the constraint, and `column1`, `column2`, etc., are the names of the columns included in the constraint. |
||||
|
||||
## Dropping a Unique Constraint |
||||
|
||||
The `ALTER TABLE` command is also used to drop a `UNIQUE` constraint. The syntax to drop a `UNIQUE` constraint is: |
||||
|
||||
```sql |
||||
ALTER TABLE table_name |
||||
DROP CONSTRAINT constraint_name; |
||||
``` |
||||
|
||||
Here, `constraint_name` is the name of the `UNIQUE` constraint that you want to drop. |
||||
- [@article@SQL UNIQUE Constraint](https://www.w3schools.com/sql/sql_unique.asp) |
@ -1,53 +1,8 @@ |
||||
# UPDATE |
||||
|
||||
The `UPDATE` command in SQL is used to modify the existing records in a table. This command is useful when you need to update existing data within a database. |
||||
The UPDATE statement in SQL is used to modify existing records in a table. It allows you to change the values of one or more columns based on specified conditions. The basic syntax includes specifying the table name, the columns to be updated with their new values, and optionally, a WHERE clause to filter which rows should be affected. UPDATE can be used in conjunction with subqueries, joins, and CTEs (Common Table Expressions) for more complex data modifications. It's important to use UPDATE carefully, especially with the WHERE clause, to avoid unintended changes to data. In transactional databases, UPDATE operations can be rolled back if they're part of a transaction that hasn't been committed. |
||||
|
||||
Here are important points to remember before updating records in SQL: |
||||
Learn more from the following resources: |
||||
|
||||
- The `WHERE` clause in the `UPDATE` statement specifies which records to modify. If you omit the `WHERE` clause, all records in the table will be updated! |
||||
|
||||
- Be careful when updating records in SQL. If you inadvertently run an `UPDATE` statement without a `WHERE` clause, you will rewrite all the data in the table. |
||||
|
||||
## SQL UPDATE Syntax |
||||
|
||||
Here is a basic syntax of SQL UPDATE command: |
||||
|
||||
```sql |
||||
UPDATE table_name |
||||
SET column1 = value1, column2 = value2...., columnN = valueN |
||||
WHERE [condition]; |
||||
``` |
||||
|
||||
In this syntax: |
||||
|
||||
- `table_name`: Specifies the table where you want to update records. |
||||
- `SET`: This keyword is used to set the column values. |
||||
- `column1, column2... columnN`: These are the columns of the table that you want to change. |
||||
- `value1, value2... valueN`: These are the new values that you want to assign for your columns. |
||||
- `WHERE`: This clause specifies which records need to be updated. It selects records based on one or more conditions. |
||||
|
||||
## SQL UPDATE Example |
||||
|
||||
Let's assume we have the following `Students` table: |
||||
|
||||
| StudentID | FirstName | LastName | Age | |
||||
|-----------|-----------|----------|-----| |
||||
| 1 | John | Doe | 20 | |
||||
| 2 | Jane | Smith | 22 | |
||||
| 3 | Bob | Johnson | 23 | |
||||
|
||||
And we want to update the `Age` of the student with `StudentID` as 2. We can use the `UPDATE` command as follows: |
||||
|
||||
```sql |
||||
UPDATE Students |
||||
SET Age = 23 |
||||
WHERE StudentID = 2; |
||||
``` |
||||
|
||||
After executing the above SQL command, the `Age` of the student with `StudentID` 2 will be updated to 23. |
||||
|
||||
| StudentID | FirstName | LastName | Age | |
||||
|-----------|-----------|----------|-----| |
||||
| 1 | John | Doe | 20 | |
||||
| 2 | Jane | Smith | 23 | |
||||
| 3 | Bob | Johnson | 23 | |
||||
- [@article@SQL UPDATE Statement](https://www.w3schools.com/sql/sql_update.asp) |
||||
- [@article@Efficient column updates in SQL](https://www.atlassian.com/data/sql/how-to-update-a-column-based-on-a-filter-of-another-column) |
@ -1,18 +1,8 @@ |
||||
# UPDATE |
||||
|
||||
The `UPDATE` statement is used to modify existing data in a given table. <br/> |
||||
It can be done so with the query |
||||
|
||||
``` |
||||
UPDATE table_name |
||||
SET column1 = value1, column2 = value2, ... |
||||
WHERE condition; |
||||
``` |
||||
|
||||
- _Keep in mind that **SET** and **WHERE** are also commands to assign a new value(SET) only if the condition is met(WHERE)_ |
||||
|
||||
Omitting the `WHERE` clause will update **all** rows in the table. |
||||
|
||||
Visit the following resources to learn more: |
||||
|
||||
- [@article@W3Schools SQL UPDATE Statement Doc](https://www.w3schools.com/sql/sql_update.asp) |
||||
# UPDATE |
||||
|
||||
The UPDATE statement in SQL is used to modify existing records in a table. It allows you to change the values of one or more columns based on specified conditions. The basic syntax includes specifying the table name, the columns to be updated with their new values, and optionally, a WHERE clause to filter which rows should be affected. UPDATE can be used in conjunction with subqueries, joins, and CTEs (Common Table Expressions) for more complex data modifications. It's important to use UPDATE carefully, especially with the WHERE clause, to avoid unintended changes to data. In transactional databases, UPDATE operations can be rolled back if they're part of a transaction that hasn't been committed. |
||||
|
||||
Learn more from the following resources: |
||||
|
||||
- [@article@SQL UPDATE Statement](https://www.w3schools.com/sql/sql_update.asp) |
||||
- [@article@Efficient column updates in SQL](https://www.atlassian.com/data/sql/how-to-update-a-column-based-on-a-filter-of-another-column) |
@ -1,35 +1,8 @@ |
||||
# UPPER |
||||
|
||||
`UPPER()` is a built-in string function in SQL. As the name suggests, it is used to convert all letters in a specified string to uppercase. If the string already consists of all uppercase characters, the function will return the original string. |
||||
UPPER() is a string function in SQL used to convert all characters in a specified string to uppercase. This function is particularly useful for data normalization, case-insensitive comparisons, or formatting output. UPPER() typically works on alphabetic characters and leaves non-alphabetic characters unchanged. It's often used in SELECT statements to display data, in WHERE clauses for case-insensitive searches, or in data manipulation operations. Most SQL databases also provide a complementary LOWER() function for converting to lowercase. When working with international character sets, it's important to be aware of potential locale-specific behavior of UPPER(). |
||||
|
||||
Syntax for this function is: |
||||
Learn more from the following resources: |
||||
|
||||
```sql |
||||
UPPER(string) |
||||
``` |
||||
|
||||
Here 'string' can be a string value or a column of a table of string(s) type. |
||||
|
||||
Let's assume a table 'students' with column 'name' as below: |
||||
|
||||
| name | |
||||
|------------| |
||||
| John Doe | |
||||
| Jane Smith | |
||||
| Kelly Will | |
||||
|
||||
If we want all the names in uppercase, we'll use `UPPER()` function as: |
||||
|
||||
```sql |
||||
SELECT UPPER(name) as 'Upper Case Name' FROM students; |
||||
``` |
||||
|
||||
And we will get: |
||||
|
||||
| Upper Case Name | |
||||
|----------------| |
||||
| JOHN DOE | |
||||
| JANE SMITH | |
||||
| KELLY WILL | |
||||
|
||||
So, `UPPER()` function helps us to bring an entire string to uppercase for easier comparison and sorting. |
||||
- [@article@SQL Server UPPER Function](https://www.w3schools.com/sql/func_sqlserver_upper.asp) |
||||
- [@article@How to Convert a String to Uppercase in SQL](https://learnsql.com/cookbook/how-to-convert-a-string-to-uppercase-in-sql/) |
@ -1,41 +1,8 @@ |
||||
# Using Indexes |
||||
|
||||
Indexes in SQL are used as a way to quicken the rate of retrieval operations on a database table. Much like the index in a book, SQL indexes allow the database program to find the data without needing to go through every row in a table and thus improves performance. |
||||
Indexes in SQL are database objects that improve the speed of data retrieval operations on database tables. They work similarly to an index in a book, allowing the database engine to quickly locate data without scanning the entire table. Proper use of indexes can significantly enhance query performance, especially for large tables. However, they come with trade-offs: while they speed up reads, they can slow down write operations (INSERT, UPDATE, DELETE) as the index also needs to be updated. Common types include B-tree indexes (default in most systems), bitmap indexes, and full-text indexes. Understanding when and how to create indexes is crucial for database optimization. This involves analyzing query patterns, understanding the data distribution, and balancing the needs of different types of operations on the database. |
||||
|
||||
## Types of Indexes: |
||||
Learn more from the following resources: |
||||
|
||||
1. **Single-Column Indexes:** |
||||
|
||||
These are created based on only one table column. The syntax for creating a single column index is as follows: |
||||
``` |
||||
CREATE INDEX index_name |
||||
ON table_name (column1); |
||||
``` |
||||
|
||||
2. **Unique Indexes:** |
||||
|
||||
They ensure the data contained in a column or a combination of two or more columns is unique. Syntax to create unique index is as follows: |
||||
``` |
||||
CREATE UNIQUE INDEX index_name |
||||
ON table_name (column1, column2...); |
||||
``` |
||||
|
||||
3. **Composite Indexes:** |
||||
|
||||
These are based on two or more columns of a table. It's important to note that, the order of columns in the definition of an index is important. Syntax to create a Composite Indexes is as follows: |
||||
``` |
||||
CREATE INDEX index_name |
||||
ON table_name (column1, column2); |
||||
``` |
||||
|
||||
4. **Implicit Indexes:** |
||||
|
||||
These are indexes that are automatically created by the database server when an object is defined. For example, when a primary key is defined. |
||||
|
||||
## How Indexes Work |
||||
|
||||
SQL indexes work by storing a part of a table's data in a place where it can be accessed extremely swiftly. The index holds the column value, and the location of the record itself. This is similar to how an index in a book stores the word, and the page number on which the word can be found. |
||||
|
||||
## Considerations |
||||
|
||||
While they do provide a significant advantage, they also require additional storage and can slow down the rate of updates and inserts into a database. As such, indexes should be used judiciously, taking into consideration the nature of the data in the table and the kinds of queries that will be used. |
||||
- [@article@What is an index in SQL?](https://stackoverflow.com/questions/2955459/what-is-an-index-in-sql) |
||||
- [@video@SQL Indexes - Definition, Examples, and Tips](https://www.youtube.com/watch?v=NZgfYbAmge8) |
@ -1,54 +1,14 @@ |
||||
# Views |
||||
|
||||
SQL views are virtual tables that do not store data directly. They are essentially a saved SQL query and can pull data from multiple tables or just present the data from one table in a different way. |
||||
Views in SQL are virtual tables based on the result set of an SQL statement. They act as a saved query that can be treated like a table, offering several benefits: |
||||
|
||||
## Creating Views |
||||
- Simplifying complex queries by encapsulating joins and subqueries |
||||
- Providing an additional security layer by restricting access to underlying tables |
||||
- Presenting data in a more relevant format for specific users or applications |
||||
|
||||
You can create a view using the `CREATE VIEW` statement. In the following example, a new view named `CustomerView` is created which contains customer's ID, name, and address from the `Customers` table: |
||||
Views can be simple (based on a single table) or complex (involving multiple tables, subqueries, or functions). Some databases support updatable views, allowing modifications to the underlying data through the view. Materialized views, available in some systems, store the query results, improving performance for frequently accessed data at the cost of additional storage and maintenance overhead. |
||||
|
||||
```sql |
||||
CREATE VIEW CustomerView AS |
||||
SELECT CustomerID, Name, Address |
||||
FROM Customers; |
||||
``` |
||||
Learn more from the following resources: |
||||
|
||||
## Querying Views |
||||
|
||||
After a view has been created, it can be used in the `FROM` clause of a `SELECT` statement, as if it's an actual table. For instance, to select all from `CustomerView`: |
||||
|
||||
```sql |
||||
SELECT * |
||||
FROM CustomerView; |
||||
``` |
||||
|
||||
## Updating Views |
||||
|
||||
The `CREATE OR REPLACE VIEW` statement is used to update a view. Consider the `CustomerView` we created earlier. If we want to include the customer's phone, we can update it as follows: |
||||
|
||||
```sql |
||||
CREATE OR REPLACE VIEW CustomerView AS |
||||
SELECT CustomerID, Name, Address, Phone |
||||
FROM Customers; |
||||
``` |
||||
|
||||
## Dropping Views |
||||
|
||||
To delete a view, use the `DROP VIEW` statement: |
||||
|
||||
```sql |
||||
DROP VIEW CustomerView; |
||||
``` |
||||
|
||||
Keep in mind that not all database systems support the `CREATE OR REPLACE VIEW` statement. Also, the updatability of a view depends on whether it includes functions, expressions, or multiple tables. Some databases might not let you update a view at all. |
||||
|
||||
## Restrictions |
||||
|
||||
There are a few restrictions to bear in mind when working with views. SQL views can't: |
||||
|
||||
- Contain a `ORDER BY` clause in the view definition |
||||
- Be indexed |
||||
- Have triggers or default values |
||||
|
||||
Each database may have its own specific limitations and capabilities with using views, so always refer to the official documentation for more information. |
||||
|
||||
Note: The above examples use a hypothetical `Customers` table. Replace this with your actual table name when trying these in your environment. |
||||
- [@video@SQL Views Tutorial](https://www.youtube.com/watch?v=cLSxasHg9WY) |
||||
- [@article@Views in SQL](https://www.datacamp.com/tutorial/views-in-sql) |
@ -1,54 +1,16 @@ |
||||
# What Are Relational Databases? |
||||
|
||||
A **relational database** is a type of database that stores and organizes data in a structured way. It uses a structure |
||||
that allows data to be identified and accessed in relation to other data in the database. Data in a relational database |
||||
is stored in various data tables, each of which has a unique key identifying every row. |
||||
Relational databases are a type of database management system (DBMS) that stores and provides access to data points that are related to one another. Based on the relational model introduced by E.F. Codd in 1970, they use a structure that allows data to be organized into tables with rows and columns. Key features include: |
||||
|
||||
- Use of SQL (Structured Query Language) for querying and managing data |
||||
- Support for ACID transactions (Atomicity, Consistency, Isolation, Durability) |
||||
- Enforcement of data integrity through constraints (e.g., primary keys, foreign keys) |
||||
- bility to establish relationships between tables, enabling complex queries and data retrieval |
||||
- Scalability and support for multi-user environments |
||||
|
||||
Examples of popular relational database systems include MySQL, PostgreSQL, Oracle, and Microsoft SQL Server. They are widely used in various applications, from small-scale projects to large enterprise systems, due to their reliability, consistency, and powerful querying capabilities. |
||||
|
||||
Relational databases are made up of a set of tables with data that fits into a predefined category. Each table has at |
||||
least one data category in a column, and each row contains a certain data instance for the categories defined in the |
||||
columns. |
||||
Learn more from the following resources: |
||||
|
||||
For example, consider an 'Employees' table: |
||||
|
||||
| EmployeeId | FirstName | LastName | Email | |
||||
|------------|-----------|----------|-----------------------| |
||||
| 1 | John | Doe | john.doe@example.com | |
||||
| 2 | Jane | Doe | jane.doe@example.com | |
||||
| 3 | Bob | Smith | bob.smith@example.com | |
||||
|
||||
In this table, 'EmployeeId', 'FirstName', 'LastName' and 'Email' are categories, and each row represents a specific |
||||
employee. |
||||
|
||||
## Relationships |
||||
|
||||
The term "relational database" comes from the concept of a relation—a set of tuples that the database organizes into |
||||
rows and columns. Each row in a table represents a relationship among a set of values. |
||||
|
||||
Relational databases use `keys` to create links between tables. A `primary key` is a unique identifier for a row of |
||||
data. A `foreign key` is a column or combination of columns used to establish and enforce a link between the data in two |
||||
tables. |
||||
|
||||
Consider an additional 'Orders' table: |
||||
|
||||
| OrderId | EmployeeId | Product | |
||||
|---------|------------|----------| |
||||
| 1 | 3 | Apples | |
||||
| 2 | 1 | Bananas | |
||||
| 3 | 2 | Cherries | |
||||
|
||||
In the 'Orders' table, 'EmployeeId' serves as the foreign key creating a relationship between 'Orders' and 'Employees'. |
||||
This allows queries that involve data in both tables, like "Find all orders placed by John Doe". |
||||
|
||||
```sql |
||||
SELECT Orders.OrderId, Orders.Product, Employees.FirstName, Employees.LastName |
||||
FROM Orders |
||||
INNER JOIN Employees ON Orders.EmployeeId = Employees.EmployeeId; |
||||
``` |
||||
|
||||
The above SQL code is an example of how to retrieve data from a relational database using a `JOIN` clause to combine |
||||
rows from two or more tables. |
||||
|
||||
Overall, relational databases provide a powerful mechanism for defining relationships within data and enabling efficient |
||||
data retrieval. |
||||
- [@video@What is a relational database?](https://www.youtube.com/watch?v=OqjJjpjDRLc) |
||||
- [@article@What is a relational database - AWS](https://aws.amazon.com/relational-database/) |
Loading…
Reference in new issue