parent
10a1866ca5
commit
7023168b77
65 changed files with 188 additions and 2845 deletions
@ -1,38 +1,8 @@ |
|||||||
# ABS |
# ABS |
||||||
|
|
||||||
The `ABS` function in SQL is used to return the absolute value of a number, i.e., the numeric value without its sign. The function takes a single argument which must be a number (integer, float, etc.) and returns the absolute, non-negative equivalent. |
The `ABS()` function in SQL returns the absolute value of a given numeric expression, meaning it converts any negative number to its positive equivalent while leaving positive numbers unchanged. This function is useful when you need to ensure that the result of a calculation or a value stored in a database column is non-negative, such as when calculating distances, differences, or other metrics where only positive values make sense. For example, `SELECT ABS(-5)` would return `5`. |
||||||
|
|
||||||
The general syntax for the ABS function is as follows: |
Learn more from the following resources: |
||||||
|
|
||||||
```sql |
- [@article@How to compute an absolute value in SQL](https://www.airops.com/sql-guide/how-to-compute-an-absolute-value-in-sql) |
||||||
ABS(expression) |
- [@article@ABS](https://www.w3schools.com/sql/func_sqlserver_abs.asp) |
||||||
``` |
|
||||||
|
|
||||||
In the syntax above, the `expression` is required and can either be a literal number, a column name, the result of another function, or any valid SQL expression that resolves to a numeric value. |
|
||||||
|
|
||||||
## Examples |
|
||||||
|
|
||||||
Consider a database table `Orders`: |
|
||||||
|
|
||||||
| OrderID | Product | Quantity | |
|
||||||
|---------|---------|----------| |
|
||||||
| 1 | Apple | -5 | |
|
||||||
| 2 | Banana | 10 | |
|
||||||
| 3 | Cherry | -15 | |
|
||||||
|
|
||||||
If you want to get the absolute value of the 'Quantity' column, you could use the `ABS`function like this: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT OrderID, Product, ABS(Quantity) as 'Absolute Quantity' |
|
||||||
FROM Orders; |
|
||||||
``` |
|
||||||
|
|
||||||
The output will be: |
|
||||||
|
|
||||||
| OrderID | Product | Absolute Quantity | |
|
||||||
|---------|---------|-------------------| |
|
||||||
| 1 | Apple | 5 | |
|
||||||
| 2 | Banana | 10 | |
|
||||||
| 3 | Cherry | 15 | |
|
||||||
|
|
||||||
As you can see, the negative values in the 'Quantity' column have been converted to positive values by the `ABS` function. |
|
@ -1,69 +1,8 @@ |
|||||||
# Advanced SQL Functions |
# Advanced SQL Functions |
||||||
|
|
||||||
Advanced SQL functions provide complex data manipulation and query capabilities enabling the user to perform tasks that go beyond the capabilities of basic SQL commands. |
Advanced SQL functions enable more sophisticated data manipulation and analysis within databases, offering powerful tools for complex queries. Key areas include: |
||||||
|
|
||||||
## Window Function |
- **String Functions**: Manipulate text data using functions like `CONCAT`, `SUBSTRING`, and `REPLACE` to combine, extract, or modify strings. |
||||||
|
- **Date & Time**: Manage temporal data with functions like `DATEADD`, `DATEDIFF`, and `FORMAT`, allowing for calculations and formatting of dates and times. |
||||||
Windowing Functions provide the ability to perform calculations across sets of rows related to the current query row. |
- **Numeric Functions**: Perform advanced calculations using functions such as `ROUND`, `FLOOR`, and `CEIL`, providing precision in numerical data processing. |
||||||
|
- **Conditional**: Implement logic within queries using functions like `CASE`, `COALESCE`, and `NULLIF` to control data flow and handle conditional scenarios. |
||||||
```sql |
|
||||||
SELECT productName, productLine, buyPrice, |
|
||||||
AVG(buyPrice) OVER(PARTITION BY productLine) as avg_price |
|
||||||
FROM products |
|
||||||
ORDER BY productLine, buyPrice; |
|
||||||
``` |
|
||||||
|
|
||||||
## Aggregate Function |
|
||||||
|
|
||||||
Aggregate functions return a single result row based on groups of rows, rather than on single rows. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT COUNT(*) FROM products; |
|
||||||
``` |
|
||||||
|
|
||||||
## Analytic Functions |
|
||||||
|
|
||||||
Analytic functions compute an aggregate value based on a group of rows. They differ from aggregate functions in that they return multiple rows for each group. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT department_id, last_name, hire_date, |
|
||||||
COUNT(*) OVER (PARTITION BY department_id) as dept_count, |
|
||||||
RANK() OVER (PARTITION BY department_id ORDER BY hire_date) as ranking |
|
||||||
FROM employees; |
|
||||||
``` |
|
||||||
|
|
||||||
## Scalar Function |
|
||||||
|
|
||||||
A scalar function returns a single value each time it is invoked. It is based on the input value. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT UPPER(productName) FROM products; |
|
||||||
``` |
|
||||||
|
|
||||||
## Stored Procedures |
|
||||||
|
|
||||||
Stored Procedures are a prepared SQL code that you can save so the code can be reused over and over again. |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE PROCEDURE SelectAllProducts @Product varchar(50) |
|
||||||
AS |
|
||||||
SELECT * FROM products WHERE Product = @Product |
|
||||||
GO; |
|
||||||
``` |
|
||||||
|
|
||||||
## String Functions |
|
||||||
|
|
||||||
Functions that manipulate the string data types. For example, `LEFT()`, `LENGTH()`, `LOWER()`, etc. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT LEFT('This is a test', 4); |
|
||||||
``` |
|
||||||
|
|
||||||
## Date Functions |
|
||||||
|
|
||||||
Functions that manipulate the date data types. For example, `GETDATE()`, `DATEADD()`, `DATEDIFF()`, etc. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT GETDATE() AS CurrentDateTime; |
|
||||||
``` |
|
||||||
Remember, not all types or functions are supported by every SQL distribution but most of them have some sort of equivalent. |
|
@ -1,74 +1,3 @@ |
|||||||
# Advanced SQL Concepts |
# Advanced SQL Concepts |
||||||
|
|
||||||
Advanced SQL commands offer powerful functionality that allow you to conduct complex queries and operations on your database. These include operations like Stored Procedures, Triggers, Views, and more. |
Advanced SQL concepts encompass a wide range of sophisticated techniques and features that go beyond basic querying and data manipulation. These include complex joins, subqueries, window functions, stored procedures, triggers, and advanced indexing strategies. By mastering these concepts, database professionals can optimize query performance, implement complex business logic, ensure data integrity, and perform advanced data analysis, enabling them to tackle more challenging database management and data processing tasks in large-scale, enterprise-level applications. |
||||||
|
|
||||||
## Stored Procedures |
|
||||||
|
|
||||||
A stored procedure is a prepared SQL code that you save, so the code can be reused over and over again. They are particularly useful when repetitive tasks need to be performed, with less client-server communication. |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE PROCEDURE procedure_name |
|
||||||
AS |
|
||||||
sql_statement |
|
||||||
GO; |
|
||||||
``` |
|
||||||
|
|
||||||
## Triggers |
|
||||||
|
|
||||||
A Trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE, UPDATE) occurs. Triggers are useful for maintaining integrity in the database. Triggers can also be used to log historical data. |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TRIGGER trigger_name |
|
||||||
ON table_name |
|
||||||
FOR INSERT, UPDATE, DELETE |
|
||||||
AS |
|
||||||
-- SQL Statements |
|
||||||
``` |
|
||||||
|
|
||||||
## Views |
|
||||||
|
|
||||||
A view is a virtual table based on the result-set of an SQL statement. It allows you to view data that is derived from other tables. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE VIEW view_name AS |
|
||||||
SELECT column1, column2, ... |
|
||||||
FROM table_name |
|
||||||
WHERE condition; |
|
||||||
``` |
|
||||||
|
|
||||||
## JOINs |
|
||||||
|
|
||||||
JOINs are used to combine rows from two or more tables, based on a related column between them. Types include INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT Orders.OrderID, Customers.CustomerName |
|
||||||
FROM Orders |
|
||||||
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID; |
|
||||||
``` |
|
||||||
|
|
||||||
## Subqueries |
|
||||||
|
|
||||||
A subquery is a query that is embedded in the WHERE or HAVING clause of another SQL query. Subqueries can return individual values or a list of records. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT column_name [, column_name ] |
|
||||||
FROM table1 [, table2 ] |
|
||||||
WHERE column_name OPERATOR |
|
||||||
(SELECT column_name [, column_name ] |
|
||||||
FROM table1 [, table2 ] |
|
||||||
[WHERE]) |
|
||||||
``` |
|
||||||
|
|
||||||
## Set Operators |
|
||||||
|
|
||||||
Set operators allow the results of multiple queries to be combined into a single result set. The UNION, UNION ALL, INTERSECT, and MINUS operators are some of the set operators. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT column_name(s) FROM table1 |
|
||||||
UNION |
|
||||||
SELECT column_name(s) FROM table2; |
|
||||||
``` |
|
||||||
|
|
||||||
Note: Make sure to adjust the code examples given above according to your specific use case. In some cases, you may also need to adjust them according to the syntax of the specific SQL variant that you are using. |
|
||||||
|
|
||||||
Also, it's important to note that these are some of the many advanced SQL topics. There are others like Window functions, CTEs, Pivoting and more. Another important area is working with different database systems as each system (like MySQL, PostgreSQL, etc.) has its own specific set of features and syntax. |
|
@ -1,80 +1,10 @@ |
|||||||
# Aggregate Queries |
# Aggregate Queries |
||||||
|
|
||||||
SQL aggregate functions are inbuilt functions that are used to perform some calculation on the data and return a single value. This is why they form the basis for "aggregate queries". These functions operate on a set of rows and return a single summarized result. |
Aggregate queries in SQL are used to perform calculations on multiple rows of data, returning a single summary value or grouped results. These queries typically involve the use of aggregate functions, such as: |
||||||
|
|
||||||
## Common Aggregate Functions |
• COUNT(): Returns the number of rows that match a specific condition. |
||||||
|
• SUM(): Calculates the total sum of a numeric column. |
||||||
**1. COUNT()** |
• AVG(): Computes the average value of a numeric column. |
||||||
|
• MIN() and MAX(): Find the smallest and largest values in a column, respectively. |
||||||
Counts the number of rows. |
• GROUP BY: Used to group rows that share a common value in specified columns, allowing aggregate functions to be applied to each group. |
||||||
|
• HAVING: Filters the results of a GROUP BY clause based on a specified condition, similar to WHERE but for groups. |
||||||
```sql |
|
||||||
SELECT COUNT(column_name) |
|
||||||
FROM table_name |
|
||||||
WHERE condition; |
|
||||||
``` |
|
||||||
|
|
||||||
**2. SUM()** |
|
||||||
|
|
||||||
Returns the sum of a numeric column. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT SUM(column_name) |
|
||||||
FROM table_name |
|
||||||
WHERE condition; |
|
||||||
``` |
|
||||||
|
|
||||||
**3. AVG()** |
|
||||||
|
|
||||||
Returns the average value of a numeric column. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT AVG(column_name) |
|
||||||
FROM table_name |
|
||||||
WHERE condition; |
|
||||||
``` |
|
||||||
|
|
||||||
**4. MIN()** |
|
||||||
|
|
||||||
Returns the smallest value of the selected column. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT MIN(column_name) |
|
||||||
FROM table_name |
|
||||||
WHERE condition; |
|
||||||
``` |
|
||||||
|
|
||||||
**5. MAX()** |
|
||||||
|
|
||||||
Returns the largest value of the selected column. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT MAX(column_name) |
|
||||||
FROM table_name |
|
||||||
WHERE condition; |
|
||||||
``` |
|
||||||
|
|
||||||
These functions ignore NULL values. |
|
||||||
|
|
||||||
## GROUP BY and HAVING Clauses |
|
||||||
|
|
||||||
To separate the results into groups of accumulated data, you can use the GROUP BY clause. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT column1, aggregate_function(column2) |
|
||||||
FROM table |
|
||||||
GROUP BY column1; |
|
||||||
``` |
|
||||||
|
|
||||||
"A group" is represented by ROW(s) that have the same value in the specific column(s). The GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group by some columns. |
|
||||||
|
|
||||||
The HAVING clause is used with the GROUP BY clause, it applies to summarized group records, unlike the 'where' clause. It was added to SQL because the WHERE keyword could not be used with aggregate functions. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT column1, aggregate_function(column2) |
|
||||||
FROM table |
|
||||||
GROUP BY column1 |
|
||||||
HAVING conditions; |
|
||||||
``` |
|
||||||
|
|
||||||
Aggregate queries are simply a way of summarizing information in your database. Although they are a powerful tool, they can become complex very quickly, especially if you start nesting them together or combining multiple aggregate functions in a single query. |
|
@ -1,75 +1,8 @@ |
|||||||
# Alter Table |
# Alter Table |
||||||
|
|
||||||
The `ALTER TABLE` command in SQL is used to add, delete/drop, or modify columns in an existing table. It's also useful for adding and dropping constraints such as primary key, foreign key, etc. |
The `ALTER TABLE` statement in SQL is used to modify the structure of an existing table. This includes adding, dropping, or modifying columns, changing the data type of a column, setting default values, and adding or dropping primary or foreign keys. |
||||||
|
|
||||||
## Add Column |
Learn more from the following resources: |
||||||
|
|
||||||
A single column can be added using the following syntax: |
- [@article@ALTER TABLE Statement](https://www.techonthenet.com/sql/tables/alter_table.php) |
||||||
|
- [@article@ALTER TABLE - PostgreSQL](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-alter-table/) |
||||||
```sql |
|
||||||
ALTER TABLE tableName |
|
||||||
ADD columnName datatype; |
|
||||||
``` |
|
||||||
|
|
||||||
To add more than one column: |
|
||||||
|
|
||||||
```sql |
|
||||||
ALTER TABLE tableName |
|
||||||
ADD (columnName1 datatype, |
|
||||||
columnName2 datatype, |
|
||||||
... |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
## Drop Column |
|
||||||
|
|
||||||
To drop a single column: |
|
||||||
|
|
||||||
```sql |
|
||||||
ALTER TABLE tableName |
|
||||||
DROP COLUMN columnName; |
|
||||||
``` |
|
||||||
|
|
||||||
To drop multiple columns: |
|
||||||
|
|
||||||
```sql |
|
||||||
ALTER TABLE tableName |
|
||||||
DROP (columnName1, |
|
||||||
columnName2, |
|
||||||
... |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
## Modify Column |
|
||||||
|
|
||||||
To modify the datatype of a column: |
|
||||||
|
|
||||||
```sql |
|
||||||
ALTER TABLE tableName |
|
||||||
MODIFY COLUMN columnName newDataType; |
|
||||||
``` |
|
||||||
|
|
||||||
## Add/Drop Constraints |
|
||||||
|
|
||||||
To add constraints: |
|
||||||
|
|
||||||
```sql |
|
||||||
ALTER TABLE tableName |
|
||||||
ADD CONSTRAINT constraintName |
|
||||||
PRIMARY KEY (column1, column2, ... column_n); |
|
||||||
``` |
|
||||||
|
|
||||||
To drop constraints: |
|
||||||
|
|
||||||
```sql |
|
||||||
ALTER TABLE tableName |
|
||||||
DROP CONSTRAINT constraintName; |
|
||||||
``` |
|
||||||
|
|
||||||
To drop PRIMARY KEY: |
|
||||||
|
|
||||||
```sql |
|
||||||
ALTER TABLE table_name |
|
||||||
DROP PRIMARY KEY; |
|
||||||
``` |
|
||||||
In conclusion, `ALTER TABLE` in SQL lets you alter the structure of an existing table. This is a powerful command that lets you dynamically add, modify, and delete columns as well as the constraints placed on them. It ensures you are more flexible in dealing with changing data storage requirements. |
|
@ -1,40 +1,8 @@ |
|||||||
# AVG |
# AVG |
||||||
|
|
||||||
The `AVG()` function in SQL is an aggregate function that returns the average value of a numeric column. It calculates the sum of values in a column and then divides it by the count of those values. |
The `AVG()` function in SQL is an aggregate function that calculates the average value of a numeric column. It returns the sum of all the values in the column, divided by the count of those values. |
||||||
|
|
||||||
Syntax: |
Learn more from the following resources: |
||||||
```sql |
|
||||||
SELECT AVG(column_name) |
|
||||||
FROM table_name; |
|
||||||
``` |
|
||||||
This statement will return the average value of the specified column. |
|
||||||
|
|
||||||
## Example Usage of AVG: |
- [@article@AVG](https://www.sqlshack.com/sql-avg-function-introduction-and-examples/) |
||||||
|
- [@article@SQL AVG() Function](https://www.w3schools.com/sql/sql_avg.asp) |
||||||
Consider the following table `Orders`: |
|
||||||
|
|
||||||
| OrderID | CustomerID | Quantity | |
|
||||||
|---------|------------|----------| |
|
||||||
| 1 | A | 30 | |
|
||||||
| 2 | A | 40 | |
|
||||||
| 3 | B | 20 | |
|
||||||
| 4 | B | 60 | |
|
||||||
| 5 | C | 50 | |
|
||||||
| 6 | C | 10 | |
|
||||||
|
|
||||||
Let's calculate the average quantity in the `Orders` table: |
|
||||||
```sql |
|
||||||
SELECT AVG(Quantity) AS AvgQuantity |
|
||||||
FROM Orders; |
|
||||||
``` |
|
||||||
The result is 35. This value is the average of all `Quantity` values in the table. |
|
||||||
|
|
||||||
It's also possible to group the average function by one or more columns. For example, to find the average quantity of order per customer, we can write: |
|
||||||
```sql |
|
||||||
SELECT CustomerID, AVG(Quantity) as AvgQuantity |
|
||||||
FROM Orders |
|
||||||
GROUP BY CustomerID; |
|
||||||
``` |
|
||||||
It will calculate the average quantity for each customer and display the result along with the associated customer's ID. |
|
||||||
|
|
||||||
> Note: The `AVG()` function works only with numeric data types (`INT`, `FLOAT`, `DECIMAL`, etc.). It will return an error if used with non-numeric data types. |
|
@ -1,43 +1,8 @@ |
|||||||
# BEGIN |
# BEGIN |
||||||
|
|
||||||
In SQL, a transaction refers to a unit of work performed against a database. Transactions in SQL are used to ensure the integrity of the database. The keywords used in SQL to control the transactions are `BEGIN`, `COMMIT`, `ROLLBACK`. |
`BEGIN` is used in SQL to start a transaction, which is a sequence of one or more SQL operations that are executed as a single unit. A transaction ensures that all operations within it are completed successfully before any changes are committed to the database. If any part of the transaction fails, the `ROLLBACK` command can be used to undo all changes made during the transaction, maintaining the integrity of the database. Once all operations are successfully completed, the `COMMIT` command is used to save the changes. Transactions are crucial for maintaining data consistency and handling errors effectively. |
||||||
|
|
||||||
## BEGIN |
Learn more from the following resources: |
||||||
|
|
||||||
In the context of SQL transactions, `BEGIN` is a keyword used to start a transaction. It marks the point at which the data referenced by a connection is logically consistent. After the `BEGIN` statement, the transaction is considered to be "open" and remains so until it is committed or rolled back. |
- [@article@BEGIN...END Statement](https://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc00801.1510/html/iqrefso/BABFBJAB.htm) |
||||||
|
- [@article@SQL 'BEGIN' & 'END' Statements](https://reintech.io/blog/understanding-sql-begin-end-statements-guide) |
||||||
Once you've initiated a transaction with `BEGIN`, all the subsequent SQL statements will be a part of this transaction until an explicit `COMMIT` or `ROLLBACK` is given. |
|
||||||
|
|
||||||
## Syntax |
|
||||||
|
|
||||||
The syntax to start a transaction is: |
|
||||||
```sql |
|
||||||
BEGIN TRANSACTION; |
|
||||||
``` |
|
||||||
or simply, |
|
||||||
```sql |
|
||||||
BEGIN; |
|
||||||
``` |
|
||||||
## Example |
|
||||||
|
|
||||||
Below is a simple example of using `BEGIN` in SQL: |
|
||||||
|
|
||||||
```sql |
|
||||||
BEGIN; |
|
||||||
|
|
||||||
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country) |
|
||||||
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway'); |
|
||||||
|
|
||||||
COMMIT; |
|
||||||
``` |
|
||||||
|
|
||||||
In this example: |
|
||||||
- `BEGIN;` marks the start of the transaction. |
|
||||||
- The `INSERT` statement adds a new row of data to the `Customers` table. |
|
||||||
- `COMMIT;` ends the transaction and permanently saves the changes made during this transaction. |
|
||||||
|
|
||||||
Note: If something goes wrong with one of the SQL statements within the transaction (after the `BEGIN;` statement), you can choose to `ROLLBACK` the transaction, which means canceling all the changes made in this transaction up to the point of error. |
|
||||||
|
|
||||||
## Conclusion |
|
||||||
|
|
||||||
In summary, `BEGIN` in SQL is used to start a transaction, which enables modifications done in a database to be viewed as a logically coherent occurrence. |
|
@ -1,47 +1,8 @@ |
|||||||
# CASE |
# CASE |
||||||
|
|
||||||
`CASE` is a conditional statement in SQL that performs different actions based on different conditions. It allows you to perform IF-THEN-ELSE logic within SQL queries. It can be used in any statement or clause that allows a valid expression. |
The CASE statement in SQL is used to create conditional logic within a query, allowing you to perform different actions based on specific conditions. It operates like an if-else statement, returning different values depending on the outcome of each condition. The syntax typically involves specifying one or more WHEN conditions, followed by the result for each condition, and an optional ELSE clause for a default outcome if none of the conditions are met. |
||||||
|
|
||||||
There are two forms of the `CASE` statement: |
Learn more from the following resources: |
||||||
|
|
||||||
1. **Simple CASE expression** - It compares an expression to a set of simple expressions to return a result. |
- [@article@SQL CASE Expression](https://www.w3schools.com/sql/sql_case.asp) |
||||||
|
- [@article@SQL CASE - Intermediate SQL](https://mode.com/sql-tutorial/sql-case) |
||||||
```sql |
|
||||||
SELECT column1, column2, |
|
||||||
(CASE |
|
||||||
WHEN condition1 THEN result1 |
|
||||||
WHEN condition2 THEN result2 |
|
||||||
... |
|
||||||
ELSE result |
|
||||||
END) |
|
||||||
FROM table_name; |
|
||||||
``` |
|
||||||
|
|
||||||
2. **Searched CASE expression** - It evaluates a set of Boolean expressions to return a result. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT column1, column2, |
|
||||||
(CASE |
|
||||||
WHEN condition1 THEN result1 |
|
||||||
WHEN condition2 THEN result2 |
|
||||||
... |
|
||||||
ELSE result |
|
||||||
END) |
|
||||||
FROM table_name; |
|
||||||
``` |
|
||||||
|
|
||||||
In both forms, `CASE` returns a result_1, result_2, ..., if condition_1, condition_2, ... is true. If no conditions are true, it returns the value in the `ELSE` clause. If the `ELSE` clause is omitted and no conditions are true, it returns NULL. |
|
||||||
|
|
||||||
Here's a concrete example: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT OrderID, Quantity, |
|
||||||
(CASE |
|
||||||
WHEN Quantity > 30 THEN 'Over 30' |
|
||||||
WHEN Quantity = 30 THEN 'Equals 30' |
|
||||||
ELSE 'Under 30' |
|
||||||
END) AS QuantityText |
|
||||||
FROM OrderDetails; |
|
||||||
``` |
|
||||||
|
|
||||||
From the "OrderDetails" table, the statement lists 'OrderID', 'Quantity', and a column named 'QuantityText' that displays 'Over 30' if 'Quantity > 30' or 'Equals 30' if 'Quantity = 30' or 'Under 30' if both conditions are false. |
|
@ -1,24 +1,7 @@ |
|||||||
# CEILING |
# CEILING |
||||||
|
|
||||||
`CEILING` is an advanced SQL function that is used to round up values. The function takes a single argument, which is a numeric or decimal number, and returns the smallest integer that is greater than or equal to the supplied number. |
The `CEILING()` function in SQL returns the smallest integer greater than or equal to a given numeric value. It's useful when you need to round up a number to the nearest whole number, regardless of whether the number is already an integer or a decimal. For example, `CEILING(4.2)` would return `5`, and `CEILING(-4.7)` would return `-4`. This function is commonly used in scenarios where rounding up is necessary, such as calculating the number of pages needed to display a certain number of items when each page has a fixed capacity. |
||||||
|
|
||||||
The syntax for using the `CEILING` function is: |
Learn more from the following resources: |
||||||
|
|
||||||
```sql |
- [@article@CEILING Function in SQL](https://www.javatpoint.com/ceiling-function-in-sql) |
||||||
CEILING (numeric_expression) |
|
||||||
``` |
|
||||||
|
|
||||||
The `numeric_expression` is an expression of the exact numeric or approximate numeric data type categories, or types that can be implicitly converted to one of these categories. |
|
||||||
|
|
||||||
For example, you have a table called 'Products' with a 'Price' column. Here's how you can use the `CEILING` function to round up all the prices to the nearest whole number: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT ProductName, Price, CEILING (Price) AS RoundedUpPrice |
|
||||||
FROM Products; |
|
||||||
``` |
|
||||||
|
|
||||||
In this example, if the original price was $10.25, the `RoundedUpPrice` will be $11. This is because the `CEILING` function rounds up the 'Price' value to the nearest whole number. |
|
||||||
|
|
||||||
It's essential to remember that `CEILING` always rounds up. So even if the Price is $10.01, the RoundedUpPrice according to `CEILING` would still be $11. If you want to round to the nearest whole number, you might want to use the `ROUND` function instead. |
|
||||||
|
|
||||||
Another important note is that the return type of `CEILING` will be of the same type as the provided numeric expression. For instance, if you supply a numeric expression of type decimal, the return type will also be of type decimal. |
|
@ -1,64 +1,7 @@ |
|||||||
# CHECK |
# CHECK |
||||||
|
|
||||||
In SQL, `CHECK` is a constraint that limits the value range that can be placed in a column. It enforces domain integrity by limiting the values in a column to meet a certain condition. |
A `CHECK` constraint in SQL is used to enforce data integrity by specifying a condition that must be true for each row in a table. It allows you to define custom rules or restrictions on the values that can be inserted or updated in one or more columns. `CHECK` constraints help maintain data quality by preventing invalid or inconsistent data from being added to the database, ensuring that only data meeting specified criteria is accepted. |
||||||
|
|
||||||
`CHECK` constraint can be used in a column definition when you create or modify a table. |
Learn more from the following resources: |
||||||
|
|
||||||
## Syntax |
- [@article@CHECK - PostgreSQL](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-check/) |
||||||
|
|
||||||
To use the `CHECK` constraint, you can follow this syntax: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE table_name ( |
|
||||||
column1 datatype CONSTRAINT constraint_name CHECK (condition), |
|
||||||
column2 datatype, |
|
||||||
... |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
If you need to apply the `CHECK` constraint on multiple columns, use the following syntax: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE table_name ( |
|
||||||
column1 datatype, |
|
||||||
column2 datatype, |
|
||||||
..., |
|
||||||
CONSTRAINT constraint_name CHECK (condition) |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
## Examples |
|
||||||
|
|
||||||
Here is an example of applying a `CHECK` constraint on a single column: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Employees ( |
|
||||||
ID int NOT NULL, |
|
||||||
Age int, |
|
||||||
Salary int CHECK (Salary>0), |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
Above SQL statement ensures that the salary of all employees in the Employees table must be more than 0. |
|
||||||
|
|
||||||
Here is an example of applying a `CHECK` constraint on multiple columns: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Employees ( |
|
||||||
ID int NOT NULL, |
|
||||||
Age int, |
|
||||||
Salary int, |
|
||||||
CONSTRAINT CHK_Person CHECK (Age>=18 AND Salary>=0) |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
Above SQL ensures that the persons' age must be greater than or equal to 18, and their salary is more than or equal to 0. |
|
||||||
|
|
||||||
It is also possible to use the `ALTER TABLE` command to add a `CHECK` constraint after the table has been created. |
|
||||||
|
|
||||||
```sql |
|
||||||
ALTER TABLE Employees |
|
||||||
ADD CONSTRAINT CHK_EmployeeAge CHECK (Age >= 21 AND Age <= 60); |
|
||||||
``` |
|
||||||
|
|
||||||
Above SQL ensures that the employees' age must be between 21 and 60. |
|
@ -1,28 +1,8 @@ |
|||||||
# COALESCE |
# COALESCE |
||||||
|
|
||||||
The `COALESCE` function in SQL is used to manage NULL values in data. It scans from left to right through the arguments and returns the first argument that is not `NULL`. |
`COALESCE` is an SQL function that returns the first non-null value in a list of expressions. It's commonly used to handle null values or provide default values in queries. `COALESCE` evaluates its arguments in order and returns the first non-null result, making it useful for data cleaning, report generation, and simplifying complex conditional logic in SQL statements. |
||||||
|
|
||||||
Syntax: |
Learn more from the following resources: |
||||||
```sql |
|
||||||
COALESCE(value1,value2,..., valueN) |
|
||||||
``` |
|
||||||
The `COALESCE` function allows handling the case where you have possible `NULL` values in your data and you want to replace it with some other value. |
|
||||||
|
|
||||||
For instance, here is an example of how you might use `COALESCE`: |
- [@article@How to use the COALESCE function in SQL](https://learnsql.com/blog/coalesce-function-sql/) |
||||||
|
- [@article@COALESCE - PostgreSQL](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-coalesce/) |
||||||
```sql |
|
||||||
SELECT product_name, COALESCE(price, 0) AS Price |
|
||||||
FROM products; |
|
||||||
``` |
|
||||||
In this example, if the "price" column for a product entry is `NULL`, it will instead return "0". |
|
||||||
|
|
||||||
Another common use case is using `COALESCE` to find the first non-NULL value in a list: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT COALESCE(NULL, NULL, 'third value', 'fourth value'); |
|
||||||
``` |
|
||||||
In this case, it would return "third value", as that's the first non-NULL value in the list. |
|
||||||
|
|
||||||
Remember, `COALESCE` does not update the original data. It only returns the first non-NULL value in the runtime. To update any NULL values permanently, you would need to use an `UPDATE` statement. |
|
||||||
|
|
||||||
The `COALESCE` function in SQL improves the reliability of your queries when null values are involved. Whether it's replacing nulls with default values or finding the earliest valid date, it's a very useful function to grasp. |
|
@ -1,59 +1,7 @@ |
|||||||
# CTEs (Common Table Expressions) |
# CTEs (Common Table Expressions) |
||||||
|
|
||||||
CTEs or Common Table Expressions are a type of temporary result set that are defined within the execution scope of a single SQL statement. They act like a temporary view for a single query, and they are typically used to simplify subqueries and improve readability. |
Common Table Expressions (CTEs) in SQL are named temporary result sets that exist within the scope of a single `SELECT`, `INSERT`, `UPDATE`, `DELETE`, or `MERGE` statement. Defined using the `WITH` clause, CTEs act like virtual tables that can be referenced multiple times within a query. They improve query readability, simplify complex queries by breaking them into manageable parts, and allow for recursive queries. CTEs are particularly useful for hierarchical or graph-like data structures and can enhance query performance in some database systems. |
||||||
|
|
||||||
## Syntax |
Learn more from the following resources: |
||||||
|
|
||||||
Here is the basic syntax of how to use a CTE in SQL: |
- [@article@Common Table Expressions (CTEs)](https://hightouch.com/sql-dictionary/sql-common-table-expression-cte) |
||||||
|
|
||||||
```sql |
|
||||||
WITH CTE_Name AS |
|
||||||
( |
|
||||||
SQL Query |
|
||||||
) |
|
||||||
SELECT * FROM CTE_Name |
|
||||||
``` |
|
||||||
|
|
||||||
In this syntax, the "WITH" keyword is used to create a CTE. The SQL query inside the parentheses is the query that creates the CTE. The final SELECT statement is used to query the data from the CTE. |
|
||||||
|
|
||||||
## Basic Usage |
|
||||||
|
|
||||||
An example of how to use a CTE is demonstrated below: |
|
||||||
|
|
||||||
```sql |
|
||||||
WITH Sales_CTE (SalesPersonID, NumberOfOrders) |
|
||||||
AS |
|
||||||
( |
|
||||||
SELECT SalesPersonID, COUNT(OrderID) |
|
||||||
FROM SalesOrderHeader |
|
||||||
GROUP BY SalesPersonID |
|
||||||
) |
|
||||||
SELECT E.EmployeeID, E.FirstName, E.LastName, S.NumberOfOrders |
|
||||||
FROM Employee E |
|
||||||
JOIN Sales_CTE S |
|
||||||
ON E.EmployeeID = S.SalesPersonID |
|
||||||
ORDER BY S.NumberOfOrders DESC; |
|
||||||
``` |
|
||||||
|
|
||||||
In this example, the CTE groups sales data by `SalesPersonID` and then joins this with the `Employee` table based on the `EmployeeID` to get the corresponding employee details. |
|
||||||
|
|
||||||
## Recursive CTEs |
|
||||||
|
|
||||||
SQL also supports recursive CTEs, which are CTEs that reference themselves. Recursive CTEs are generally used to solve problems that require iteration, such as traversing hierarchies. Here's an example: |
|
||||||
|
|
||||||
```sql |
|
||||||
WITH Recursive_CTE AS |
|
||||||
( |
|
||||||
SELECT EmployeeID, ManagerID, FirstName |
|
||||||
FROM Employee |
|
||||||
WHERE ManagerID IS NULL |
|
||||||
UNION ALL |
|
||||||
SELECT E.EmployeeID, E.ManagerID, E.FirstName |
|
||||||
FROM Employee E |
|
||||||
INNER JOIN Recursive_CTE RCTE |
|
||||||
ON E.ManagerID = RCTE.EmployeeID |
|
||||||
) |
|
||||||
SELECT * FROM Recursive_CTE; |
|
||||||
``` |
|
||||||
|
|
||||||
In the example above, the CTE starts with the employees who have no manager (`ManagerID IS NULL`). Then it recursively adds employees who are managed by the employees already in the CTE. The result is a list of all employees in the company, hierarchically organized by manager. |
|
||||||
|
@ -1,41 +1,7 @@ |
|||||||
# CONCAT |
# CONCAT |
||||||
|
|
||||||
`CONCAT` is a SQL function that allows you to concatenate, or join, two or more strings together. This is extremely useful whenever you need to combine text from multiple columns into a single column. |
`CONCAT` is an SQL function used to combine two or more strings into a single string. It takes multiple input strings as arguments and returns a new string that is the concatenation of all the input strings in the order they were provided. `CONCAT` is commonly used in `SELECT` statements to merge data from multiple columns, create custom output formats, or generate dynamic SQL statements. |
||||||
|
|
||||||
The syntax for the `CONCAT` function is quite simple: |
Learn more from the following resources: |
||||||
|
|
||||||
```sql |
- [@article@An overview of the CONCAT function in SQL](https://www.sqlshack.com/an-overview-of-the-concat-function-in-sql-with-examples/) |
||||||
CONCAT(string1, string2, ..., string_n) |
|
||||||
``` |
|
||||||
|
|
||||||
This function accepts as input any number of string arguments, from two to as many as needed, and returns a new string which is the result of all the input strings joined together. The strings are concatenated in the order in which they are passed to the function. |
|
||||||
|
|
||||||
Here's a simple example: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT CONCAT('Hello', ' ', 'World'); |
|
||||||
``` |
|
||||||
|
|
||||||
This will return the string: |
|
||||||
|
|
||||||
``` |
|
||||||
'Hello World' |
|
||||||
``` |
|
||||||
|
|
||||||
You can also use `CONCAT` with columns from a table: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT CONCAT(first_name, ' ', last_name) AS full_name |
|
||||||
FROM employees; |
|
||||||
``` |
|
||||||
|
|
||||||
The above query will return a new column `full_name` which is the result of `first_name` and `last_name` with a space in between. If `first_name` is 'John' and `last_name` is 'Doe', the returned full name would be 'John Doe'. |
|
||||||
|
|
||||||
However, keep in mind that `CONCAT` will return `NULL` if any of the input strings is `NULL`. To avoid this, you can use the `CONCAT_WS` function which accepts a separator as the first argument and then a list of strings to concatenate. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT CONCAT_WS(' ', first_name, last_name) AS full_name |
|
||||||
FROM employees; |
|
||||||
``` |
|
||||||
|
|
||||||
The `CONCAT_WS` function will ignore any `NULL` values, only joining the non-NULL values with the provided separator. Hence, 'John NULL' would become just 'John'. |
|
||||||
|
@ -1,33 +1,7 @@ |
|||||||
# Correlated Subqueries |
# Correlated Subqueries |
||||||
|
|
||||||
In SQL, a correlated subquery is a subquery that uses values from the outer query in its WHERE clause. The correlated subquery is evaluated once for each row processed by the outer query. It exists because it depends on the outer query and it cannot execute independently of the outer query because the subquery is correlated with the outer query as it uses its column in its WHERE clause. |
In SQL, a correlated subquery is a subquery that uses values from the outer query in its `WHERE` clause. The correlated subquery is evaluated once for each row processed by the outer query. It exists because it depends on the outer query and it cannot execute independently of the outer query because the subquery is correlated with the outer query as it uses its column in its `WHERE` clause. |
||||||
|
|
||||||
## Syntax: |
Learn more from the following resources: |
||||||
|
|
||||||
```sql |
- [@official@Correlated Subqueries](https://dev.mysql.com/doc/refman/8.4/en/correlated-subqueries.html) |
||||||
SELECT column_name [, column_name...] |
|
||||||
FROM table1 [, table2...] |
|
||||||
WHERE column_name OPERATOR |
|
||||||
(SELECT column_name [, column_name...] |
|
||||||
FROM table_name |
|
||||||
WHERE condition [table1.column_name = table2.column_name...]); |
|
||||||
``` |
|
||||||
|
|
||||||
## Code Example |
|
||||||
|
|
||||||
For instance, if you want to get the employees whose salaries are above their department's average salaries, it can be queried with a correlated subquery as follows: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT e1.employee_name, e1.salary |
|
||||||
FROM employee e1 |
|
||||||
WHERE salary > |
|
||||||
(SELECT AVG(salary) |
|
||||||
FROM employee e2 |
|
||||||
WHERE e1.department = e2.department); |
|
||||||
``` |
|
||||||
|
|
||||||
In the example above, the correlated subquery (the inner query) calculates the average salary for each department. The outer query then compares the salary of each employee to the average salary of their respective department. It returns the employees whose salaries are above their department's average. The correlated subquery is executed once for each row selected by the outer query. |
|
||||||
|
|
||||||
Also note that `e1` and `e2` are the aliases of the `employee` table so that we can use it in both the inner query and outer query. Here, `e2.department` in the inner query comes from the outer query's `e1.department`. |
|
||||||
|
|
||||||
Thus, a correlated subquery is a subquery that depends on the outer SQL query for its values. This means that the subquery is run once for every Row in the outer query, often resulting in quite a bit of processing, and thus slower results. |
|
@ -1,29 +1,7 @@ |
|||||||
# COUNT |
# COUNT |
||||||
|
|
||||||
`COUNT` is a SQL function that returns the number of rows that match a specified criteria. Essentially, `COUNT` function is used when you need to know the count of a record in a certain table's column. |
`COUNT` is an SQL aggregate function that returns the number of rows that match the specified criteria. It can be used to count all rows in a table, non-null values in a specific column, or rows that meet certain conditions when combined with a `WHERE` clause. `COUNT` is often used in data analysis, reporting, and performance optimization queries to determine the size of datasets or the frequency of particular values. |
||||||
|
|
||||||
There are two types of count function; `COUNT(*)` and `COUNT(column)`. |
Learn more from the following resources: |
||||||
|
|
||||||
- `COUNT(*)` counts all the rows in the target table whether columns contain null values or not. |
- [@article@COUNT](https://www.w3schools.com/sql/sql_count.asp) |
||||||
|
|
||||||
```sql |
|
||||||
SELECT COUNT(*) FROM table_name; |
|
||||||
``` |
|
||||||
|
|
||||||
- `COUNT(column)` counts the rows in the column of a table excluding null. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT COUNT(column_name) FROM table_name; |
|
||||||
``` |
|
||||||
|
|
||||||
You may also use `COUNT()` in conjunction with `GROUP BY` to return the count of rows within each group. |
|
||||||
|
|
||||||
A typical example would be: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name; |
|
||||||
``` |
|
||||||
|
|
||||||
Here, `column_name` is the name of the column based on which the rows will be grouped. This query will return the count of rows in each group of `column_name`. |
|
||||||
|
|
||||||
By understanding how to use the `COUNT()` function, you can extract more meaningful data from your tables, and perform analytics and generate reports based on the counts of certain attributes in your database. |
|
@ -1,52 +1,7 @@ |
|||||||
# Create Table |
# Create Table |
||||||
|
|
||||||
The `CREATE TABLE` statement in SQL is a Data Definition Language (DDL) command used to create a new table in the database. |
`CREATE TABLE` is an SQL statement used to define and create a new table in a database. It specifies the table name, column names, data types, and optional constraints such as primary keys, foreign keys, and default values. This statement establishes the structure of the table, defining how data will be stored and organized within it. `CREATE TABLE` is a fundamental command in database management, essential for setting up the schema of a database and preparing it to store data. |
||||||
|
|
||||||
## SQL CREATE TABLE Syntax |
Learn more from the following resources: |
||||||
|
|
||||||
The syntax for SQL `CREATE TABLE` is as follows: |
- [@article@CREATE TABLE](https://www.tutorialspoint.com/sql/sql-create-table.htm) |
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE table_name ( |
|
||||||
column1 datatype, |
|
||||||
column2 datatype, |
|
||||||
column3 datatype, |
|
||||||
.... |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
- `table_name` is the name of the table that you want to create. |
|
||||||
- `column1, column2,...` are the columns in the table. |
|
||||||
- `datatype` is the data type for the column, such as varchar, int, date, etc. |
|
||||||
|
|
||||||
## SQL CREATE TABLE Example |
|
||||||
|
|
||||||
Here is an example of the `CREATE TABLE` statement: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Employees ( |
|
||||||
ID int, |
|
||||||
Name varchar(255), |
|
||||||
Salary int, |
|
||||||
Department varchar(255), |
|
||||||
Position varchar(255) |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
This SQL command creates a new table named `Employees` with five columns, named 'ID', 'Name', 'Salary', 'Department', and 'Position'. The data types are int for the 'ID' and 'Salary', and varchar(255) for the others. |
|
||||||
|
|
||||||
## SQL CREATE TABLE with NOT NULL |
|
||||||
|
|
||||||
The `NOT NULL` constraint enforces a column to not accept null values. When creating a new table, you can add this constraint. Here is a practical example: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Employees ( |
|
||||||
ID int NOT NULL, |
|
||||||
Name varchar(255) NOT NULL, |
|
||||||
Salary int, |
|
||||||
Department varchar(255), |
|
||||||
Position varchar(255) |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
In the example above, the 'ID' and 'Name' must always have a value. They cannot be unassigned or undefined. |
|
@ -1,52 +1,8 @@ |
|||||||
# Creating Views |
# Creating Views |
||||||
|
|
||||||
In SQL, creating views can be achieved through the `CREATE VIEW` statement. A view is a virtual table based on the result-set of an SQL statement. It contains rows and columns from one or more tables. The syntax for the `CREATE VIEW` statement is: |
Creating views in SQL involves using the `CREATE VIEW` statement to define a virtual table based on the result of a `SELECT` query. Views don't store data themselves but provide a way to present data from one or more tables in a specific format. They can simplify complex queries, enhance data security by restricting access to underlying tables, and provide a consistent interface for querying frequently used data combinations. Views can be queried like regular tables and are often used to encapsulate business logic or present data in a more user-friendly manner. |
||||||
|
|
||||||
```sql |
Learn more from the following resources: |
||||||
CREATE VIEW view_name AS |
|
||||||
SELECT column1, column2, ... |
|
||||||
FROM table_name |
|
||||||
WHERE condition; |
|
||||||
``` |
|
||||||
|
|
||||||
Here: |
- [@article@How to create a view in SQL](https://www.sqlshack.com/how-to-create-a-view-in-sql-server/) |
||||||
- `CREATE VIEW view_name` : It creates a new view that you define with `view_name`. |
- [@video@SQL Views in 4 minutes](https://www.youtube.com/watch?v=vLLkNI-vkV8) |
||||||
- `AS SELECT column1, column2 ...` : These are the columns you want in your view. You can choose one or more columns from one or more tables. |
|
||||||
- `FROM table_name` : `table_name` is the name of the table from which you want to create the view. |
|
||||||
- `WHERE` : It is an optional clause that you can use to specify conditions for displaying records. |
|
||||||
|
|
||||||
**Example:** |
|
||||||
|
|
||||||
Let's say you have a table named `Employees` having following data: |
|
||||||
|
|
||||||
| ID | NAME | SALARY | DEPARTMENT_ID | |
|
||||||
|----|-------|--------|---------------| |
|
||||||
| 1 | John | 3000 | 2 | |
|
||||||
| 2 | Sue | 3500 | 3 | |
|
||||||
| 3 | Phil | 4500 | 2 | |
|
||||||
| 4 | Anna | 5000 | 1 | |
|
||||||
|
|
||||||
You can create a view that shows only the employees from department 2: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE VIEW Department2 AS |
|
||||||
SELECT Name, Salary |
|
||||||
FROM Employees |
|
||||||
WHERE Department_ID = 2; |
|
||||||
``` |
|
||||||
|
|
||||||
After running this statement, `Department2` will be a saved view in your database, and you can query it like you would with a standard table: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT * |
|
||||||
FROM Department2; |
|
||||||
``` |
|
||||||
|
|
||||||
This would bring up |
|
||||||
|
|
||||||
| NAME | SALARY | |
|
||||||
|------|--------| |
|
||||||
| John | 3000 | |
|
||||||
| Phil | 4500 | |
|
||||||
|
|
||||||
In total, the `CREATE VIEW` statement is a useful command when you want to save a particular query and its result set for future use. This can simplify complex queries by breaking them up into manageable parts. |
|
@ -1,93 +1,7 @@ |
|||||||
# Data Constraints |
# Data Constraints |
||||||
|
|
||||||
Data constraints in SQL are used to specify rules for the data in a table. Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the table. |
Data constraints in SQL are rules applied to columns or tables to enforce data integrity and consistency. They include primary key, foreign key, unique, check, and not null constraints. These constraints define limitations on the data that can be inserted, updated, or deleted in a database, ensuring that the data meets specific criteria and maintains relationships between tables. By implementing data constraints, database designers can prevent invalid data entry, maintain referential integrity, and enforce business rules directly at the database level. |
||||||
|
|
||||||
## Types of SQL Data Constraints |
Learn more from the following resources: |
||||||
|
|
||||||
1. **NOT NULL Constraint**: Ensures that a column cannot have a NULL value. |
- [@article@Data Constraints](https://www.w3schools.com/sql/sql_constraints.asp) |
||||||
|
|
||||||
For Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Students ( |
|
||||||
ID int NOT NULL, |
|
||||||
Name varchar(255) NOT NULL, |
|
||||||
Age int |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
2. **UNIQUE Constraint**: Ensures that all values in a column are different. |
|
||||||
|
|
||||||
For Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Students ( |
|
||||||
ID int NOT NULL UNIQUE, |
|
||||||
Name varchar(255) NOT NULL, |
|
||||||
Age int |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
3. **PRIMARY KEY Constraint**: Uniquely identifies each record in a database table. Primary keys must contain UNIQUE values. Exactly the same as the UNIQUE constraint but there can be many unique constraints in a table, but only one PRIMARY KEY constraint per table. |
|
||||||
|
|
||||||
For Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Students ( |
|
||||||
ID int NOT NULL, |
|
||||||
Name varchar(255) NOT NULL, |
|
||||||
Age int, |
|
||||||
PRIMARY KEY (ID) |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
4. **FOREIGN KEY Constraint**: Prevents actions that would destroy links between tables. A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table. |
|
||||||
|
|
||||||
For Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Orders ( |
|
||||||
OrderID int NOT NULL, |
|
||||||
OrderNumber int NOT NULL, |
|
||||||
ID int, |
|
||||||
PRIMARY KEY (OrderID), |
|
||||||
FOREIGN KEY (ID) REFERENCES Students(ID) |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
5. **CHECK Constraint**: The CHECK constraint ensures that all values in a column satisfies certain conditions. |
|
||||||
|
|
||||||
For Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Students ( |
|
||||||
ID int NOT NULL, |
|
||||||
Name varchar(255) NOT NULL, |
|
||||||
Age int, |
|
||||||
CHECK (Age>=18) |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
6. **DEFAULT Constraint**: Provides a default value for a column when none is specified. |
|
||||||
|
|
||||||
For Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Students ( |
|
||||||
ID int NOT NULL, |
|
||||||
Name varchar(255) NOT NULL, |
|
||||||
Age int, |
|
||||||
City varchar(255) DEFAULT 'Unknown' |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
7. **INDEX Constraint**: Used to create and retrieve data from the database very quickly. |
|
||||||
|
|
||||||
For Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE INDEX idx_name |
|
||||||
ON Students (Name); |
|
||||||
``` |
|
||||||
|
|
||||||
Note: Indexes are not a part of the SQL standard and are not supported by all databases. |
|
@ -1,49 +1,7 @@ |
|||||||
# Data Definition Language (DDL) |
# Data Definition Language (DDL) |
||||||
|
|
||||||
Data Definition Language (DDL) is a subset of SQL. Its primary function is to create, modify, and delete database structures but not data. The commands in DDL are: |
Data Definition Language (DDL) is a subset of SQL used to define and manage the structure of database objects. DDL commands include `CREATE`, `ALTER`, `DROP`, and `TRUNCATE`, which are used to create, modify, delete, and empty database structures such as tables, indexes, views, and schemas. These commands allow database administrators and developers to define the database schema, set up relationships between tables, and manage the overall structure of the database. DDL statements typically result in immediate changes to the database structure and can affect existing data. |
||||||
|
|
||||||
1. `CREATE`: This command is used to create the database or its objects (like table, index, function, views, store procedure, and triggers). |
Learn more from the following resources: |
||||||
|
|
||||||
```sql |
- [@article@Data Definition Language (DDL)](https://docs.getdbt.com/terms/ddl) |
||||||
CREATE TABLE table_name ( |
|
||||||
column1 data_type(size), |
|
||||||
column2 data_type(size), |
|
||||||
... |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
2. `DROP`: This command is used to delete an existing database or table. |
|
||||||
|
|
||||||
```sql |
|
||||||
DROP TABLE table_name; |
|
||||||
``` |
|
||||||
|
|
||||||
3. `ALTER`: This is used to alter the structure of the database. It is used to add, delete/drop or modify columns in an existing table. |
|
||||||
|
|
||||||
```sql |
|
||||||
ALTER TABLE table_name ADD column_name datatype; |
|
||||||
ALTER TABLE table_name DROP COLUMN column_name; |
|
||||||
ALTER TABLE table_name MODIFY COLUMN column_name datatype(size); |
|
||||||
``` |
|
||||||
|
|
||||||
4. `TRUNCATE`: This is used to remove all records from a table, including all spaces allocated for the records which are removed. |
|
||||||
|
|
||||||
```sql |
|
||||||
TRUNCATE TABLE table_name; |
|
||||||
``` |
|
||||||
|
|
||||||
5. `RENAME`: This is used to rename an object in the database. |
|
||||||
|
|
||||||
```sql |
|
||||||
-- To rename a table |
|
||||||
ALTER TABLE table_name |
|
||||||
RENAME TO new_table_name; |
|
||||||
|
|
||||||
-- To rename a column |
|
||||||
ALTER TABLE table_name |
|
||||||
RENAME COLUMN old_column_name TO new_column_name; |
|
||||||
``` |
|
||||||
|
|
||||||
Remember: In DDL operations, `COMMIT` and `ROLLBACK` statement cannot be performed because the MySQL engine automatically commits the changes. |
|
||||||
|
|
||||||
Remember to replace `table_name`, `column_name`, `datatype(size)`, `old_table_name`, and `new_table_name` in the examples above with your actual table names, column names, data types and sizes, and the old or new table names you want to specify. |
|
@ -1,54 +1,5 @@ |
|||||||
# Data Integrity and Security |
# Data Integrity and Security |
||||||
|
|
||||||
Integrity Security in SQL refers to the accuracy and consistency of the data in a database. It is a crucial aspect of the database that ensures the data being entered into databases follows the defined rules, preventing any damage to the main data. It comes in several forms: |
Data integrity and security in SQL encompass measures and techniques to ensure data accuracy, consistency, and protection within a database. This includes implementing constraints (like primary keys and foreign keys), using transactions to maintain data consistency, setting up user authentication and authorization, encrypting sensitive data, and regularly backing up the database. |
||||||
|
|
||||||
**1. Entity Integrity** |
SQL provides various tools and commands to enforce data integrity rules, control access to data, and protect against unauthorized access or data corruption, ensuring the reliability and confidentiality of stored information. |
||||||
|
|
||||||
Entity integrity ensures that there are no duplicate rows in a table. This is often managed with the help of the primary key. |
|
||||||
|
|
||||||
For example, consider the following SQL command to create a table. Primary Key on the EmployeeID column will ensure that every entry in this column is unique. |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Employee ( |
|
||||||
EmployeeID int NOT NULL, |
|
||||||
LastName varchar(255), |
|
||||||
FirstName varchar(255), |
|
||||||
Age int, |
|
||||||
PRIMARY KEY (EmployeeID) |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
**2. Domain Integrity** |
|
||||||
|
|
||||||
Domain Integrity enforces valid entries for a given column by restricting the type, the format, or the range of possible values. |
|
||||||
|
|
||||||
For example, setting a specific data type and size for a column. |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Employee ( |
|
||||||
EmployeeID int NOT NULL, |
|
||||||
LastName varchar(50), |
|
||||||
FirstName varchar(50), |
|
||||||
Age int CHECK (Age>=18 and Age<=60) |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
**3. Referential Integrity** |
|
||||||
|
|
||||||
Referential integrity ensures that relationships between tables remain consistent. More specifically, that a foreign key in one table must always refer to the primary key in another table. |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Orders ( |
|
||||||
OrderID int NOT NULL, |
|
||||||
OrderNumber int NOT NULL, |
|
||||||
EmployeeID int, |
|
||||||
PRIMARY KEY (OrderID), |
|
||||||
FOREIGN KEY (EmployeeID) REFERENCES Employee(EmployeeID) |
|
||||||
); |
|
||||||
``` |
|
||||||
**4. User-Defined Integrity** |
|
||||||
|
|
||||||
User-defined integrity refers to a set of rules specified by a user, which do not belong to the entity, domain, or referential integrity. |
|
||||||
For example, a user might define a rule that an employee's hire date must be less than 3 months in the future. |
|
||||||
|
|
||||||
Please note that SQL doesn't provide specific built-in functionalities to handle user-defined integrity, it depends on the code logic implemented by each application. |
|
@ -1,41 +1,3 @@ |
|||||||
# Data Manipulation Language (DML) |
# Data Manipulation Language (DML) |
||||||
|
|
||||||
*DML* is a subcategory of `SQL` which stands for _Data Manipulation Language_. The purpose of DML is to insert, retrieve, update and delete data from the database. With this, we can perform operations on existing records. |
Data Manipulation Language (DML) is a subset of SQL used to manage data within database objects. It includes commands like `SELECT`, `INSERT`, `UPDATE`, and `DELETE`, which allow users to retrieve, add, modify, and remove data from tables. DML statements operate on the data itself rather than the database structure, enabling users to interact with the stored information. These commands are essential for day-to-day database operations, data analysis, and maintaining the accuracy and relevance of the data within a database system. |
||||||
|
|
||||||
DML contains four commands which are: |
|
||||||
|
|
||||||
1. **INSERT INTO** - This command is used to insert new rows (records) into a table. |
|
||||||
|
|
||||||
Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
INSERT INTO table_name ( column1, column2, column3, ... ) |
|
||||||
VALUES ( value1, value2, value3, ... ) |
|
||||||
``` |
|
||||||
|
|
||||||
2. **SELECT** - This command is used to select data from a database. The data returned is stored in a result table, called the result-set. |
|
||||||
|
|
||||||
Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT column1, column2, ... |
|
||||||
FROM table_name |
|
||||||
``` |
|
||||||
|
|
||||||
3. **UPDATE** - This command is used to modify the existing rows in a table. |
|
||||||
|
|
||||||
Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
UPDATE table_name |
|
||||||
SET column1 = value1, column2 = value2, ... |
|
||||||
WHERE condition; |
|
||||||
``` |
|
||||||
|
|
||||||
4. **DELETE FROM** - This command is used to delete existing rows (records) from a table. |
|
||||||
|
|
||||||
Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
DELETE FROM table_name WHERE condition; |
|
||||||
``` |
|
@ -1,82 +1,7 @@ |
|||||||
# Data Types |
# Data Types |
||||||
|
|
||||||
SQL data types define the type of data that can be stored in a database table's column. Depending on the DBMS, the names |
SQL data types define the kind of values that can be stored in a column and determine how the data is stored, processed, and retrieved. Common data types include numeric types (`INTEGER`, `DECIMAL`), character types (`CHAR`, `VARCHAR`), date and time types (`DATE`, `TIMESTAMP`), binary types (`BLOB`), and boolean types. Each database management system may have its own specific set of data types with slight variations. Choosing the appropriate data type for each column is crucial for optimizing storage, ensuring data integrity, and improving query performance. |
||||||
of the data types can differ slightly. Here are the general types: |
|
||||||
|
|
||||||
## INT |
Learn more from the following resources: |
||||||
|
|
||||||
`INT` is used for whole numbers. For example: |
- [@article@SQL Data Types](https://www.digitalocean.com/community/tutorials/sql-data-types) |
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Employees ( |
|
||||||
ID INT, |
|
||||||
Name VARCHAR(30) |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
## DECIMAL |
|
||||||
|
|
||||||
`DECIMAL` is used for decimal and fractional numbers. For example: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Items ( |
|
||||||
ID INT, |
|
||||||
Price DECIMAL(5,2) |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
## CHAR |
|
||||||
|
|
||||||
`CHAR` is used for fixed-length strings. For example: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Employees ( |
|
||||||
ID INT, |
|
||||||
Initial CHAR(1) |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
## VARCHAR |
|
||||||
|
|
||||||
`VARCHAR` is used for variable-length strings. For example: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Employees ( |
|
||||||
ID INT, |
|
||||||
Name VARCHAR(30) |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
## DATE |
|
||||||
|
|
||||||
`DATE` is used for dates in the format (`YYYY-MM-DD`). |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Employees ( |
|
||||||
ID INT, |
|
||||||
BirthDate DATE |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
## DATETIME |
|
||||||
|
|
||||||
`DATETIME` is used for date and time values in the format (`YYYY-MM-DD HH:MI:SS`). |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Orders ( |
|
||||||
ID INT, |
|
||||||
OrderDate DATETIME |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
## BINARY |
|
||||||
|
|
||||||
`BINARY` is used for binary strings. |
|
||||||
|
|
||||||
## BOOLEAN |
|
||||||
|
|
||||||
`BOOLEAN` is used for boolean values (`TRUE` or `FALSE`). |
|
||||||
|
|
||||||
**Remember**, the specific syntax for creating tables and defining column data types can vary slightly depending upon |
|
||||||
the SQL database you are using (MySQL, PostgreSQL, SQL Server, SQLite, Oracle, etc.), but the general concept and |
|
||||||
organization of data types is cross-platform. |
|
@ -1,76 +1,7 @@ |
|||||||
# DATE |
# DATE |
||||||
|
|
||||||
In SQL, DATE is a data type that stores the date. It does not store time information. The format of the date is, 'YYYY-MM-DD'. For instance, '2022-01-01'. SQL provides several functions to handle and manipulate dates. |
The DATE data type in SQL is used to store calendar dates (typically in the format YYYY-MM-DD). It represents a specific day without any time information. DATE columns are commonly used for storing birthdates, event dates, or any other data that requires only day-level precision. SQL provides various functions to manipulate and format DATE values, allowing for date arithmetic, extraction of date components, and comparison between dates. The exact range of valid dates may vary depending on the specific database management system being used. |
||||||
|
|
||||||
Below are some common examples of how to use the DATE data type in SQL: |
Learn more from the following resources: |
||||||
|
|
||||||
## Create a table with DATE data type |
- [@article@SQL DATE](https://www.w3schools.com/sql/sql_dates.asp) |
||||||
|
|
||||||
```sql |
|
||||||
CREATE TABLE Orders ( |
|
||||||
OrderId int, |
|
||||||
ProductName varchar(255), |
|
||||||
OrderDate date |
|
||||||
); |
|
||||||
``` |
|
||||||
|
|
||||||
In this example, the OrderDate column uses the DATE data type to store the date of the order. |
|
||||||
|
|
||||||
## Insert a date value into a table |
|
||||||
|
|
||||||
```sql |
|
||||||
INSERT INTO Orders (OrderId, ProductName, OrderDate) |
|
||||||
VALUES (1, 'Product 1', '2022-01-01'); |
|
||||||
``` |
|
||||||
|
|
||||||
This command inserts a new row into the Orders table with a date. |
|
||||||
|
|
||||||
## Retrieve data with a specific date |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT * FROM Orders |
|
||||||
WHERE OrderDate = '2022-01-01'; |
|
||||||
``` |
|
||||||
|
|
||||||
This command retrieves all orders made on January 1, 2022. |
|
||||||
|
|
||||||
## Update a date value in a table |
|
||||||
|
|
||||||
```sql |
|
||||||
UPDATE Orders |
|
||||||
SET OrderDate = '2022-01-02' |
|
||||||
WHERE OrderId = 1; |
|
||||||
``` |
|
||||||
|
|
||||||
This command updates the date from January 1, 2022 to January 2, 2022, for the order with the order ID 1. |
|
||||||
|
|
||||||
## SQL Date Functions |
|
||||||
|
|
||||||
SQL also provides several built-in functions to work with the DATE data type: |
|
||||||
|
|
||||||
## CURRENT_DATE |
|
||||||
|
|
||||||
Returns the current date. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT CURRENT_DATE; |
|
||||||
``` |
|
||||||
|
|
||||||
## DATEADD |
|
||||||
|
|
||||||
Add or subtract a specified time interval from a date. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT DATEADD(day, 5, OrderDate) AS "Due Date" |
|
||||||
FROM Orders; |
|
||||||
``` |
|
||||||
In this example, we are adding 5 days to each OrderDate in the table Orders. |
|
||||||
|
|
||||||
## DATEDIFF |
|
||||||
|
|
||||||
Get the difference between two dates. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT DATEDIFF(day, '2022-01-01', '2022-01-06') AS "Difference"; |
|
||||||
``` |
|
||||||
It will return 5, that is the difference in days between the two dates. |
|
@ -1,45 +1,7 @@ |
|||||||
# DATEADD |
# DATEADD |
||||||
|
|
||||||
`DATEADD` is a built-in function in SQL that allows you to add or subtract units of time from a specified date. The function takes three parameters: |
`DATEADD` is an SQL function used to add or subtract a specified time interval to a date or datetime value. It typically takes three arguments: the interval type (e.g., day, month, year), the number of intervals to add or subtract, and the date to modify. This function is useful for date calculations, such as finding future or past dates, calculating durations, or generating date ranges. The exact syntax and name of this function may vary slightly between different database management systems (e.g., `DATEADD` in SQL Server, `DATE_ADD` in MySQL). |
||||||
|
|
||||||
- An interval type (such as day, month, year, hour, minute, second) |
Learn more from the following resources: |
||||||
- A number (which can be either positive, for future dates, or negative, for past dates) |
|
||||||
- A date from which calculation will be based. |
|
||||||
|
|
||||||
The usage of this function can be especially useful when you need to perform operations on dates, such as finding a date "n" days before or after a specified date, or getting the first or last day of a month. |
- [@article@DATEADD](https://www.mssqltips.com/sqlservertutorial/9380/sql-dateadd-function/) |
||||||
|
|
||||||
## Syntax |
|
||||||
|
|
||||||
The generic syntax for `DATEADD` is: |
|
||||||
|
|
||||||
```sql |
|
||||||
DATEADD(interval, number, date) |
|
||||||
``` |
|
||||||
Here's what each param means: |
|
||||||
|
|
||||||
- `interval`: The part of date to which an integer value will be added. This could be a year, quarter, month, day, hour, minute, second, millisecond, microsecond, or nanosecond. |
|
||||||
|
|
||||||
- `number`: The value to add. The value can either be negative to get dates in the past or positive to get dates in the future. |
|
||||||
|
|
||||||
- `date`: The date or datetime expression to which the interval and number are added. |
|
||||||
|
|
||||||
For example, if we want to add three days to the date '2022-01-01', we would write: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT DATEADD(day, 3, '2022-01-01') as NewDate |
|
||||||
``` |
|
||||||
|
|
||||||
The result would be: `2022-01-04`. |
|
||||||
|
|
||||||
You can substitute 'day' with any of the accepted interval types to add different units of time. |
|
||||||
|
|
||||||
## Sample Query |
|
||||||
|
|
||||||
If you have a table called `Orders` with a `DateTime` field `OrderDate` and you want to find all orders placed in the next seven days, you can use the `DATEADD` function as follows: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT * FROM Orders |
|
||||||
WHERE OrderDate <= DATEADD(day, 7, GETDATE()) |
|
||||||
``` |
|
||||||
|
|
||||||
This will return all orders from now until a week from now. |
|
@ -1,37 +1,7 @@ |
|||||||
# DELETE |
# DELETE |
||||||
|
|
||||||
The DELETE statement is used to delete existing records in a table. This is a straightforward process, but care must be taken because the DELETE statement is destructive and cannot be undone by default. |
DELETE is an SQL statement used to remove one or more rows from a table. It allows you to specify which rows to delete using a WHERE clause, or delete all rows if no condition is provided. DELETE is part of the Data Manipulation Language (DML) and is used for data maintenance, removing outdated or incorrect information, or implementing business logic that requires data removal. When used without a WHERE clause, it empties the entire table while preserving its structure, unlike the TRUNCATE command. |
||||||
|
|
||||||
## Syntax |
Learn more from the following resources: |
||||||
|
|
||||||
The basic syntax of a DELETE query with WHERE clause in SQL is as follows: |
- [@article@DELETE](https://www.w3schools.com/sql/sql_delete.asp) |
||||||
```sql |
|
||||||
DELETE FROM table_name [WHERE condition] |
|
||||||
``` |
|
||||||
|
|
||||||
- `table_name`: Specifies the table where you want to delete data. |
|
||||||
- `WHERE condition`: It is optional. You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records would be deleted. |
|
||||||
|
|
||||||
## Examples |
|
||||||
|
|
||||||
1. **DELETE ALL Rows** |
|
||||||
|
|
||||||
Deletes all rows from a table named 'students'. |
|
||||||
```sql |
|
||||||
DELETE FROM students; |
|
||||||
``` |
|
||||||
|
|
||||||
2. **DELETE Specified Rows** |
|
||||||
|
|
||||||
Deletes the student whose student_id is '1001' from the 'students' table. |
|
||||||
```sql |
|
||||||
DELETE FROM students WHERE student_id = '1001'; |
|
||||||
``` |
|
||||||
|
|
||||||
**Caution:** Be very careful when using the DELETE statement. If you omit the WHERE clause, all records will be deleted! |
|
||||||
|
|
||||||
## Multi-table deletions |
|
||||||
|
|
||||||
Some database systems allow for deleting from multiple tables in a single DELETE statement. This is database-specific and beyond the scope of the basic SQL DELETE command. |
|
||||||
|
|
||||||
Remember, always make sure to have a backup and confirm you're deleting the correct data before running a DELETE command, especially in production environments. |
|
@ -1,31 +1,7 @@ |
|||||||
# Dropping Views |
# Dropping Views |
||||||
|
|
||||||
"Dropping" in SQL is the process of deleting an existing database object. In the context of views, "dropping" refers to deleting an existing view from the database. Once a view is dropped, it cannot be used any longer until it is recreated with the same or new definition. If you're going to drop a view, ensure it's not being used anywhere in your application or it will lead to errors. |
Dropping views in SQL involves using the `DROP VIEW` statement to remove an existing view from the database. This operation permanently deletes the view definition, but it doesn't affect the underlying tables from which the view was created. Dropping a view is typically done when the view is no longer needed, needs to be replaced with a different definition, or as part of database maintenance. It's important to note that dropping a view can impact other database objects or applications that depend on it, so caution should be exercised when performing this operation. |
||||||
|
|
||||||
## Dropping Views |
Learn more from the following resources: |
||||||
|
|
||||||
You can drop a view in SQL using the `DROP VIEW` statement. The `DROP VIEW` statement removes one or more views from the database. You specify the name of the view that you want to remove after the `DROP VIEW` clause. |
- [@article@DROP VIEW](https://study.com/academy/lesson/sql-drop-view-tutorial-overview.html) |
||||||
|
|
||||||
Here is the basic syntax to drop an existing view: |
|
||||||
|
|
||||||
```sql |
|
||||||
DROP VIEW view_name; |
|
||||||
``` |
|
||||||
|
|
||||||
To drop multiple views in a single command, you use a list of comma-separated views. |
|
||||||
|
|
||||||
```sql |
|
||||||
DROP VIEW view_name1, view_name2, ..., view_name_n; |
|
||||||
``` |
|
||||||
|
|
||||||
**Note**: Be careful when dropping views. Once a view is dropped, all the permissions granted on it will also be dropped. |
|
||||||
|
|
||||||
Before dropping a view, you can check if the view exists by using the `IF EXISTS` parameter. If you drop a view that does not exist, you will get an error. To prevent this, you can use the `IF EXISTS` parameter. |
|
||||||
|
|
||||||
Here is how you do it: |
|
||||||
|
|
||||||
```sql |
|
||||||
DROP VIEW IF EXISTS view_name; |
|
||||||
``` |
|
||||||
|
|
||||||
In this case, if the view exists, it will be dropped. If the view does not exist, nothing happens and you don't get an error. |
|
@ -1,50 +1,9 @@ |
|||||||
# Dynamic SQL |
# Dynamic SQL |
||||||
|
|
||||||
**Dynamic SQL** |
|
||||||
|
|
||||||
Dynamic SQL is a programming method that allows you to build SQL statements dynamically at runtime. It allows you to create more flexible and adaptable applications because you can manipulate the SQL statements on the fly, in response to inputs or changing conditions. |
Dynamic SQL is a programming method that allows you to build SQL statements dynamically at runtime. It allows you to create more flexible and adaptable applications because you can manipulate the SQL statements on the fly, in response to inputs or changing conditions. |
||||||
|
|
||||||
Consider an application where a user can choose multiple search conditions from a range of choices. You might not know how many conditions the user will choose, or what they'll be until runtime. With static SQL, you would have to include a large number of potential search conditions in your WHERE clause. With dynamic SQL, you can build the search string based on the user's actual choices. |
Consider an application where a user can choose multiple search conditions from a range of choices. You might not know how many conditions the user will choose, or what they'll be until runtime. With static SQL, you would have to include a large number of potential search conditions in your WHERE clause. With dynamic SQL, you can build the search string based on the user's actual choices. Note that while the use of Dynamic SQL offers greater flexibility, it also comes with potential security risks such as SQL Injection, and should be used judiciously. Always validate and sanitize inputs when building dynamic queries. |
||||||
|
|
||||||
**Executing Dynamic SQL** |
|
||||||
|
|
||||||
There are two ways to execute dynamic SQL: |
|
||||||
|
|
||||||
1. `EXECUTE IMMEDIATE` statement |
|
||||||
2. `OPEN-FOR, FETCH, CLOSE` statements |
|
||||||
|
|
||||||
|
|
||||||
**Code Examples** |
|
||||||
|
|
||||||
1. Using `EXECUTE IMMEDIATE`: |
|
||||||
|
|
||||||
Here, a table name is passed as a variable to a PL/SQL block. The block concatenates the variable into a DELETE statement, which is executed dynamically. |
|
||||||
|
|
||||||
```sql |
|
||||||
DECLARE |
|
||||||
table_name VARCHAR(30) := 'employees'; |
|
||||||
sql_stmt VARCHAR(100); |
|
||||||
BEGIN |
|
||||||
sql_stmt := 'DELETE FROM ' || table_name; |
|
||||||
EXECUTE IMMEDIATE sql_stmt; |
|
||||||
END; |
|
||||||
``` |
|
||||||
|
|
||||||
2. Using `OPEN-FOR, FETCH, CLOSE` |
|
||||||
|
|
||||||
In this example, a dynamic SQL query is being built and executed using the `OPEN-FOR, FETCH, CLOSE` statements. |
|
||||||
|
|
||||||
```sql |
Learn more from the following resources: |
||||||
DECLARE |
|
||||||
sql_stmt VARCHAR2(1000); |
|
||||||
emp_id NUMBER(4) := 7566; |
|
||||||
emp_rec emp%ROWTYPE; |
|
||||||
BEGIN |
|
||||||
sql_stmt := 'SELECT * FROM emp WHERE empno = :id'; |
|
||||||
OPEN emp_cv FOR sql_stmt USING emp_id; |
|
||||||
FETCH emp_cv INTO emp_rec; |
|
||||||
CLOSE emp_cv; |
|
||||||
END; |
|
||||||
``` |
|
||||||
|
|
||||||
Note that while the use of Dynamic SQL offers greater flexibility, it also comes with potential security risks such as SQL Injection, and should be used judiciously. Always validate and sanitize inputs when building dynamic queries. |
- [@article@Dynamic SQL in SQL Server](https://www.sqlshack.com/dynamic-sql-in-sql-server/) |
@ -1,63 +1,7 @@ |
|||||||
# FULL OUTER JOIN |
# FULL OUTER JOIN |
||||||
|
|
||||||
A `FULL OUTER JOIN` in SQL is a method to combine rows from two or more tables, based on a related column between them. It returns all rows from the left table (`table1`) and from the right table (`table2`). |
A `FULL OUTER JOIN` in SQL combines the results of both `LEFT` and `RIGHT OUTER JOIN`s. It returns all rows from both tables, matching records where the join condition is met and including unmatched rows from both tables with `NULL` values in place of missing data. This join type is useful when you need to see all data from both tables, regardless of whether there are matching rows, and is particularly valuable for identifying missing relationships or performing data reconciliation between two tables. |
||||||
|
|
||||||
The `FULL OUTER JOIN` keyword combines the results of both left and right outer joins and returns all (matched or unmatched) rows from the tables on both sides of the join clause. |
Learn more from the following resources: |
||||||
|
|
||||||
If there are records in the "Customers" table that do not have matches in the "Orders" table, those will be included. Also, if there are records in the "Orders" table that do not have matches in the "Customers" table, those will be included. |
- [@article@FULL OUTER JOIN](https://www.w3schools.com/sql/sql_join_full.asp) |
||||||
|
|
||||||
## Syntax |
|
||||||
|
|
||||||
``` |
|
||||||
SELECT column_name(s) |
|
||||||
FROM table1 |
|
||||||
FULL OUTER JOIN table2 |
|
||||||
ON table1.column_name = table2.column_name; |
|
||||||
``` |
|
||||||
|
|
||||||
## Code Example |
|
||||||
|
|
||||||
Consider the following two tables: |
|
||||||
|
|
||||||
**Table1: Customers** |
|
||||||
|
|
||||||
| ID | Name | |
|
||||||
|----|-------| |
|
||||||
| 1 | Tom | |
|
||||||
| 2 | Lucy | |
|
||||||
| 3 | Steve | |
|
||||||
| 4 | Dave | |
|
||||||
|
|
||||||
**Table2: Orders** |
|
||||||
|
|
||||||
| OrderID | CustomerID | Product | |
|
||||||
|---------|------------|----------| |
|
||||||
| 1 | 3 | Apple | |
|
||||||
| 2 | 3 | Banana | |
|
||||||
| 3 | 1 | Orange | |
|
||||||
| 4 | 2 | Mango | |
|
||||||
| 5 | 7 | Blueberry| |
|
||||||
|
|
||||||
A `FULL OUTER JOIN` query would look like this: |
|
||||||
|
|
||||||
``` |
|
||||||
SELECT Customers.Name, Orders.Product |
|
||||||
FROM Customers |
|
||||||
FULL OUTER JOIN Orders |
|
||||||
ON Customers.ID = Orders.CustomerID |
|
||||||
ORDER BY Customers.Name; |
|
||||||
``` |
|
||||||
|
|
||||||
The result-set will look like this: |
|
||||||
|
|
||||||
| Name | Product | |
|
||||||
|-------|----------| |
|
||||||
| Tom | Orange | |
|
||||||
| Lucy | Mango | |
|
||||||
| Steve | Apple | |
|
||||||
| Steve | Banana | |
|
||||||
| NULL | Blueberry| |
|
||||||
| Dave | NULL | |
|
||||||
|
|
||||||
This response includes all customers and all orders. If no matching orders exist for a customer, or if no matching customer exists for an order, the missing side will contain NULL. |
|
||||||
For example, Dave made no orders (his details in the product column are NULL) and the Blueberry order was made by a non-existing customer (the customer's details are NULL in the name column). |
|
@ -1,46 +1,8 @@ |
|||||||
# GRANT and REVOKE |
# GRANT and REVOKE |
||||||
|
|
||||||
In SQL, `GRANT` and `REVOKE` are Data Control Language (DCL) commands used for providing and removing user privileges respectively. |
`GRANT` and `REVOKE` are SQL commands used to manage user permissions in a database. `GRANT` is used to give specific privileges (such as `SELECT`, `INSERT`, `UPDATE`, `DELETE`) on database objects to users or roles, while `REVOKE` is used to remove these privileges. These commands are essential for implementing database security, controlling access to sensitive data, and ensuring that users have appropriate permissions for their roles. By using `GRANT` and `REVOKE`, database administrators can fine-tune access control, adhering to the principle of least privilege in database management. |
||||||
|
|
||||||
## GRANT |
Learn more from the following resources: |
||||||
|
|
||||||
The `GRANT` statement allows database administrators to grant permissions or privileges on a database object to users. There are various types of privileges like SELECT, INSERT, UPDATE, DELETE, REFERENCES, ALL. |
- [@article@GRANT](https://www.ibm.com/docs/en/qmf/12.2.0?topic=privileges-sql-grant-statement) |
||||||
|
- [@article@REVOKE](https://www.ibm.com/docs/en/qmf/12.2.0?topic=privileges-sql-revoke-statement) |
||||||
You can use the `GRANT` statement as follows: |
|
||||||
|
|
||||||
```sql |
|
||||||
GRANT privilege_name |
|
||||||
ON object_name |
|
||||||
TO {user_name |PUBLIC |role_name} |
|
||||||
[WITH GRANT OPTION]; |
|
||||||
``` |
|
||||||
|
|
||||||
Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
GRANT SELECT ON employees TO user1; |
|
||||||
``` |
|
||||||
|
|
||||||
In this example, `user1` is granted permission to read/perform SELECT operations on the `employees` table. |
|
||||||
|
|
||||||
## REVOKE |
|
||||||
|
|
||||||
The `REVOKE` statement can be used when we want to revoke some or all of the privileges that were assigned earlier to a user or a group of users. The syntax for using the `REVOKE` command is similar to the `GRANT` command. |
|
||||||
|
|
||||||
Here's the syntax: |
|
||||||
|
|
||||||
```sql |
|
||||||
REVOKE privilege_name |
|
||||||
ON object_name |
|
||||||
FROM {user_name |PUBLIC |role_name} |
|
||||||
``` |
|
||||||
|
|
||||||
Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
REVOKE SELECT ON employees FROM user1; |
|
||||||
``` |
|
||||||
|
|
||||||
In this example, `user1` is revoked from the permission to read/perform SELECT operations on the `employees` table. |
|
||||||
|
|
||||||
Permission management is an important aspect of database management, understanding, and using `GRANT` and `REVOKE` operations help in maintaining the integrity and security of your data in SQL. |
|
@ -1,68 +1,7 @@ |
|||||||
# GROUP BY |
# GROUP BY |
||||||
|
|
||||||
"Group By" is a clause in SQL that is used to arrange identical data into groups. This clause comes under the category of Group Functions, alongside the likes of Count, Sum, Average, etc. |
`GROUP BY` is an SQL clause used in `SELECT` statements to arrange identical data into groups. It's typically used with aggregate functions (like `COUNT`, `SUM`, `AVG`) to perform calculations on each group of rows. `GROUP BY` collects data across multiple records and groups the results by one or more columns, allowing for analysis of data at a higher level of granularity. This clause is fundamental for generating summary reports, performing data analysis, and creating meaningful aggregations of data in relational databases. |
||||||
|
|
||||||
The syntax for 'Group by' is: |
Learn more from the following resources: |
||||||
|
|
||||||
```sql |
- [@article@SQL GROUP BY](https://www.programiz.com/sql/group-by) |
||||||
SELECT column1, column2 |
|
||||||
FROM table_name |
|
||||||
GROUP BY column1, column2; |
|
||||||
``` |
|
||||||
|
|
||||||
Here, column1, column2, are the names of the columns based on which we want to group the results. |
|
||||||
|
|
||||||
## Example: |
|
||||||
|
|
||||||
Assume we have a "Sales" table. This table has three columns: ID, Item, and Amount. |
|
||||||
|
|
||||||
```sql |
|
||||||
ID Item Amount |
|
||||||
--- ------ ------ |
|
||||||
1 A 150 |
|
||||||
2 B 200 |
|
||||||
3 A 100 |
|
||||||
4 B 50 |
|
||||||
5 A 200 |
|
||||||
6 A 100 |
|
||||||
7 B 150 |
|
||||||
``` |
|
||||||
|
|
||||||
Execute the following SQL statement... |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT Item, SUM(Amount) |
|
||||||
FROM Sales |
|
||||||
GROUP BY Item; |
|
||||||
``` |
|
||||||
|
|
||||||
This will concatenate, or "group", all items that are the same into one row, applying the SUM() function on their respective Amounts. The output will then be: |
|
||||||
|
|
||||||
```sql |
|
||||||
Item SUM(Amount) |
|
||||||
------ ---------- |
|
||||||
A 550 |
|
||||||
B 400 |
|
||||||
``` |
|
||||||
|
|
||||||
## Group By with Having Clause |
|
||||||
|
|
||||||
The Group By clause can also be used with the Having keyword. The Having keyword allows you to filter the results of the group function. |
|
||||||
|
|
||||||
For example: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT Item, SUM(Amount) |
|
||||||
FROM Sales |
|
||||||
GROUP BY Item |
|
||||||
HAVING SUM(Amount) > 150; |
|
||||||
``` |
|
||||||
|
|
||||||
This will return all grouped items where the total amount is more than 150. Hence, the result will be: |
|
||||||
|
|
||||||
```sql |
|
||||||
Item SUM(Amount) |
|
||||||
------ ---------- |
|
||||||
A 550 |
|
||||||
B 400 |
|
||||||
``` |
|
@ -1,57 +1,7 @@ |
|||||||
# GROUP BY |
# GROUP BY |
||||||
|
|
||||||
**Group By** is an SQL clause that arranges identical data into groups. It is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or multiple columns. |
GROUP BY is an SQL clause used in SELECT statements to arrange identical data into groups. It's typically used with aggregate functions (like COUNT, SUM, AVG) to perform calculations on each group of rows. GROUP BY collects data across multiple records and groups the results by one or more columns, allowing for analysis of data at a higher level of granularity. This clause is fundamental for generating summary reports, performing data analysis, and creating meaningful aggregations of data in relational databases. |
||||||
|
|
||||||
## Syntax: |
Learn more from the following resources: |
||||||
|
|
||||||
```sql |
- [@article@SQL GROUP BY](https://www.programiz.com/sql/group-by) |
||||||
SELECT column1, column2, ..., aggregate_function(column_name) |
|
||||||
FROM table_name |
|
||||||
WHERE condition |
|
||||||
GROUP BY column1, column2, ...; |
|
||||||
``` |
|
||||||
|
|
||||||
## Explanation: |
|
||||||
|
|
||||||
- **column1, column2**, these columns are not under the aggregate function or any operation. They will be used to group the data. |
|
||||||
- **aggregate_function(column_name)**, Aggregate functions will apply on the group of the column_name specified, not individual rows. |
|
||||||
- The **WHERE** clause is optional. It adds conditions to select which rows will be grouped. |
|
||||||
|
|
||||||
## Examples: |
|
||||||
|
|
||||||
Here's an example of the **Group By** clause in action. Given is a table **Sales**: |
|
||||||
|
|
||||||
| order_id | product_id | qty | |
|
||||||
|----------|------------|-----| |
|
||||||
| 1 | 1001 | 20 | |
|
||||||
| 2 | 1002 | 10 | |
|
||||||
| 3 | 1003 | 50 | |
|
||||||
| 4 | 1001 | 10 | |
|
||||||
| 5 | 1002 | 20 | |
|
||||||
| 6 | 1003 | 50 | |
|
||||||
|
|
||||||
## Example 1: |
|
||||||
```sql |
|
||||||
SELECT product_id, SUM(qty) |
|
||||||
FROM SALES |
|
||||||
GROUP BY product_id; |
|
||||||
``` |
|
||||||
|
|
||||||
The result will be: |
|
||||||
|
|
||||||
|product_id | SUM(qty) |
|
||||||
|-----------|----------| |
|
||||||
| 1001 | 30 | |
|
||||||
| 1002 | 30 | |
|
||||||
| 1003 | 100 | |
|
||||||
|
|
||||||
## Example 2: |
|
||||||
|
|
||||||
You can perform group by operation on multiple columns. In the below example, 'product_id' and 'order_id' are used to group the data. |
|
||||||
```sql |
|
||||||
SELECT product_id, order_id, SUM(qty) |
|
||||||
FROM SALES |
|
||||||
GROUP BY product_id, order_id; |
|
||||||
``` |
|
||||||
|
|
||||||
**Group By** clause can be used with **HAVING** clause to add a condition on grouped data. |
|
@ -1,72 +1,7 @@ |
|||||||
# Indexes |
# Indexes |
||||||
|
|
||||||
An index in SQL is a database object which is used to improve the speed of data retrieval operations on a database table. Similarly to how an index in a book helps you find information quickly without reading the entire book, an index in a database helps the database software find data quickly without scanning the entire table. |
Indexes in SQL are database objects that improve the speed of data retrieval operations on database tables. They work similarly to book indexes, providing a quick lookup mechanism for finding rows with specific column values. Indexes create a separate data structure that allows the database engine to locate data without scanning the entire table. While they speed up `SELECT` queries, indexes can slow down `INSERT`, `UPDATE`, and `DELETE` operations because the index structure must be updated. Proper index design is crucial for optimizing database performance, especially for large tables or frequently queried columns. |
||||||
|
|
||||||
## Clustered Index |
Learn more from the following resources: |
||||||
|
|
||||||
A clustered index determines the physical order of data inside a table. It sorts and stores the data rows in the table based on their key values. There can be only one clustered index per table. |
- [@article@Create SQL Index Statement](https://www.w3schools.com/sql/sql_create_index.asp) |
||||||
|
|
||||||
Creating a clustered index: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE CLUSTERED INDEX index_name |
|
||||||
ON table_name (column_name); |
|
||||||
``` |
|
||||||
|
|
||||||
## Non-Clustered Index |
|
||||||
|
|
||||||
A non-clustered index doesn’t sort the physical data inside the table. Instead, it creates a separate object within a table which points back to the original table rows after creating. You can create numerous non-clustered indexes per table. |
|
||||||
|
|
||||||
Creating a non-clustered index: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE NONCLUSTERED INDEX index_name |
|
||||||
ON table_name (column_name); |
|
||||||
``` |
|
||||||
|
|
||||||
## Indexes on Multiple Columns |
|
||||||
|
|
||||||
An index can be built on more than one column of a table, which results in index entries having values of multiple columns. This is known as a composite index. |
|
||||||
|
|
||||||
Creating a composite index: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE INDEX index_name |
|
||||||
ON table_name (column1, column2); |
|
||||||
``` |
|
||||||
|
|
||||||
## Unique Indexes |
|
||||||
|
|
||||||
A unique index doesn't allow any field to have duplicate values if the field is unique indexed. If a primary key is defined, a unique index can be applied automatically. |
|
||||||
|
|
||||||
Creating a unique index: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE UNIQUE INDEX index_name |
|
||||||
ON table_name (column_name); |
|
||||||
``` |
|
||||||
|
|
||||||
## Explicit vs Implicit Indexes |
|
||||||
|
|
||||||
Indexes explicitly created by users are known as explicit indexes, while indexes automatically created by SQL Server when a primary key or unique constraint is defined are known as implicit indexes. |
|
||||||
|
|
||||||
Creating an explicit index: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE INDEX index_name |
|
||||||
ON table_name (column_name); |
|
||||||
``` |
|
||||||
|
|
||||||
## Full-Text Indexes |
|
||||||
|
|
||||||
If you're dealing with text searching within a large string of text, full-text indexes are especially helpful. These indexes do not work using a standard comparison search but instead use word-breakers, filters, and noise-words (stop words). |
|
||||||
|
|
||||||
Creating a full-text index: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE FULLTEXT INDEX ON table_name |
|
||||||
(column_name) |
|
||||||
KEY INDEX index_name; |
|
||||||
``` |
|
||||||
|
|
||||||
Please note that the creation and maintenance of indexes involve a trade-off between query speed and update costs. Indexes speed up retrieval at the expense of slower updates and increased storage space. |
|
@ -1,69 +1,7 @@ |
|||||||
# SQL JOIN Queries |
# SQL JOIN Queries |
||||||
|
|
||||||
JOIN clause is used to combine rows from two or more tables, based on a related column between them. |
SQL `JOIN` queries combine rows from two or more tables based on a related column between them. There are several types of JOINs, including INNER JOIN (returns matching rows), `LEFT JOIN` (returns all rows from the left table and matching rows from the right), `RIGHT JOIN` (opposite of `LEFT JOIN`), and `FULL JOIN` (returns all rows when there's a match in either table). `JOIN`s are fundamental for working with relational databases, allowing users to retrieve data from multiple tables in a single query, establish relationships between tables, and perform complex data analysis across related datasets. |
||||||
|
|
||||||
## INNER JOIN: |
Learn more from the following resources: |
||||||
|
|
||||||
Inner join returns records that have matching values in both tables. For example: |
- [@article@7 SQL JOIN Examples With Detailed Explanations](https://learnsql.com/blog/sql-join-examples-with-explanations/) |
||||||
|
|
||||||
```sql |
|
||||||
SELECT Orders.OrderID, Customers.CustomerName |
|
||||||
FROM Orders |
|
||||||
INNER JOIN Customers |
|
||||||
ON Orders.CustomerID = Customers.CustomerID; |
|
||||||
``` |
|
||||||
|
|
||||||
## LEFT (OUTER) JOIN: |
|
||||||
|
|
||||||
Returns all records from the left table, and the matched records from the right table. Also returns NULL if there is no match. Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT Customers.CustomerName, Orders.OrderID |
|
||||||
FROM Customers |
|
||||||
LEFT JOIN Orders |
|
||||||
ON Customers.CustomerID = Orders.CustomerID; |
|
||||||
``` |
|
||||||
|
|
||||||
## RIGHT (OUTER) JOIN: |
|
||||||
|
|
||||||
Returns all records from the right table, and the matched records from the left table. Also returns null if there is no match. Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT Orders.OrderID, Customers.CustomerName |
|
||||||
FROM Orders |
|
||||||
RIGHT JOIN Customers |
|
||||||
ON Orders.CustomerID = Customers.CustomerID; |
|
||||||
``` |
|
||||||
## FULL (OUTER) JOIN: |
|
||||||
|
|
||||||
Returns all records when there is a match in either left (table1) or right (table2) table records. Also returns null if there is no match. Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT Customers.CustomerName, Orders.OrderID |
|
||||||
FROM Customers |
|
||||||
FULL OUTER JOIN Orders |
|
||||||
ON Customers.CustomerID = Orders.CustomerID; |
|
||||||
``` |
|
||||||
## SELF JOIN: |
|
||||||
|
|
||||||
Self join is a regular join, but the table is joined with itself. Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, A.City |
|
||||||
FROM Customers A, Customers B |
|
||||||
WHERE A.CustomerID <> B.CustomerID |
|
||||||
AND A.City = B.City; |
|
||||||
``` |
|
||||||
|
|
||||||
## NATURAL JOIN: |
|
||||||
|
|
||||||
The natural join is akin to an inner join, automatically linking two columns based on identical names. |
|
||||||
Note: Columns should have same data type in both tables |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT * |
|
||||||
FROM Customers |
|
||||||
NATURAL JOIN Orders; |
|
||||||
``` |
|
||||||
|
|
||||||
**Note**: JOINS can be used with SELECT, UPDATE, and DELETE statements. |
|
@ -1,50 +1,7 @@ |
|||||||
# JOINs |
# JOINs |
||||||
|
|
||||||
SQL Joins are used to retrieve data from two or more data tables, based on a related column between them. The key types of JOINs include: |
SQL `JOINs` are clauses used to combine rows from two or more tables based on a related column between them. They allow retrieval of data from multiple tables in a single query, enabling complex data analysis and reporting. The main types of `JOINs` include `INNER JOIN` (returns matching rows from both tables), `LEFT JOIN` (returns all rows from the left table and matching rows from the right), `RIGHT JOIN` (opposite of `LEFT JOIN`), and `FULL JOIN` (returns all rows when there's a match in either table). `JOINs` are fundamental to relational database operations, facilitating data integration and exploration across related datasets. |
||||||
|
|
||||||
1. INNER JOIN: This type of join returns records with matching values in both tables. |
Learn more from the following resources: |
||||||
|
|
||||||
```sql |
- [@article@SQL JOINs Cheat Sheet](https://www.datacamp.com/cheat-sheet/sql-joins-cheat-sheet) |
||||||
SELECT table1.column1, table2.column2... |
|
||||||
FROM table1 |
|
||||||
INNER JOIN table2 |
|
||||||
ON table1.matching_column = table2.matching_column; |
|
||||||
``` |
|
||||||
2. LEFT (OUTER) JOIN: Returns all records from the left table, and matched records from the right table. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT table1.column1, table2.column2... |
|
||||||
FROM table1 |
|
||||||
LEFT JOIN table2 |
|
||||||
ON table1.matching_column = table2.matching_column; |
|
||||||
``` |
|
||||||
3. RIGHT (OUTER) JOIN: Returns all records from the right table, and matched records from the left table. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT table1.column1, table2.column2... |
|
||||||
FROM table1 |
|
||||||
RIGHT JOIN table2 |
|
||||||
ON table1.matching_column = table2.matching_column; |
|
||||||
``` |
|
||||||
4. FULL (OUTER) JOIN: Returns all records when either a match is found in either left (table1) or right (table2) table records. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT table1.column1, table2.column2... |
|
||||||
FROM table1 |
|
||||||
FULL JOIN table2 |
|
||||||
ON table1.matching_column = table2.matching_column; |
|
||||||
``` |
|
||||||
5. SELF JOIN: A self join is a join in which a table is joined with itself. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT a.column_name, b.column_name... |
|
||||||
FROM table_name AS a, table_name AS b |
|
||||||
WHERE condition; |
|
||||||
``` |
|
||||||
6. CARTESIAN JOIN: If WHERE clause is omitted, the join operation produces a Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT table1.column1, table2.column2... |
|
||||||
FROM table1, table2; |
|
||||||
``` |
|
||||||
Each type of JOIN allows for the retrieval of data in different situations, making them flexible and versatile for different SQL queries. |
|
@ -1,50 +1,7 @@ |
|||||||
# lag |
# lag |
||||||
|
|
||||||
`LAG` is a window function provided by SQL that allows us to fetch data from a previous row in the same result set without using a self-join. This function is commonly used in data analysis, for instance, comparing sales in a certain period with sales in a previous period. |
`LAG` is a window function in SQL that provides access to a row at a specified offset prior to the current row within a partition. It allows you to compare the current row's values with previous rows' values without using self-joins. LAG is particularly useful for calculating running differences, identifying trends, or comparing sequential data points in time-series analysis. The function takes the column to offset, the number of rows to offset (default is 1), and an optional default value to return when the offset goes beyond the partition's boundary. |
||||||
|
|
||||||
The general syntax for using the `LAG` function is as follows: |
Learn more from the following resources: |
||||||
|
|
||||||
```sql |
- [@article@Understanding the LAG function in SQL](https://www.datacamp.com/tutorial/sql-lag) |
||||||
LAG (expression [, offset [, default]]) |
|
||||||
OVER ( |
|
||||||
[PARTITION BY partition_expression, ... ] |
|
||||||
ORDER BY sort_expression [ASC | DESC], ... |
|
||||||
) |
|
||||||
``` |
|
||||||
|
|
||||||
Let's break down this syntax: |
|
||||||
|
|
||||||
- `expression`: This is the value to return from a previous row. If you specify multiple expressions, `LAG` treats them as a single compound expression. |
|
||||||
- `offset`: This is an optional section where you specify the number of steps to reachback. By default, the `offset` is 1, meaning that it gets the value from a previous row. |
|
||||||
- `default`: This is another optional section where you define a value to return if the `LAG` function accesses beyond the scope of partition. By default, it returns NULL. |
|
||||||
|
|
||||||
## Example |
|
||||||
|
|
||||||
Suppose we have the following 'sales' table: |
|
||||||
|
|
||||||
| Year | Sales | |
|
||||||
| ---- | ----- | |
|
||||||
| 2017 | 200 | |
|
||||||
| 2018 | 250 | |
|
||||||
| 2019 | 300 | |
|
||||||
| 2020 | 350 | |
|
||||||
|
|
||||||
You'd like to compare the sales of each year to the sales of the previous year. Here's how you can do it using the `LAG` function: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT Year, |
|
||||||
Sales, |
|
||||||
LAG(Sales) OVER (ORDER BY Year) AS PrevYearSales |
|
||||||
FROM sales; |
|
||||||
``` |
|
||||||
|
|
||||||
This should produce: |
|
||||||
|
|
||||||
| Year | Sales | PrevYearSales | |
|
||||||
| ---- | ----- | ------------- | |
|
||||||
| 2017 | 200 | NULL | |
|
||||||
| 2018 | 250 | 200 | |
|
||||||
| 2019 | 300 | 250 | |
|
||||||
| 2020 | 350 | 300 | |
|
||||||
|
|
||||||
In this example, `LAG` fetched the sales of the previous year ordered by the 'Year' column. The sales in 2017 do not have a previous year, so `LAG` returns NULL. |
|
@ -1,34 +1,7 @@ |
|||||||
# lead |
# lead |
||||||
|
|
||||||
In SQL, the `LEAD` function is a kind of window function that allows you to look at a row after a certain row, and use its value in calculations. `LEAD` function returns the value from the next row (or a subsequent row) of the current row in the table. |
`LEAD` is a window function in SQL that provides access to a row at a specified offset after the current row within a partition. It's the counterpart to the `LAG` function, allowing you to look ahead in your dataset rather than behind. `LEAD` is useful for comparing current values with future values, calculating forward-looking metrics, or analyzing trends in sequential data. Like `LAG`, it takes arguments for the column to offset, the number of rows to look ahead (default is 1), and an optional default value when the offset exceeds the partition's boundary. |
||||||
|
|
||||||
## Usage |
Learn more from the following resources: |
||||||
|
|
||||||
The `LEAD` function takes three arguments: |
- [@article@SQL LEAD](https://www.codecademy.com/resources/docs/sql/window-functions/lead) |
||||||
|
|
||||||
1. `value_expression` - the column or expression whose next value will be returned. |
|
||||||
2. `offset` - determines how many rows ahead to retrieve the value from. If it's omitted, then its default value is 1. |
|
||||||
3. `default_value` - the value returned when the `LEAD` function navigates past the last row. If it's omitted, it returns NULL. |
|
||||||
|
|
||||||
The syntax of the `LEAD` function is as follows: |
|
||||||
|
|
||||||
```sql |
|
||||||
LEAD(value_expression, [offset], [default_value]) OVER ([PARTITION BY partition_expression] ORDER BY sort_expression [ASC | DESC]) |
|
||||||
``` |
|
||||||
|
|
||||||
## Example |
|
||||||
|
|
||||||
Consider a simple example where you have a "sales" table and you want to compare each monthly sale with the sale of the next month. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT |
|
||||||
month, |
|
||||||
sale, |
|
||||||
LEAD(sale) OVER (ORDER BY month) NextMonthSale |
|
||||||
FROM |
|
||||||
sales; |
|
||||||
``` |
|
||||||
|
|
||||||
This SQL command will give an output where each row displays the sale of the current month and the sale amount of the next month. |
|
||||||
|
|
||||||
Please note that 'LEAD' function might return 'NULL' if there are no subsequent rows in window frame to fetch. |
|
@ -1,30 +1,7 @@ |
|||||||
# LEFT JOIN |
# LEFT JOIN |
||||||
|
|
||||||
The SQL LEFT JOIN combines rows from two or more tables based on a related column between them and returns all rows from the left table (table1) and the matched rows from the right table (table2). If there is no match, the result is `NULL` on the right side. |
A `LEFT JOIN` in SQL returns all rows from the left (first) table and the matching rows from the right (second) table. If there's no match in the right table, `NULL` values are returned for those columns. This join type is useful when you want to see all records from one table, regardless of whether they have corresponding entries in another table. `LEFT JOIN`s are commonly used for finding missing relationships, creating reports that include all primary records, or when working with data where not all entries have corresponding matches in related tables. |
||||||
|
|
||||||
## Syntax |
Learn more from the following resources: |
||||||
``` |
|
||||||
SELECT column_name(s) |
|
||||||
FROM table1 |
|
||||||
LEFT JOIN table2 |
|
||||||
ON table1.column_name = table2.column_name; |
|
||||||
``` |
|
||||||
|
|
||||||
## How SQL LEFT JOIN Works |
- [@article@SQL LEFT JOIN](https://www.w3schools.com/sql/sql_join_left.asp) |
||||||
|
|
||||||
The `LEFT JOIN` keyword returns all records from the left table (table1), and the matched records from the right table (table2). The result is `NULL` from the right side, if there is no match. |
|
||||||
|
|
||||||
![LEFT JOIN Diagram](https://www.w3schools.com/sql/img_leftjoin.gif) |
|
||||||
|
|
||||||
## SQL LEFT JOIN Example |
|
||||||
|
|
||||||
Let's assume we have two tables: `Orders` and `Customers`. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT Orders.OrderID, Customers.CustomerName |
|
||||||
FROM Orders |
|
||||||
LEFT JOIN Customers |
|
||||||
ON Orders.CustomerID = Customers.CustomerID; |
|
||||||
``` |
|
||||||
|
|
||||||
This SQL statement would return all OrderID and the matching CustomerName. If there is no match, the result is `NULL`. |
|
@ -1,53 +1,7 @@ |
|||||||
# LENGTH |
# LENGTH |
||||||
|
|
||||||
In SQL, `LENGTH` is a built-in function that allows you to find the number of characters in a string or the length of a string. |
The `LENGTH` function in SQL returns the number of characters in a string. It's used to measure the size of text data, which can be helpful for data validation, formatting, or analysis. In some database systems, `LENGTH` may count characters differently for multi-byte character sets. Most SQL dialects support `LENGTH`, but some may use alternative names like LEN (in SQL Server) or `CHAR_LENGTH`. This function is particularly useful for enforcing character limits, splitting strings, or identifying anomalies in string data. |
||||||
|
|
||||||
Syntax: |
Learn more from the following resources: |
||||||
|
|
||||||
```sql |
- [@article@How to Check the Length of a String in SQL](https://learnsql.com/cookbook/how-to-check-the-length-of-a-string-in-sql/) |
||||||
LENGTH ( string ) |
|
||||||
``` |
|
||||||
Here, `string` can be any string literal, column or expression resulting in a string. |
|
||||||
|
|
||||||
## Examples |
|
||||||
|
|
||||||
Consider an "employees" table: |
|
||||||
|
|
||||||
| id | first_name | last_name | |
|
||||||
|----|------------|-----------| |
|
||||||
| 1 | John | Doe | |
|
||||||
| 2 | Jane | Smith | |
|
||||||
| 3 | Alice | Murphy | |
|
||||||
|
|
||||||
To compute the length of the first_name field for all records, use the following SQL statement: |
|
||||||
```sql |
|
||||||
SELECT first_name, LENGTH(first_name) as length_of_first_name |
|
||||||
FROM employees; |
|
||||||
``` |
|
||||||
Output: |
|
||||||
|
|
||||||
| first_name | length_of_first_name | |
|
||||||
|------------|----------------------| |
|
||||||
| John | 4 | |
|
||||||
| Jane | 4 | |
|
||||||
| Alice | 5 | |
|
||||||
|
|
||||||
## Usage with DISTINCT |
|
||||||
`LENGTH` can also be used in conjunction with `DISTINCT` to find the number of distinct lengths of a specific field. |
|
||||||
```sql |
|
||||||
SELECT DISTINCT LENGTH(first_name) as distinct_length_of_first_name |
|
||||||
FROM employees; |
|
||||||
``` |
|
||||||
|
|
||||||
## Usage with WHERE Clause |
|
||||||
|
|
||||||
It can work in the WHERE clause to return only those records where the length of a specific field meets a certain condition. |
|
||||||
```sql |
|
||||||
SELECT * |
|
||||||
FROM employees |
|
||||||
WHERE LENGTH(first_name) > 4; |
|
||||||
``` |
|
||||||
|
|
||||||
Do note that the `LENGTH` function may return different results in different SQL systems due to character set and collation differences. In some systems, `LENGTH()` returns length in characters while in others it could return length in bytes. |
|
||||||
|
|
||||||
For example, MySQL has separate `CHAR_LENGTH()` and `LENGTH()` functions. `CHAR_LENGTH()` returns the length of the string in characters, while `LENGTH()` in MySQL returns the length of the string in bytes. This can make a difference if your string includes multibyte characters (like UTF-8). In such scenarios, it's always recommended to be sure how your specific SQL system implements `LENGTH` function. |
|
@ -1,38 +1,7 @@ |
|||||||
# LOWER |
# LOWER |
||||||
|
|
||||||
`LOWER` is a built-in function in SQL used to return all uppercase character(s) in a string to lowercase. It can be quite useful when performing case-insensitive comparisons or searches in your queries. |
The `LOWER` function in SQL converts all characters in a specified string to lowercase. It's a string manipulation function that takes a single argument (the input string) and returns the same string with all alphabetic characters converted to their lowercase equivalents. `LOWER` is useful for standardizing data, making case-insensitive comparisons, or formatting output. It doesn't affect non-alphabetic characters or numbers in the string. `LOWER` is commonly used in data cleaning, search operations, and ensuring consistent data representation across different systems. |
||||||
|
|
||||||
## Syntax: |
Learn more from the following resources: |
||||||
|
|
||||||
The basic syntax for `LOWER` in SQL is: |
- [@article@How to change text to lowercase in SQL](https://learnsql.com/cookbook/how-to-change-text-to-lowercase-in-sql/) |
||||||
|
|
||||||
``` |
|
||||||
LOWER(string) |
|
||||||
``` |
|
||||||
|
|
||||||
Here, 'string' can be a literal string or a column of a table, and the function will return the string with all alphabetic characters converted to lowercase. |
|
||||||
|
|
||||||
## Example: |
|
||||||
|
|
||||||
Let's take a look at a very basic example. Assuming we have the following string "SQL is BAE!" and we want to convert it to lower case. |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT LOWER('SQL is BAE!') AS LowerCaseString; |
|
||||||
``` |
|
||||||
|
|
||||||
Output: |
|
||||||
```sql |
|
||||||
lowercasestring |
|
||||||
---------------- |
|
||||||
sql is bae! |
|
||||||
``` |
|
||||||
|
|
||||||
If you are using a column from a table, let's say we have a table 'students' with a column 'Name' and we want to convert all the entries in that column to lowercase: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT LOWER(Name) AS LowerCaseName FROM students; |
|
||||||
``` |
|
||||||
|
|
||||||
Here, the LOWER function will return all the names from the 'Name' column in the 'students' table in their lowercase forms. |
|
||||||
|
|
||||||
Remember, the `LOWER` function doesn't affect the numbers and special characters in the input string, it only converts uppercase alphabetical characters to lowercase. |
|
@ -1,48 +1,7 @@ |
|||||||
# Managing Indexes |
# Managing Indexes |
||||||
|
|
||||||
Indexes can drastically speed up data retrieval in SQL databases by allowing the database to immediately locate the data needed without having to scan the entire database. However, these additional data structures also consume storage, and maintaining them can slow down any create, update, or delete operations, hence the need to manage them appropriately. |
Managing indexes in SQL involves creating, modifying, and dropping indexes to optimize database performance. This process includes identifying columns that benefit from indexing (frequently queried or used in JOIN conditions), creating appropriate index types (e.g., single-column, composite, unique), and regularly analyzing index usage and effectiveness. Database administrators must balance the improved query performance that indexes provide against the overhead they introduce for data modification operations. Proper index management also includes periodic maintenance tasks like rebuilding or reorganizing indexes to maintain their efficiency as data changes over time. |
||||||
|
|
||||||
## Creating Indexes |
Learn more from the following resources: |
||||||
|
|
||||||
To create an index, you use the `CREATE INDEX` command followed by the index name, the table name, and the columns you want to use in the index. |
- [@article@SQL Server Indexes](https://www.sqlservercentral.com/articles/sql-server-indexes) |
||||||
|
|
||||||
```sql |
|
||||||
CREATE INDEX index_name |
|
||||||
ON table_name(column_name); |
|
||||||
``` |
|
||||||
|
|
||||||
## Removing Indexes |
|
||||||
|
|
||||||
If an index is no longer required or if it's causing performance issues due to too much storage consumption, it can be dropped using the `DROP INDEX` command. |
|
||||||
|
|
||||||
```sql |
|
||||||
DROP INDEX index_name; |
|
||||||
``` |
|
||||||
|
|
||||||
## Listing Indexes |
|
||||||
|
|
||||||
You can get a list of all the indexes on a table using the `SHOW INDEXES` command. |
|
||||||
|
|
||||||
```sql |
|
||||||
SHOW INDEXES IN table_name; |
|
||||||
``` |
|
||||||
|
|
||||||
Remember that most SQL databases automatically create indexes for primary keys, and they do not need to be managed manually. |
|
||||||
|
|
||||||
## Modifying Indexes |
|
||||||
|
|
||||||
Modifying an existing index often means dropping the old index and creating a new one. PostgreSQL, MySQL, and MS SQL Server provide a way to reindex without dropping and recreating them manually. |
|
||||||
|
|
||||||
For example, in PostgreSQL: |
|
||||||
|
|
||||||
```sql |
|
||||||
REINDEX INDEX index_name; |
|
||||||
``` |
|
||||||
|
|
||||||
## Indexes and Performance |
|
||||||
|
|
||||||
While indexes can improve read speed, they also slow down write operations because each write must also update the index. That's why it's essential to find a balance between the number of indexes and database performance. Too many indexes can negatively impact performance. |
|
||||||
|
|
||||||
Therefore, you should only create indexes when they are likely to be needed and when they will have a significant impact on improving query performance. You can use the SQL Server Profiler, MySQL's slow query log, or other database-specific tools to identify the queries that are running slow, and then create indexes to optimize those queries. Regularly monitor your database performance to make sure that the indexes are still needed and that they are providing the expected improvements. |
|
||||||
|
|
||||||
Add indexes strategically and purposefully, and do regular cleanups of any unnecessary indexes. |
|
@ -1,37 +1,7 @@ |
|||||||
# MAX |
# MAX |
||||||
|
|
||||||
The `MAX()` function in SQL is used to return the maximum value of an expression in a SELECT statement. |
`MAX` is an aggregate function in SQL that returns the highest value in a set of values. It can be used with numeric, date, or string data types, selecting the maximum value from a specified column. `MAX` is often used in combination with `GROUP` BY to find the highest value within each group. This function is useful for various data analysis tasks, such as finding the highest salary, the most recent date, or the alphabetically last name in a dataset. |
||||||
|
|
||||||
It can be used for numeric, character, and datetime column data types. If there are null values, then they are not considered for comparison. |
Learn more from the following resources: |
||||||
|
|
||||||
## Syntax |
- [@article@MAX](https://www.techonthenet.com/sql/max.php) |
||||||
|
|
||||||
```sql |
|
||||||
SELECT MAX(column_name) |
|
||||||
FROM table_name |
|
||||||
WHERE condition; |
|
||||||
``` |
|
||||||
|
|
||||||
In this syntax, the `column_name` argument is the column in the `table_name` that you wish to find the maximum value of. |
|
||||||
|
|
||||||
## Example |
|
||||||
|
|
||||||
Consider the following Employee table: |
|
||||||
|
|
||||||
| ID | NAME | SALARY | |
|
||||||
|----|----------|--------| |
|
||||||
| 1 | John | 1000 | |
|
||||||
| 2 | Robert | 2000 | |
|
||||||
| 3 | Jim | 3000 | |
|
||||||
| 4 | Jessica | 2500 | |
|
||||||
|
|
||||||
To find the highest salary amongst all the employees, you would use the `MAX()` function as follows: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT MAX(SALARY) AS "Highest Salary" |
|
||||||
FROM Employee; |
|
||||||
``` |
|
||||||
|
|
||||||
The above SQL returns `3000` as it’s the highest salary in the Employee table. |
|
||||||
|
|
||||||
Warning: SQL `MAX()` function will only return a single row as a result. If multiple rows hold the highest value and if you want to get all these rows, you should not use `MAX()`. A better option would be sorting the column and then `LIMIT` the result just to the first row. |
|
@ -1,57 +1,7 @@ |
|||||||
# MIN |
# MIN |
||||||
|
|
||||||
`MIN` is an SQL aggregate function used to return the smallest value in a selected column. It is useful in querying tables where users want to identify the smallest or least available value in datasets. `MIN` ignores any null values in the dataset. |
`MIN` is an aggregate function in SQL that returns the lowest value in a set of values. It works with numeric, date, or string data types, selecting the minimum value from a specified column. Often used in conjunction with `GROUP BY`, `MIN` can find the smallest value within each group. This function is useful for various data analysis tasks, such as identifying the lowest price, earliest date, or alphabetically first name in a dataset. |
||||||
|
|
||||||
Syntax: |
Learn more from the following resources: |
||||||
|
|
||||||
```sql |
- [@article@SQL MAX & MIN](https://www.programiz.com/sql/min-and-max) |
||||||
SELECT MIN(column_name) |
|
||||||
FROM table_name |
|
||||||
WHERE condition; |
|
||||||
``` |
|
||||||
|
|
||||||
In the case where `column_name` belongs to a numeric data type (Integers, Float, etc.), `MIN` returns the smallest numeric value in the column. |
|
||||||
|
|
||||||
If `column_name` belongs to datetime types (Date, Time, etc.), `MIN` returns the earliest date or time. |
|
||||||
|
|
||||||
If `column_name` belongs to string types (Char, Text, etc.), `MIN` returns the lowest value in lexicographic order (similar to alphabetic order). |
|
||||||
|
|
||||||
## Examples: |
|
||||||
|
|
||||||
Consider a table, named `Orders`, with the following layout: |
|
||||||
|
|
||||||
| OrderID | CustomerID | OrderDate | |
|
||||||
|---------|-------------|------------| |
|
||||||
| 1 | C01 | 2020-10-10 | |
|
||||||
| 2 | C02 | 2020-09-05 | |
|
||||||
| 3 | C01 | 2020-08-21 | |
|
||||||
|
|
||||||
1. To find the earliest order date in the `Orders` table, the `MIN` function is used in the following way: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT MIN(OrderDate) AS EarliestOrder |
|
||||||
FROM Orders; |
|
||||||
``` |
|
||||||
|
|
||||||
The result of this query will be `2020-08-21`. |
|
||||||
|
|
||||||
2. Suppose we have a Prices table with items and their prices. To find the lowest price, use: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT MIN(price) AS LowestPrice |
|
||||||
FROM Prices; |
|
||||||
``` |
|
||||||
|
|
||||||
This query will return the smallest value in the price column. |
|
||||||
|
|
||||||
One important usage is when it is used along with the `GROUP BY` clause to find the minimum value in each group. |
|
||||||
|
|
||||||
Example, to find the earliest order date for each customer: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT CustomerID, MIN(OrderDate) AS EarliestOrder |
|
||||||
FROM Orders |
|
||||||
GROUP BY CustomerID; |
|
||||||
``` |
|
||||||
|
|
||||||
This query will return the earliest order date for each customer. |
|
@ -1,33 +1,7 @@ |
|||||||
# MOD |
# MOD |
||||||
|
|
||||||
The SQL `MOD()` function is a mathematical function that returns the remainder of the values from the division of two numbers. It calculates the modulo operation. This function is very useful when you want to find the remainder value after one number is divided by another. |
The `MOD` function in SQL calculates the remainder when one number is divided by another. It takes two arguments: the dividend and the divisor. `MOD` returns the remainder of the division operation, which is useful for various mathematical operations, including checking for odd/even numbers, implementing cyclic behaviors, or distributing data evenly. The syntax and exact behavior may vary slightly between different database systems, with some using the % operator instead of the `MOD` keyword. |
||||||
|
|
||||||
## Syntax |
Learn more from the following resources: |
||||||
|
|
||||||
The syntax of the MOD function in SQL is: |
- [@article@MOD](https://www.w3schools.com/sql/func_mysql_mod.asp) |
||||||
```sql |
|
||||||
MOD(expression1, expression2) |
|
||||||
``` |
|
||||||
|
|
||||||
- `Expression1` and `Expression2` are the values that you want to apply the function to. |
|
||||||
|
|
||||||
## Basic Usage |
|
||||||
|
|
||||||
For instance, if you want to find the remainder of the division of 15 by 4 you would write: |
|
||||||
```sql |
|
||||||
SELECT MOD(15, 4) as result; |
|
||||||
``` |
|
||||||
The result would be `3` because 3 is the remainder after dividing 15 by 4. |
|
||||||
|
|
||||||
## Usage with Table Columns |
|
||||||
|
|
||||||
The `MOD()` function can also be applied to table columns. Let's imagine that you have a table named "Orders" with an "OrderNumber" column and you want to find the remainder of every order number when divided by 7, you would do: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT OrderNumber, MOD(OrderNumber, 7) as result |
|
||||||
FROM Orders; |
|
||||||
``` |
|
||||||
|
|
||||||
This will return a list of all order numbers, along with the remainder when each order number is divided by 7. |
|
||||||
|
|
||||||
Keep in mind that the SQL `MOD()` function may not work in the same way, or might not support all features, in every SQL database. Always refer to the documentation specific to the SQL database you are using. |
|
@ -1,82 +1,11 @@ |
|||||||
# Modifying Views |
# Modifying Views |
||||||
|
|
||||||
In SQL, you can modify a VIEW in two ways: |
In SQL, you can modify a `VIEW` in two ways: |
||||||
|
|
||||||
- Using CREATE OR REPLACE VIEW: This command helps you modify a VIEW but keeps the VIEW name intact. This is beneficial when you want to change the definition of the VIEW but do not want to change the VIEW name. |
- Using `CREATE` OR `REPLACE VIEW`: This command helps you modify a VIEW but keeps the VIEW name intact. This is beneficial when you want to change the definition of the `VIEW` but do not want to change the VIEW name. |
||||||
|
|
||||||
- Using the DROP VIEW and then CREATE VIEW: In this method, you first remove the VIEW using the DROP VIEW command and then recreate the view using the new definition with the CREATE VIEW command. |
- Using the `DROP VIEW` and then `CREATE VIEW`: In this method, you first remove the `VIEW` using the `DROP VIEW` command and then recreate the view using the new definition with the `CREATE VIEW` command. |
||||||
|
|
||||||
## Modifying VIEW Using CREATE OR REPLACE VIEW |
Learn more from the following resources: |
||||||
|
|
||||||
Syntax: |
- [@article@Modify Views in SQL Server](https://www.sqlshack.com/create-view-sql-modifying-views-in-sql-server/) |
||||||
|
|
||||||
```sql |
|
||||||
CREATE OR REPLACE VIEW view_name AS |
|
||||||
SELECT column1, column2, ... |
|
||||||
FROM table_name |
|
||||||
WHERE condition; |
|
||||||
``` |
|
||||||
|
|
||||||
Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
CREATE OR REPLACE VIEW customer_view AS |
|
||||||
SELECT customer_name, country |
|
||||||
FROM customers |
|
||||||
WHERE country='USA'; |
|
||||||
``` |
|
||||||
In this example, 'customer_view' will show the names and countries of customers only from the USA. |
|
||||||
|
|
||||||
## Modifying VIEW Using DROP VIEW and CREATE VIEW |
|
||||||
|
|
||||||
Syntax: |
|
||||||
Drop the VIEW: |
|
||||||
```sql |
|
||||||
DROP VIEW view_name; |
|
||||||
``` |
|
||||||
Create a new VIEW: |
|
||||||
```sql |
|
||||||
CREATE VIEW view_name AS |
|
||||||
SELECT column1, column2, ... |
|
||||||
FROM table_name |
|
||||||
WHERE condition; |
|
||||||
``` |
|
||||||
|
|
||||||
Example: |
|
||||||
Drop the VIEW |
|
||||||
```sql |
|
||||||
DROP VIEW customer_view; |
|
||||||
``` |
|
||||||
Create a new VIEW: |
|
||||||
```sql |
|
||||||
CREATE VIEW customer_view AS |
|
||||||
SELECT customer_name, country |
|
||||||
FROM customers |
|
||||||
WHERE country='UK'; |
|
||||||
``` |
|
||||||
In this example, we first removed 'customer_view'. Then, we created it again with the new definition where it now shows the names and countries of the customers only from the UK. |
|
||||||
|
|
||||||
**CAUTION**: If other views, stored procedures, or programs depend on this view, they will be affected after you drop the view. For this reason, using CREATE OR REPLACE VIEW is generally safer. |
|
||||||
|
|
||||||
## Modifying Data through VIEW |
|
||||||
|
|
||||||
In some cases, you can modify the data of the underlying tables via a VIEW. |
|
||||||
|
|
||||||
Syntax: |
|
||||||
|
|
||||||
```sql |
|
||||||
UPDATE view_name |
|
||||||
SET column1 = value1, column2 = value2, ... |
|
||||||
WHERE condition; |
|
||||||
``` |
|
||||||
|
|
||||||
Example: |
|
||||||
|
|
||||||
```sql |
|
||||||
UPDATE customer_view |
|
||||||
SET country = 'USA' |
|
||||||
WHERE customer_name = 'John Doe'; |
|
||||||
``` |
|
||||||
This command will update the country of 'John Doe' to 'USA' in both the VIEW and the underlying table. |
|
||||||
|
|
||||||
However, not every VIEW is updatable. You can only modify the data if the VIEW you're modifying is a simple VIEW that returns results from a single table without any aggregation or complex clauses. If you attempt to modify a complex view (i.e., it includes JOIN, GROUP BY, HAVING, DISTINCT), you will get an error. |
|
@ -1,40 +1,7 @@ |
|||||||
# NULLIF |
# NULLIF |
||||||
|
|
||||||
`NULLIF` is a built-in conditional function in SQL Server. The `NULLIF` function compares two expressions and returns NULL if they are equal or the first expression if they are not. |
`NULLIF` is an SQL function that compares two expressions and returns NULL if they are equal, otherwise it returns the first expression. It's particularly useful for avoiding division by zero errors or for treating specific values as `NULL` in calculations or comparisons. `NULLIF` takes two arguments and is often used in combination with aggregate functions or in `CASE` statements to handle special cases in data processing or reporting. |
||||||
|
|
||||||
## Syntax |
Learn more from the following resources: |
||||||
|
|
||||||
Here's the syntax of the `NULLIF` function: |
- [@article@NULLIF](https://www.w3schools.com/sql/func_sqlserver_nullif.asp) |
||||||
|
|
||||||
```sql |
|
||||||
NULLIF(expression1, expression2); |
|
||||||
``` |
|
||||||
`NULLIF` compares `expression1` to `expression2`. If `expression1` and `expression2` are equal, the function returns NULL. Otherwise, it returns `expression1`. Both expressions must have the same data type. |
|
||||||
|
|
||||||
## Example |
|
||||||
|
|
||||||
Consider the following example: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT |
|
||||||
first_name, |
|
||||||
last_name, |
|
||||||
NULLIF(email, 'NA') AS email |
|
||||||
FROM |
|
||||||
users; |
|
||||||
``` |
|
||||||
In this SQL Server `NULLIF` function example, if the field email is 'NA', then NULL would be returned. Otherwise the actual `email` field value is returned. |
|
||||||
|
|
||||||
In another example, consider a division operation: |
|
||||||
|
|
||||||
```sql |
|
||||||
SELECT |
|
||||||
avg_salary, |
|
||||||
NULLIF(avg_salary, 0) AS avg_salary_no_zero |
|
||||||
FROM |
|
||||||
positions; |
|
||||||
``` |
|
||||||
|
|
||||||
In this SQL Server `NULLIF` function example, if `avg_salary` field is 0, then NULL would be returned. This is useful to avoid division by zero errors. |
|
||||||
|
|
||||||
In nutshell, the SQL `NULLIF` function can be handy in many scenarios such as to circumvent division by zero errors or to translate known sentinel values into NULL values that can be handled by SQL's NULL handling functions. |
|
Loading…
Reference in new issue