From dcfa8f82eb6fad71159faa2b1afc32543e809dd3 Mon Sep 17 00:00:00 2001 From: Jivan <137729176+Jivanjamadar@users.noreply.github.com> Date: Sat, 9 Nov 2024 13:03:03 +0530 Subject: [PATCH 01/11] Create PrioritySearch.md --- docs/algorithms/Searching Algorithms/PrioritySearch.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 docs/algorithms/Searching Algorithms/PrioritySearch.md diff --git a/docs/algorithms/Searching Algorithms/PrioritySearch.md b/docs/algorithms/Searching Algorithms/PrioritySearch.md new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/docs/algorithms/Searching Algorithms/PrioritySearch.md @@ -0,0 +1 @@ + From f80305c4daa921a4b6ae723b4cf5f784a8ff217a Mon Sep 17 00:00:00 2001 From: Jivan <137729176+Jivanjamadar@users.noreply.github.com> Date: Sat, 9 Nov 2024 13:10:01 +0530 Subject: [PATCH 02/11] Update PrioritySearch.md --- .../Searching Algorithms/PrioritySearch.md | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) diff --git a/docs/algorithms/Searching Algorithms/PrioritySearch.md b/docs/algorithms/Searching Algorithms/PrioritySearch.md index 8b1378917..552215b54 100644 --- a/docs/algorithms/Searching Algorithms/PrioritySearch.md +++ b/docs/algorithms/Searching Algorithms/PrioritySearch.md @@ -1 +1,121 @@ +--- + +id: Priority search algorithm +sidebar_position: 6 +title: Priority search +sidebar_label: Priority search algorithm + +--- + +## Definition πŸ“– + +**Priority search** is a search algorithm that is used for efficiently finding the closest point in a 2D plane to a given query point, using an ordered set of rectangles. It is particularly useful in scenarios where you need to search a large set of rectangles or intervals efficiently. The algorithm works by partitioning a set of 2D rectangles or intervals using priority values, allowing for faster querying than a brute-force search. + +## Characteristics ✨ + +- **Efficient for Rectangles**: + - Priority search is designed specifically for searching within a set of rectangles in a 2D plane, where each rectangle is associated with a priority value. + +- **Optimized for Range Queries**: + - The algorithm helps efficiently find the rectangle with the smallest priority value that contains a given point. + +- **Use of Data Structures**: + - The algorithm typically uses a combination of data structures such as a priority search tree (a variant of a binary search tree) or a segment tree to optimize the search process. + +- **Ordered Rectangles**: + - The rectangles are sorted in terms of their priority values, which enables the search process to be faster and more efficient. + +## Time Complexity ⏱️ + +- **Best Case: `O(log n)`** 🌟 + If the target rectangle is found early in the search process, it leads to an efficient query time. + +- **Average Case: `O(log n)`** πŸ”„ + In general, the search algorithm operates in logarithmic time complexity, making it faster than brute-force search methods. + +- **Worst Case: `O(n)`** πŸ’₯ + In the worst-case scenario, if the query point lies outside the regions covered by the rectangles or if all rectangles need to be checked, the time complexity could degrade to linear time. + +## Space Complexity πŸ’Ύ + +- **Space Complexity: `O(n)`** + Priority search typically requires space for storing the rectangles and their associated priority values, along with any auxiliary data structures (such as a tree or heap) used for efficient querying. + +## C++ Implementation πŸ’» + +Here’s a simple implementation of priority search in C++: + +```cpp +#include +#include +#include +using namespace std; + +struct Rectangle { + int x1, y1, x2, y2, priority; +}; + +int prioritySearch(const vector& rectangles, int targetX, int targetY) { + // Sort rectangles by priority + vector sortedRectangles = rectangles; + sort(sortedRectangles.begin(), sortedRectangles.end(), [](const Rectangle& a, const Rectangle& b) { + return a.priority < b.priority; + }); + + // Find the first rectangle that contains the target point + for (const auto& rect : sortedRectangles) { + if (targetX >= rect.x1 && targetX <= rect.x2 && targetY >= rect.y1 && targetY <= rect.y2) { + return rect.priority; + } + } + return -1; // No rectangle contains the point +} + +int main() { + vector rectangles = { + {0, 0, 2, 2, 1}, + {1, 1, 3, 3, 2}, + {2, 2, 4, 4, 3} + }; + int targetX = 2, targetY = 2; + + int priority = prioritySearch(rectangles, targetX, targetY); + + if (priority != -1) + cout << "Rectangle found with priority " << priority << endl; + else + cout << "No rectangle contains the point" << endl; + + return 0; +} +``` +## Applications of Priority Search 🌐 +**Geographical Information Systems (GIS):** + - Used to find the closest feature (like a region or building) in a GIS, given a point location. +**Computer Graphics:** + - In graphics applications, priority search can be useful for collision detection or determining the nearest object in a 2D plane. +**Database Management:** + - Priority search is used in databases to efficiently query for spatial data that is organized by priority or weight. +**Computer-Aided Design (CAD):** + - Used in CAD tools to find the nearest object or region that meets certain conditions (such as priority). + +## Advantages and Disadvantages +### Advantages: βœ… + +**Efficient for Sorted Data:** + - When rectangles are sorted by priority, the search can be much faster than a brute-force approach, with logarithmic time complexity in the average case. + +**Low Memory Overhead:** + - The space complexity is manageable, requiring only space for storing the rectangles and any auxiliary data structures. + +**Optimized for Range Queries:** + - Priority search is optimized for finding the nearest object in a range, making it ideal for applications like GIS and CAD. + +### Disadvantages: ⚠️ + +**Requires Sorted Data:** + - The efficiency of the algorithm depends on the rectangles being sorted by priority. If the data is not sorted, additional effort is required to sort it, which can reduce the overall performance. + +**Limited to 2D Search:** + - Priority search is primarily designed for 2D spatial queries and may not be suitable for higher-dimensional data without modification. From 5b5e6f4fcc0b84643f714b29cfeb48d8760420e1 Mon Sep 17 00:00:00 2001 From: Jivan <137729176+Jivanjamadar@users.noreply.github.com> Date: Sat, 9 Nov 2024 13:15:04 +0530 Subject: [PATCH 03/11] Update PrioritySearch.md --- .../Searching Algorithms/PrioritySearch.md | 26 ++++++++++++++----- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/docs/algorithms/Searching Algorithms/PrioritySearch.md b/docs/algorithms/Searching Algorithms/PrioritySearch.md index 552215b54..fb60fd227 100644 --- a/docs/algorithms/Searching Algorithms/PrioritySearch.md +++ b/docs/algorithms/Searching Algorithms/PrioritySearch.md @@ -1,12 +1,11 @@ - --- -id: Priority search algorithm -sidebar_position: 6 -title: Priority search -sidebar_label: Priority search algorithm +id: Priority-search-algorithm +sidebar_position: 5 +title: Priority Search algorithm +sidebar_label: Priority Search algorithm ---- +--- ## Definition πŸ“– @@ -91,15 +90,23 @@ int main() { } ``` ## Applications of Priority Search 🌐 + **Geographical Information Systems (GIS):** + - Used to find the closest feature (like a region or building) in a GIS, given a point location. + **Computer Graphics:** + - In graphics applications, priority search can be useful for collision detection or determining the nearest object in a 2D plane. + **Database Management:** + - Priority search is used in databases to efficiently query for spatial data that is organized by priority or weight. + **Computer-Aided Design (CAD):** - - Used in CAD tools to find the nearest object or region that meets certain conditions (such as priority). + - Used in CAD tools to find the nearest object or region that meets certain conditions (such as priority). + ## Advantages and Disadvantages ### Advantages: βœ… @@ -119,3 +126,8 @@ int main() { **Limited to 2D Search:** - Priority search is primarily designed for 2D spatial queries and may not be suitable for higher-dimensional data without modification. + +## Summary +Priority Search is an algorithm used for efficiently finding the closest rectangle to a query point in a 2D plane, where each rectangle is associated with a priority value. It sorts the rectangles by priority and searches for the one that contains the query point. + + From ae3c83676d551c3324689b063c1a0c9feb45b5bb Mon Sep 17 00:00:00 2001 From: Shriya Dindi <126611334+shriyadindi@users.noreply.github.com> Date: Sat, 9 Nov 2024 13:29:06 +0530 Subject: [PATCH 04/11] Update problemData.ts --- src/data/problemData.ts | 104 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) diff --git a/src/data/problemData.ts b/src/data/problemData.ts index 7cbbac9af..cc5663978 100644 --- a/src/data/problemData.ts +++ b/src/data/problemData.ts @@ -3872,6 +3872,110 @@ class Solution: return "".join(order) if len(order) == len(indegree) else "" `, }, +}, + bestMeetingPoint: { + title: "Best Meeting Point", + description: + "Given a grid where each cell represents a location in a city, find the best meeting point for all people. The best meeting point is the location that minimizes the total distance to all other people in the grid. The distance between two points is calculated using the Manhattan distance.", + examples: [ + { + input: "grid = [[1,0,0],[0,1,0],[0,0,1]]", + output: "2", + explanation: + "The best meeting point is at location (1, 1), which minimizes the sum of Manhattan distances to all people (1 + 1 + 1 = 3).", + }, + { + input: "grid = [[0,0,0],[0,1,0],[0,0,0]]", + output: "2", + explanation: + "The best meeting point is at (1, 1), which minimizes the sum of Manhattan distances to all other people in the grid.", + }, + ], + solution: { + cpp: ` + #include + #include + using namespace std; + + class Solution { + public: + int minTotalDistance(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector row, col; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) { + row.push_back(i); + col.push_back(j); + } + } + } + + sort(row.begin(), row.end()); + sort(col.begin(), col.end()); + + int medianRow = row[row.size() / 2], medianCol = col[col.size() / 2]; + int distance = 0; + for (int i = 0; i < row.size(); i++) { + distance += abs(row[i] - medianRow) + abs(col[i] - medianCol); + } + + return distance; + } + };`, + + java: ` + import java.util.*; + + class Solution { + public int minTotalDistance(int[][] grid) { + List row = new ArrayList<>(); + List col = new ArrayList<>(); + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + if (grid[i][j] == 1) { + row.add(i); + col.add(j); + } + } + } + + Collections.sort(row); + Collections.sort(col); + + int medianRow = row.get(row.size() / 2), medianCol = col.get(col.size() / 2); + int distance = 0; + for (int i = 0; i < row.size(); i++) { + distance += Math.abs(row.get(i) - medianRow) + Math.abs(col.get(i) - medianCol); + } + + return distance; + } + };`, + + python: ` + class Solution: + def minTotalDistance(self, grid: list[list[int]]) -> int: + row, col = [], [] + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] == 1: + row.append(i) + col.append(j) + + row.sort() + col.sort() + + medianRow = row[len(row) // 2] + medianCol = col[len(col) // 2] + + distance = 0 + for i in range(len(row)): + distance += abs(row[i] - medianRow) + abs(col[i] - medianCol) + + return distance + `, + }, }, }; From f7c21304af8ed89f0054a458ab4e15e510c55b15 Mon Sep 17 00:00:00 2001 From: Abhijit Motekar <109235675+AbhijitMotekar99@users.noreply.github.com> Date: Sat, 9 Nov 2024 16:06:05 +0530 Subject: [PATCH 05/11] Create Rabin-Karp.md --- docs/Rabin-Karp Algorithm/Rabin-Karp.md | 129 ++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 docs/Rabin-Karp Algorithm/Rabin-Karp.md diff --git a/docs/Rabin-Karp Algorithm/Rabin-Karp.md b/docs/Rabin-Karp Algorithm/Rabin-Karp.md new file mode 100644 index 000000000..a7db9d785 --- /dev/null +++ b/docs/Rabin-Karp Algorithm/Rabin-Karp.md @@ -0,0 +1,129 @@ +--- +id: rabin-karp-algorithm +title: "Rabin-Karp Algorithm for Pattern Searching" +sidebar_label: "Rabin-Karp Algorithm" +sidebar_position: 1 +description: "Detailed explanation and implementation of the Rabin-Karp algorithm for pattern searching in strings." +tags: [Algorithm, Rabin-Karp, Pattern Matching, String Searching] +--- + +# Rabin-Karp Algorithm +## Overview +The Rabin-Karp algorithm is a string-searching algorithm that uses hashing to find patterns in text efficiently. It is especially useful for locating multiple occurrences of a pattern within a text and performs well in average cases, though it can degrade in performance if there are hash collisions. + +The algorithm's main advantage is its use of a **rolling hash function**, which allows it to re-compute hash values efficiently as it slides over the text. + +## Use Cases +- **Plagiarism Detection**: Identifies similar or identical sequences within a document. +- **DNA Sequence Matching**: Finds specific nucleotide patterns within larger DNA sequences. +- **Spam Detection**: Helps locate keywords or patterns within large datasets for filtering purposes. + +## Algorithm Details +### Key Concepts +1. **Hashing**: The pattern and text windows are hashed to enable quick comparison. +2. **Rolling Hash**: A technique to compute hash values in constant time by reusing previous hash values as the window slides across the text. +3. **Collision Handling**: To address hash collisions, the algorithm performs an additional string comparison when hashes match. + +### Algorithm Complexity +- **Average Time Complexity**: \(O(n + m)\), where \(n\) is the length of the text and \(m\) is the length of the pattern. +- **Worst-Case Complexity**: \(O(n \times m)\) in cases of frequent hash collisions. + +## Example Pseudocode +### Rabin-Karp Pattern Search + +```cpp +// Given a text T and pattern P, this function finds all occurrences of P in T. + +function rabinKarp(text, pattern, prime): + n = length(text) + m = length(pattern) + hashPattern = computeHash(pattern, prime) + hashText = computeHash(text.substring(0, m), prime) + + for i from 0 to n - m: + if hashPattern == hashText: + if text.substring(i, i + m) == pattern: + print("Pattern found at index", i) + + if i < n - m: + hashText = recomputeHash(text, i, m, hashText, prime) + +function computeHash(str, prime): + hashValue = 0 + for each character in str: + hashValue = (hashValue * 256 + ASCII(character)) % prime + return hashValue +``` + +## Code Example in C++: Rabin-Karp Algorithm +```cpp +#include +#include +#include +using namespace std; + +const int d = 256; // Number of characters in the input alphabet + +void rabinKarpSearch(string text, string pattern, int prime) { + int m = pattern.length(); + int n = text.length(); + int p = 0; // Hash value for pattern + int t = 0; // Hash value for text + int h = 1; + + // Calculate the value of h (d^(m-1)) % prime + for (int i = 0; i < m - 1; i++) + h = (h * d) % prime; + + // Calculate the hash value of pattern and first window of text + for (int i = 0; i < m; i++) { + p = (d * p + pattern[i]) % prime; + t = (d * t + text[i]) % prime; + } + + // Slide the pattern over text one character at a time + for (int i = 0; i <= n - m; i++) { + // Check the hash values of current window of text and pattern + if (p == t) { + // If the hash values match, check the actual characters + bool match = true; + for (int j = 0; j < m; j++) { + if (text[i + j] != pattern[j]) { + match = false; + break; + } + } + if (match) + cout << "Pattern found at index " << i << endl; + } + + // Calculate hash value for the next window of text + if (i < n - m) { + t = (d * (t - text[i] * h) + text[i + m]) % prime; + if (t < 0) + t = (t + prime); + } + } +} + +int main() { + string text = "GEEKS FOR GEEKS"; + string pattern = "GEEK"; + int prime = 101; // A prime number + rabinKarpSearch(text, pattern, prime); + return 0; +} +``` + +## Explanation of the Code +- Hash Initialization: Calculates initial hash values for both the pattern and the first window of text. +- Hash Comparison: If the hash values match, the algorithm checks the actual text to confirm a match. +- Hash Update: Uses a rolling hash to efficiently update the hash value as it slides through the text, maintaining constant time complexity for each shift. + +## Example Walkthrough +Consider the text "GEEKS FOR GEEKS" and the pattern "GEEK". The algorithm computes the initial hash for "GEEK" and matches it against the rolling hash of each substring in the text, sliding character-by-character to check each window. + +## Real-World Example +The Rabin-Karp algorithm is widely used in applications requiring fast, efficient pattern matching. Examples include searching for specific words or sequences in large documents or databases, identifying duplicate code snippets, and finding malicious patterns within network packets. + +By adding the Rabin-Karp algorithm, we enhance the Algo repository with a fast and robust solution for text searching, useful in both educational contexts and practical applications like data processing and network security. From 89a3acd0466a4640cd63e4974e0e55ee5d44b654 Mon Sep 17 00:00:00 2001 From: Souvik Kumar Pramanik <123581988+souvikpramanikgit@users.noreply.github.com> Date: Sat, 9 Nov 2024 16:09:56 +0530 Subject: [PATCH 06/11] Create sql-30.md --- docs/languages/SQL/sql-30.md | 71 ++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 docs/languages/SQL/sql-30.md diff --git a/docs/languages/SQL/sql-30.md b/docs/languages/SQL/sql-30.md new file mode 100644 index 000000000..553591563 --- /dev/null +++ b/docs/languages/SQL/sql-30.md @@ -0,0 +1,71 @@ +--- +id: sql-create-database +sidebar_position: 30 +title: "SQL CREATE DATABASE Statement" +sidebar_label: "SQL CREATE DATABASE" +description: "The SQL CREATE DATABASE statement is used to create a new database." +tags: [sql, dbms, database, create database] +--- + +The `CREATE DATABASE` statement in SQL is used to create a new database. It allows you to specify the name of the database and, in some SQL systems, additional configuration options such as character set, collation, and storage settings. + +### Syntax + +```sql +CREATE DATABASE database_name; +``` + +### Key Points +* Database Name: Must be unique within the SQL server. +* Permissions: Creating a database usually requires administrative or specific permissions. +* Optional Clauses: Some SQL systems support additional options like CHARACTER SET and COLLATE to define the database encoding and collation. + +### Example + +**Example 1: Basic CREATE DATABASE Statement** + +Create a database named StoreDB. + +```sql +CREATE DATABASE StoreDB; +``` + +**Example 2: CREATE DATABASE with Character Set and Collation** + +Create a database named CustomerDB with specific character set and collation (supported in certain SQL systems like MySQL). + +```sql +CREATE DATABASE CustomerDB +CHARACTER SET utf8 +COLLATE utf8_general_ci; +``` + +**Example 3: Checking for Database Existence** + +To avoid errors when creating a database that might already exist, use a conditional check (supported in certain databases). + +```sql +CREATE DATABASE IF NOT EXISTS InventoryDB; +``` + +### Viewing Created Databases + +After creating a database, you can view a list of databases using: + +```sql +SHOW DATABASES; -- MySQL +``` + +Or, in SQL Server: + +```sql +SELECT name +FROM sys.databases; +``` + +**Notes :** +* Database Creation: The CREATE DATABASE statement is supported in most SQL-based databases like MySQL, PostgreSQL, and SQL Server, but syntax may vary slightly. +* Modifying Databases: Once created, you can alter database settings with ALTER DATABASE. +* Dropping Databases: Use DROP DATABASE database_name; to remove a database, but be cautious as this action is irreversible. + +The CREATE DATABASE statement is essential for setting up new databases within an SQL server, laying the foundation for organizing and managing data. From 997e85cf8e495b90896200ef44882bd6b7da2a33 Mon Sep 17 00:00:00 2001 From: Jivan <137729176+Jivanjamadar@users.noreply.github.com> Date: Sat, 9 Nov 2024 16:16:14 +0530 Subject: [PATCH 07/11] Update PrioritySearch.md --- docs/algorithms/Searching Algorithms/PrioritySearch.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/algorithms/Searching Algorithms/PrioritySearch.md b/docs/algorithms/Searching Algorithms/PrioritySearch.md index fb60fd227..3001d05f8 100644 --- a/docs/algorithms/Searching Algorithms/PrioritySearch.md +++ b/docs/algorithms/Searching Algorithms/PrioritySearch.md @@ -1,6 +1,6 @@ --- -id: Priority-search-algorithm +id: priority-search-algorithm sidebar_position: 5 title: Priority Search algorithm sidebar_label: Priority Search algorithm From 2e6d04154d1247ddd6f04c8bdc7f21242bf56315 Mon Sep 17 00:00:00 2001 From: Souvik Kumar Pramanik <123581988+souvikpramanikgit@users.noreply.github.com> Date: Sat, 9 Nov 2024 16:16:27 +0530 Subject: [PATCH 08/11] Create sql-31.md --- docs/languages/SQL/sql-31.md | 61 ++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 docs/languages/SQL/sql-31.md diff --git a/docs/languages/SQL/sql-31.md b/docs/languages/SQL/sql-31.md new file mode 100644 index 000000000..d39b4c293 --- /dev/null +++ b/docs/languages/SQL/sql-31.md @@ -0,0 +1,61 @@ +--- +id: sql-drop-database +sidebar_position: 31 +title: "SQL DROP DATABASE Statement" +sidebar_label: "SQL DROP DATABASE" +description: "The SQL DROP DATABASE statement is used to delete an existing database." +tags: [sql, dbms, database, drop database] +--- + +The `DROP DATABASE` statement in SQL is used to delete an existing database, along with all its tables, data, and associated objects. This action is irreversible, so it should be used with caution. + +### Syntax + +```sql +DROP DATABASE database_name; +``` + +### Key Points +* Permanent Deletion: The database and all its data are permanently deleted. +* Permissions Required: Dropping a database generally requires administrative privileges. +* Safety Precaution: Be certain before executing this command, as it cannot be undone. + +### Example + +**Example 1: Basic DROP DATABASE Statement** + +Delete a database named StoreDB. + +```sql +DROP DATABASE StoreDB; +``` + +**Example 2: Conditionally Dropping a Database** + +To avoid errors when attempting to drop a database that may not exist, you can use a conditional check (supported in certain databases). + +```sql +DROP DATABASE IF EXISTS CustomerDB; +``` + +### Viewing Available Databases + +Before deleting a database, you may want to view a list of existing databases to ensure accuracy: + +```sql +SHOW DATABASES; -- MySQL +``` + +Or, in SQL Server: + +```sql +SELECT name +FROM sys.databases; +``` + +**Notes :** +* Data Loss Warning: Dropping a database will delete all data and schema definitions within it. This action is irreversible. +* Database Backup: It is recommended to create a backup of any critical data before using DROP DATABASE. +* Compatibility: The DROP DATABASE statement is supported across most SQL systems, though syntax may vary slightly. + +The DROP DATABASE statement is a powerful command for removing databases when they are no longer needed, but it should be used with caution to prevent accidental data loss. From 3d4d0af1b31f06f899b63743517d32520b4cd84b Mon Sep 17 00:00:00 2001 From: Souvik Kumar Pramanik <123581988+souvikpramanikgit@users.noreply.github.com> Date: Sat, 9 Nov 2024 16:22:30 +0530 Subject: [PATCH 09/11] Create sql-32.md --- docs/languages/SQL/sql-32.md | 76 ++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 docs/languages/SQL/sql-32.md diff --git a/docs/languages/SQL/sql-32.md b/docs/languages/SQL/sql-32.md new file mode 100644 index 000000000..bc8d77e26 --- /dev/null +++ b/docs/languages/SQL/sql-32.md @@ -0,0 +1,76 @@ +--- +id: sql-create-table +sidebar_position: 32 +title: "SQL CREATE TABLE Statement" +sidebar_label: "SQL CREATE TABLE" +description: "The SQL CREATE TABLE statement is used to create a new table in the database." +tags: [sql, dbms, database, create table, schema] +--- + +The `CREATE TABLE` statement in SQL is used to create a new table in the database. It allows you to define the table's columns, data types, and any constraints. + +### Syntax + +```sql +CREATE TABLE table_name ( + column1 datatype constraint, + column2 datatype constraint, + ... +); +``` + +### Key Points + +* Table and Column Names: Table names and column names should be unique within the database. +* Data Types: Define the type of data each column will hold (e.g., INT, VARCHAR, DATE). +* Constraints: Apply constraints like PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, and CHECK to control data integrity. + +### Example + +**Example 1: Basic CREATE TABLE Statement** + +Create a table named Customers with basic columns and data types. + +```sql +CREATE TABLE Customers ( + CustomerID INT PRIMARY KEY, + CustomerName VARCHAR(100) NOT NULL, + ContactName VARCHAR(100), + Country VARCHAR(50) +); +``` + +**Example 2: CREATE TABLE with Constraints** + +Create a table named Orders with primary key, foreign key, and other constraints. + +```sql +CREATE TABLE Orders ( + OrderID INT PRIMARY KEY, + OrderDate DATE NOT NULL, + CustomerID INT, + Amount DECIMAL(10, 2), + CONSTRAINT FK_CustomerOrder FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) +); +``` + +**Example 3: CREATE TABLE with Default Values** + +Create a table with a column that has a default value. + +```sql +CREATE TABLE Products ( + ProductID INT PRIMARY KEY, + ProductName VARCHAR(100) NOT NULL, + Price DECIMAL(10, 2) DEFAULT 0.00 +); +``` + +**Notes :** + +* Primary Key: Uniquely identifies each record in the table. +* Foreign Key: Establishes a relationship with another table, ensuring data consistency. +* Default Values: Assign default values to columns when no data is provided. +* Auto-Increment: Certain SQL databases support the AUTO_INCREMENT attribute (e.g., SERIAL in PostgreSQL) for automatically generating unique values for primary keys. + +The CREATE TABLE statement is fundamental for setting up the schema of a database and defining the structure and constraints for data storage. From 294e8b0ea88785a2cfc1ab932af93e183bc8162b Mon Sep 17 00:00:00 2001 From: Souvik Kumar Pramanik <123581988+souvikpramanikgit@users.noreply.github.com> Date: Sat, 9 Nov 2024 16:28:49 +0530 Subject: [PATCH 10/11] Create sql-33.md --- docs/languages/SQL/sql-33.md | 90 ++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 docs/languages/SQL/sql-33.md diff --git a/docs/languages/SQL/sql-33.md b/docs/languages/SQL/sql-33.md new file mode 100644 index 000000000..a91286a0d --- /dev/null +++ b/docs/languages/SQL/sql-33.md @@ -0,0 +1,90 @@ +--- +id: sql-views +sidebar_position: 33 +title: "SQL Views" +sidebar_label: "SQL Views" +description: "SQL Views are virtual tables that represent a saved query in the database." +tags: [sql, dbms, database, views, virtual tables] +--- + +A **View** in SQL is a virtual table based on a result set of a `SELECT` query. Views can simplify complex queries, enhance security by limiting data access, and provide a more user-friendly way to access data. + +### Advantages of Views + +- **Simplicity**: Abstract complex queries, allowing easier access to data. +- **Security**: Restrict access to specific data by allowing users to query a view instead of underlying tables. +- **Data Consistency**: Ensure data consistency by allowing standardized queries to run on views instead of individual tables. + +### Syntax + +```sql +CREATE VIEW view_name AS +SELECT column1, column2, ... +FROM table_name +WHERE condition; +``` + +### Example + +**Example 1: Creating a Simple View** + +Create a view named CustomerView that displays only selected columns from the Customers table. + +```sql +CREATE VIEW CustomerView AS +SELECT CustomerID, CustomerName, Country +FROM Customers; +``` + +To query data from this view: + +```sql +SELECT * FROM CustomerView; +``` + +**Example 2: View with Join** + +Create a view that combines data from multiple tables to show order details. + +```sql +CREATE VIEW OrderDetailsView AS +SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate, Orders.Amount +FROM Orders +JOIN Customers ON Orders.CustomerID = Customers.CustomerID; +``` + +**Example 3: Updating Data through a View** + +In some SQL databases, views can be updatable. This depends on database constraints and view complexity. Here’s an example of updating a view: + +```sql +UPDATE CustomerView +SET Country = 'USA' +WHERE CustomerID = 1; +``` + +Note: Not all views are updatable. Complex views (e.g., those with joins, group functions) may not support updates. + +### Managing Views + +* **Modify a View:** Use CREATE OR REPLACE VIEW to modify an existing view without dropping it. + +```sql +CREATE OR REPLACE VIEW CustomerView AS +SELECT CustomerID, CustomerName +FROM Customers +WHERE Country = 'USA'; +``` + +* **Delete a View:** Use DROP VIEW to remove a view from the database. + +```sql +DROP VIEW view_name; +``` + +**Notes :** +* Virtual Table: A view doesn’t store data; it only stores the SQL query that defines it. +* Read-Only Views: Some views are read-only depending on complexity and database constraints. +* Permissions: Views can provide restricted data access to specific users without exposing full tables. + +SQL Views are powerful tools that enhance database usability, security, and data management by abstracting and simplifying access to underlying tables. From 44bce6fecf9e2b76c1b758d69ab31a1a861f6a3d Mon Sep 17 00:00:00 2001 From: riyaa060 <153705031+riyaa060@users.noreply.github.com> Date: Sat, 9 Nov 2024 20:06:29 +0530 Subject: [PATCH 11/11] Update java-10.md --- docs/languages/java/java-10.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/languages/java/java-10.md b/docs/languages/java/java-10.md index 61a8905d5..8defc1f2c 100644 --- a/docs/languages/java/java-10.md +++ b/docs/languages/java/java-10.md @@ -1,5 +1,5 @@ --- -id:memory-management +id: memory-management sidebar_position: 10 title: "Memory management in Java" sidebar_label: "Memory management"