rewriting
All checks were successful
learn org at code.softwareshinobi.com/databases.softwareshinobi.com/pipeline/head This commit looks good
All checks were successful
learn org at code.softwareshinobi.com/databases.softwareshinobi.com/pipeline/head This commit looks good
This commit is contained in:
140
landing/docs/SQL-101/004-basic-syntax.md
Normal file
140
landing/docs/SQL-101/004-basic-syntax.md
Normal file
@@ -0,0 +1,140 @@
|
||||
# Essential Commands
|
||||
|
||||
Mastering foundational SQL is prerequisite for building effective data-driven Java applications. This document outlines the core SQL Data Manipulation Language (DML) statements—`SELECT`, `INSERT`, `UPDATE`, `DELETE`.
|
||||
|
||||
Precision in these commands is paramount for application performance, scalability, and data integrity. These statements are the direct instructions executed by the database engine.
|
||||
|
||||
## SELECT
|
||||
|
||||
Employ the `SELECT` statement to retrieve data subsets from database tables.
|
||||
|
||||
**Purpose:** Data retrieval based on specified criteria.
|
||||
|
||||
```sql
|
||||
SELECT column1, column2 FROM table_name;
|
||||
```
|
||||
|
||||
* `SELECT`: Initiates data retrieval operations.
|
||||
* `column1, column2`: Designates the specific columns required. List multiple columns separated by commas.
|
||||
* `FROM table_name`: Identifies the source table for the operation.
|
||||
|
||||
Retrieve all columns using the `*` wildcard:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users;
|
||||
```
|
||||
|
||||
**Example:** Fetch the `username` and `email` for all entries within the `users` table.
|
||||
|
||||
```sql
|
||||
SELECT username, email FROM users;
|
||||
```
|
||||
|
||||
Execution against an empty table yields no result rows. For a populated table with columns `id`, `username`, `about`, `birthday `, `active`, `email`, a `SELECT *` might produce:
|
||||
|
||||
| id | username | about | birthday | active | email |
|
||||
|----|----------------|-------|----------|--------|----------------------|
|
||||
| 1 | software shinobi | NULL | NULL | 1 | software shinobi@email.com |
|
||||
|
||||
*(Note: Database systems commonly represent boolean `true` as `1`)*.
|
||||
|
||||
Selecting only `username` and `email`:
|
||||
|
||||
```sql
|
||||
SELECT username, email FROM users;
|
||||
```
|
||||
|
||||
| username | email |
|
||||
|----------------|----------------------|
|
||||
| software shinobi | software shinobi@email.com |
|
||||
|
||||
## INSERT
|
||||
|
||||
Utilize the `INSERT` statement to append new records (rows) to a database table.
|
||||
|
||||
**Purpose:** Introduction of new data rows.
|
||||
|
||||
```sql
|
||||
INSERT INTO table_name (column1, column2) VALUES (value1, value 2);
|
||||
```
|
||||
|
||||
* `INSERT INTO`: The command directive for adding data.
|
||||
* `table_name (column1, column2)`: Specifies the target table and the explicit columns receiving data.
|
||||
* `VALUES (value1, value2)`: Provides the data values corresponding to the specified column list. Value order must align with column order.
|
||||
|
||||
**Example:** Add a single user entry to the `users` table.
|
||||
|
||||
```sql
|
||||
INSERT INTO users (username, email, active)
|
||||
VALUES (' software shinobi', 'software shinobi@email.com', true);
|
||||
```
|
||||
|
||||
Omitting the column list requires supplying values for *all* columns in the table, strictly adhering to the table's column definition order.
|
||||
|
||||
## UPDATE
|
||||
|
||||
Employ the `UPDATE` statement to modify existing data entries within a database table.
|
||||
|
||||
**Purpose:** Modification of existing data records.
|
||||
|
||||
```sql
|
||||
UPDATE table_name SET column1 = new_value WHERE condition;
|
||||
```
|
||||
|
||||
* `UPDATE table_ name`: Declares the table targeted for modifications.
|
||||
* `SET column1 = new_value`: Assigns `new_value` to `column1`. Multiple `column = value` assignments are permitted, separated by commas.
|
||||
* `WHERE condition`: The essential filter clause. Only rows satisfying this condition are processed.
|
||||
|
||||
**Example:** Adjust the username for the user associated with `id = 1`.
|
||||
|
||||
```sql
|
||||
UPDATE users SET username = 'Software Shinobi' WHERE id = 1;
|
||||
```
|
||||
|
||||
**Critical:** Excluding the `WHERE` clause will apply the changes to *every* row in the table. Exercise extreme caution and validate constraints.
|
||||
|
||||
## DELETE
|
||||
|
||||
Use the `DELETE` statement to eliminate records (rows) from a database table.
|
||||
|
||||
**Purpose:** Removal of data records.
|
||||
|
||||
```sql
|
||||
DELETE FROM table_name WHERE condition;
|
||||
```
|
||||
|
||||
* `DELETE FROM table_name`: Identifies the table from which rows will be removed.
|
||||
* `WHERE condition`: Specifies the criteria determining which rows are deleted.
|
||||
|
||||
**Example:** Remove the user record where `id` is equal to 1.
|
||||
|
||||
```sql
|
||||
DELETE FROM users WHERE id = 1 ;
|
||||
```
|
||||
|
||||
**Critical:** Omitting the `WHERE` clause triggers the deletion of *all* records in the table. Such data removal is typically irreversible without a prior backup. Proceed with absolute certainty.
|
||||
|
||||
## Comments
|
||||
|
||||
Incorporate comments into SQL scripts to bolster readability and clarify operational intent. Comments are explicitly ignored by the database engine during execution.
|
||||
|
||||
**Purpose:** Script comprehension and internal documentation.
|
||||
|
||||
**Single-line comments:** Prefixed by `--`. All text subsequent to `--` on the same line is treated as a comment.
|
||||
|
||||
```sql
|
||||
SELECT * FROM users; -- Retrieve all user records
|
||||
```
|
||||
|
||||
**Multi-line comments:** Enclosed between `/*` and `*/`. Ideal for extended explanations or temporary exclusion of SQL blocks.
|
||||
|
||||
```sql
|
||||
/*
|
||||
This complex query block
|
||||
fetches data for quarterly reports.
|
||||
Needs optimization review.
|
||||
*/
|
||||
-- SELECT revenue_data FROM finance_table WHERE quarter = 'Q2';
|
||||
```
|
||||
|
||||
Apply comments strategically to explain nuanced logic or articulate the strategic objective of specific queries. Maintain consistent commenting practices within your team to ensure maximum collaborative clarity.
|
||||
341
landing/docs/SQL-101/005-select.md
Normal file
341
landing/docs/SQL-101/005-select.md
Normal file
@@ -0,0 +1,341 @@
|
||||
# SELECT Statement
|
||||
|
||||
The `SELECT ` statement is the primary tool for retrieving data from database tables. It forms the core of data interaction in SQL, enabling projection operations from Relational Algebra.
|
||||
|
||||
Use `SELECT` to retrieve all records or filter records based on specific criteria.
|
||||
|
||||
First, create the necessary database and table for demonstration.
|
||||
|
||||
```sql
|
||||
CREATE DATABASE sql_demo;
|
||||
```
|
||||
|
||||
Switch to the database:
|
||||
|
||||
```sql
|
||||
USE sql_demo;
|
||||
```
|
||||
|
||||
Create a `users` table:
|
||||
|
||||
```sql
|
||||
CREATE TABLE users
|
||||
(
|
||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
username VARCHAR(255) NOT NULL,
|
||||
about TEXT,
|
||||
email VARCHAR(255),
|
||||
birthday DATE,
|
||||
active BOOL
|
||||
);
|
||||
```
|
||||
|
||||
Insert initial data:
|
||||
|
||||
```sql
|
||||
INSERT INTO users
|
||||
( username, email, active )
|
||||
VALUES
|
||||
('shinobi', 's@valorantdigital.com', true),
|
||||
(' Java Team Six', 'd@valorantdigital.com', false),
|
||||
('tony', 't@valorantdigital.com', true);
|
||||
```
|
||||
|
||||
Output confirms data insertion:
|
||||
|
||||
```
|
||||
Query OK, 3 rows affected (0.00 sec)
|
||||
Records: 3 Duplicates: 0 Warnings: 0
|
||||
```
|
||||
|
||||
## Selecting All Columns
|
||||
|
||||
Retrieve all data from the `users` table using `SELECT *`:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users;
|
||||
```
|
||||
|
||||
This statement executes the retrieval action (`SELECT`). The asterisk (`*`) specifies all columns. The `FROM` clause indicates the source table (`users`).
|
||||
|
||||
Output includes all entries and all columns:
|
||||
|
||||
```
|
||||
+ ----+---------------+-------+----------+---------+---------------------+
|
||||
| id | username | about | birthday | active | email |
|
||||
+----+---------------+-------+----------+--------+-----------------------+
|
||||
| 1 | shinobi | NULL | NULL | 1 | s@valorantdigital.com |
|
||||
| 2 | Java Team Six | NULL | NULL | 0 | d@valorantdigital.com |
|
||||
| 3 | tony | NULL | NULL | 1 | t@valorantdigital.com |
|
||||
+----+---------------+-------+----------+--------+-----------------------+
|
||||
3 rows in set (0.00 sec)
|
||||
```
|
||||
|
||||
This retrieves all 3 users created, including currently `NULL` `about` and `birthday` fields. Often, tables have many columns; you will frequently need to select only a subset.
|
||||
|
||||
## Pattern Matching
|
||||
|
||||
SQL pattern matching finds data without knowing the exact value. Use wildcard characters (`_`, `%`) with `LIKE` or `ILIKE`.
|
||||
|
||||
* `_`: Matches any single character.
|
||||
* `%`: Matches any number of characters (including zero).
|
||||
|
||||
Find usernames ending with `y`:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE username LIKE '%y';
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----+----------+-------+----------+--------+-----------------------+
|
||||
| id | username | about | birthday | active | email |
|
||||
+----+----------+-------+----------+--------+-----------------------+
|
||||
| 1 | shinobi | NULL | NULL | 1 | s@valorantdigital.com |
|
||||
| 3 | tony | NULL | NULL | 1 | t@valorantdigital.com |
|
||||
+----+---------+-------+----------+--------+-----------------------+
|
||||
```
|
||||
|
||||
The `%` before `y` matches any characters preceding `y`.
|
||||
|
||||
To match a specific number of characters, use multiple `_`. Each `_` is one character.
|
||||
|
||||
Find usernames with `e` as the second character:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE username LIKE '_e%';
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----+---------------+-------+----------+--------+-----------------------+
|
||||
| id | username | about | birthday | active | email |
|
||||
+----+---------------+-------+----------+--------+-----------------------+
|
||||
| 2 | Java Team Six | NULL | NULL | 0 | d@valorantdigital.com |
|
||||
+----+---------------+-------+----------+--------+-----------------------+
|
||||
```
|
||||
|
||||
Note that `LIKE` is case-sensitive. Use `ILIKE` to perform case-insensitive pattern matching.
|
||||
|
||||
## Formatting Results
|
||||
|
||||
Each SQL statement terminates with a semi-colon (`;`). Alternatively, use `\G` to format output as a list, improving readability for tables with numerous columns.
|
||||
|
||||
```sql
|
||||
SELECT * FROM users \G
|
||||
```
|
||||
|
||||
Output is formatted vertically:
|
||||
|
||||
```
|
||||
*************************** 1. row ***************************
|
||||
id: 1
|
||||
username: shinobi
|
||||
about: NULL
|
||||
birthday: NULL
|
||||
active: 1
|
||||
email: s@valorantdigital.com
|
||||
*************************** 2 . row ***************************
|
||||
id: 2
|
||||
username: Java Team Six
|
||||
about: NULL
|
||||
birthday: NULL
|
||||
active: 0
|
||||
email: d@valorantdigital.com
|
||||
...
|
||||
```
|
||||
|
||||
This vertical format is practical when table width exceeds display capacity.
|
||||
|
||||
## Selecting Specific Columns
|
||||
|
||||
Instead of `*`, list desired columns separated by commas to retrieve only those fields. Retrieve `username` and `active`:
|
||||
|
||||
```sql
|
||||
SELECT username, active FROM users;
|
||||
```
|
||||
|
||||
Output contains only the specified columns:
|
||||
|
||||
```
|
||||
+---------------+--------+
|
||||
| username | active |
|
||||
+---------------+--------+
|
||||
| shinobi | 1 |
|
||||
| Java Team Six | 0 |
|
||||
| tony | 1 |
|
||||
+---------------+--------+
|
||||
```
|
||||
|
||||
Note: SQL names are case-insensitive (e.g., `username` ≡ `USERNAME` ≡ `userName`).
|
||||
|
||||
## SELECT Without a FROM Clause
|
||||
|
||||
A `SELECT` statement can retrieve literal values without referencing a table (`FROM` clause).
|
||||
|
||||
```sql
|
||||
SELECT 'Troy' as username;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----------+
|
||||
| username |
|
||||
+----------+
|
||||
| Troy |
|
||||
+----------+
|
||||
```
|
||||
|
||||
## SELECT with Arithmetic Operations
|
||||
|
||||
Apply arithmetic expressions (+, –, *, /) directly within the `SELECT` clause.
|
||||
|
||||
Example: Multiply the `active` column value by 5 and alias the result as `new_active`.
|
||||
|
||||
```sql
|
||||
SELECT username, active*5 as new_active FROM users;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+---------------+------------+
|
||||
| username | new_active |
|
||||
+---------------+------------+
|
||||
| shinobi | 5 |
|
||||
| Java Team Six | 0 |
|
||||
| tony | 5 |
|
||||
+---------------+------------+
|
||||
```
|
||||
|
||||
## Limiting Results
|
||||
|
||||
The `LIMIT` clause restricts the number of rows returned. Retrieve only 1 user:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users LIMIT 1;
|
||||
```
|
||||
|
||||
Output provides a single row:
|
||||
|
||||
```
|
||||
+----+----------+-------+----------+--------+-----------------------+
|
||||
| id | username | about | birthday | active | email |
|
||||
+----+----------+-------+----------+--------+-----------------------+
|
||||
| 1 | shinobi | NULL | NULL | 1 | s@valorantdigital.com |
|
||||
+----+----------+-------+----------+--------+-----------------------+
|
||||
```
|
||||
|
||||
Modify the number following `LIMIT` to retrieve more rows (e.g., `LIMIT 2`).
|
||||
|
||||
## Aggregate Functions (COUNT, MIN, MAX, AVG, SUM)
|
||||
|
||||
Aggregate functions perform calculations across a set of rows.
|
||||
|
||||
* `COUNT`: Returns the number of rows.
|
||||
|
||||
```sql
|
||||
SELECT COUNT(*) FROM users;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----------+
|
||||
| COUNT(*) |
|
||||
+----------+
|
||||
| 3 |
|
||||
+----------+
|
||||
```
|
||||
|
||||
* `MIN`: Returns the smallest value in a column. Get the lowest user ID:
|
||||
|
||||
```sql
|
||||
SELECT MIN(id) FROM users ;
|
||||
```
|
||||
|
||||
This returns `1`.
|
||||
|
||||
* `MAX`: Returns the largest value in a column. Get the highest user ID:
|
||||
|
||||
```sql
|
||||
SELECT MAX(id) FROM users;
|
||||
```
|
||||
|
||||
This returns `3`.
|
||||
|
||||
* `AVG`: Returns the average value of a numeric column. Calculate the average ID:
|
||||
```sql
|
||||
SELECT AVG(id) FROM users;
|
||||
```
|
||||
|
||||
(1 + 2 + 3) / 3 results in `2`.
|
||||
|
||||
* `SUM`: Returns the total sum of values in a numeric column. Sum the IDs:
|
||||
|
||||
```sql
|
||||
SELECT SUM(id) FROM users;
|
||||
```
|
||||
|
||||
1 + 2 + 3 results in `6`.
|
||||
|
||||
## Retrieving Distinct Values
|
||||
|
||||
The `DISTINCT` keyword eliminates duplicate rows from the result set.
|
||||
|
||||
Insert duplicate data for demonstration:
|
||||
|
||||
```sql
|
||||
INSERT INTO users
|
||||
( username, email, active )
|
||||
VALUES
|
||||
('shinobi', 's@valorantdigital.com', true),
|
||||
('Java Team Six', 'd@valorantdigital.com', false),
|
||||
('tony ', 't@valorantdigital.com', true);
|
||||
```
|
||||
|
||||
The `users` table now has 6 entries, with usernames repeated.
|
||||
|
||||
Select all usernames (including duplicates):
|
||||
|
||||
```sql
|
||||
SELECT username FROM users;
|
||||
```
|
||||
|
||||
Output shows repetitions:
|
||||
|
||||
```
|
||||
+---------------+
|
||||
| username |
|
||||
+---------------+
|
||||
| shinobi |
|
||||
| Java Team Six |
|
||||
| tony |
|
||||
| shinobi |
|
||||
| Java Team Six |
|
||||
| tony |
|
||||
+ ---------------+
|
||||
```
|
||||
|
||||
Use `DISTINCT` to show only unique usernames:
|
||||
|
||||
```sql
|
||||
SELECT DISTINCT username FROM users;
|
||||
```
|
||||
|
||||
Output contains only unique entries:
|
||||
|
||||
```
|
||||
+---------------+
|
||||
| username |
|
||||
+---------------+
|
||||
| shinobi |
|
||||
| Java Team Six |
|
||||
| tony |
|
||||
+---------------+
|
||||
```
|
||||
|
||||
The duplicate usernames are removed from the result set.
|
||||
179
landing/docs/SQL-101/006-where.md
Normal file
179
landing/docs/SQL-101/006-where.md
Normal file
@@ -0,0 +1,179 @@
|
||||
# WHERE Clause
|
||||
|
||||
The `WHERE` clause filters query results. It restricts the rows returned based on specified conditions. Position this clause directly after `FROM`.
|
||||
|
||||
```sql
|
||||
SELECT column_name FROM table_name WHERE condition;
|
||||
```
|
||||
|
||||
The `condition` is an expression evaluating to true, false, or unknown. Only rows where the condition evaluates to true are included in the result set.
|
||||
|
||||
## WHERE Clause Example
|
||||
|
||||
Consider a `users` table. To retrieve only active users:
|
||||
|
||||
```sql
|
||||
SELECT DISTINCT username, email, active FROM users WHERE active=true;
|
||||
```
|
||||
|
||||
Output demonstrates results filtered by the `active= true` condition.
|
||||
|
||||
| username | email | active |
|
||||
|----------|-------------------|--------|
|
||||
| shinobi | b@javateamsix.com | 1 |
|
||||
| tony | t@javateamsix.com | 1 |
|
||||
|
||||
Conversely, retrieve inactive users by setting `active=false`:
|
||||
|
||||
```sql
|
||||
SELECT DISTINCT username, email, active FROM users WHERE active=false;
|
||||
```
|
||||
|
||||
Output reflects rows where `active ` is false (0).
|
||||
|
||||
| username | email | active |
|
||||
|-------------|-------------------|--------|
|
||||
| Java Team Six | d@javateamsix.com | 0 |
|
||||
|
||||
To select users with a specific username, like 'shinobi':
|
||||
|
||||
```sql
|
||||
SELECT username, email, active FROM users WHERE username='shinobi';
|
||||
```
|
||||
|
||||
Multiple entries match the username 'shinobi'.
|
||||
|
||||
| username | email | active |
|
||||
|----------|-------------------|--------|
|
||||
| shinobi | b@javateamsix.com | 1 |
|
||||
| shinobi | b@javateamsix.com | 1 |
|
||||
|
||||
## Operators
|
||||
|
||||
Comparison operators define conditions within the `WHERE` clause.
|
||||
|
||||
* `= ` : Equal to
|
||||
* `!=` : Not equal to
|
||||
* `>` : Greater than
|
||||
* `>=` : Greater than or equal to
|
||||
* `<` : Less than
|
||||
* `<=` : Less than or equal to
|
||||
|
||||
## AND Keyword
|
||||
|
||||
Combine multiple conditions with the `AND` keyword. The `AND` operator returns rows where *all* conditions are true.
|
||||
|
||||
Example: Select active users with username 'shinobi'.
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE username='shinobi' AND active=true;
|
||||
```
|
||||
|
||||
Output shows rows matching both the username and active status.
|
||||
|
||||
| id | username | about | birthday | active | email |
|
||||
|----|---------- |-------|----------|--------|-------------------|
|
||||
| 2 | shinobi | NULL | NULL | 1 | b@javateamsix.com |
|
||||
| 5 | shinobi | NULL | NULL | 1 | b@javateamsix.com |
|
||||
|
||||
If no rows satisfy *all* conditions, the result is empty.
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE username='shinobi' AND active=false;
|
||||
```
|
||||
|
||||
-- Output:
|
||||
Empty set.
|
||||
|
||||
## OR Keyword
|
||||
|
||||
Combine conditions with the `OR` keyword. The `OR` operator returns rows where *any* condition is true. Use `OR` to fetch data matching one criterion or another.
|
||||
|
||||
Example: Select users with username 'shinobi' OR where active is false.
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE username='shinobi' OR active=false;
|
||||
```
|
||||
|
||||
Output includes rows where either condition is met.
|
||||
|
||||
| id | username | about | birthday | active | email |
|
||||
|----|-------------|-------|----------|--------|-------------------|
|
||||
| 2 | shinobi | NULL | NULL | 1 | b@javate amsix.com |
|
||||
| 3 | Java Team Six | NULL | NULL | 0 | d@javateamsix.com |
|
||||
| 5 | shinobi | NULL | NULL | 1 | b@javateamsix.com |
|
||||
| 6 | Java Team Six | NULL | NULL | 0 | d@javateamsix.com |
|
||||
|
||||
## LIKE Operator
|
||||
|
||||
The `LIKE` operator performs pattern matching. It is typically used with wildcard characters (`%` for any sequence of characters, `_` for any single character).
|
||||
|
||||
Example: Select users where the username contains the letter 'y'.
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE username LIKE '%y%';
|
||||
```
|
||||
|
||||
Output includes usernames containing 'y'.
|
||||
|
||||
| id | username | about | birthday | active | email |
|
||||
|----|----------|-------|----------|--------|-------------------|
|
||||
| 2 | shinobi | NULL | NULL | 1 | b@javateamsix.com |
|
||||
| 4 | tony | NULL | NULL | 1 | t@javateamsix.com |
|
||||
|
||||
## IN Operator
|
||||
|
||||
The `IN` operator checks if a column's value matches any value in a specified list. This simplifies conditions that would otherwise require multiple `OR` statements.
|
||||
|
||||
Example: Select users with username 'shinobi' or ' Java Team Six'.
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE username IN ('shinobi', 'Java Team Six');
|
||||
```
|
||||
|
||||
Output shows all rows where the username is in the provided list.
|
||||
|
||||
| id | username | about | birthday | active | email |
|
||||
|----|-------------|-------|----------|--------|-------------------|
|
||||
| 2 | shinobi | NULL | NULL | 1 | b@javateamsix.com |
|
||||
| 3 | Java Team Six | NULL | NULL | 0 | d@javateamsix.com |
|
||||
| 5 | shinobi | NULL | NULL | 1 | b@javateamsix .com |
|
||||
| 6 | Java Team Six | NULL | NULL | 0 | d@javateamsix.com |
|
||||
|
||||
## IS Operator
|
||||
|
||||
Use the `IS` operator specifically for checking `NULL` values . The `=` operator cannot be used for this purpose.
|
||||
|
||||
To find rows where `about` is `NULL`:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE about IS NULL;
|
||||
```
|
||||
|
||||
To find rows where `about` is not `NULL`:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE about IS NOT NULL;
|
||||
```
|
||||
|
||||
## BETWEEN Operator
|
||||
|
||||
The `BETWEEN` operator selects values within a defined range. This range is inclusive of the start and end values. Applicable to numbers, text, and dates.
|
||||
|
||||
Example: Select users with an ID between 3 and 6 (inclusive).
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE id BETWEEN 3 AND 6;
|
||||
```
|
||||
|
||||
Output displays rows where `id` is within the specified range.
|
||||
|
||||
| id | username | about | birthday | active | email |
|
||||
|----|-------------|-------|----------|--------|-------------------|
|
||||
| 3 | Java Team Six | NULL | NULL | 0 | d@javateamsix.com |
|
||||
| 5 | shinobi | NULL | NULL | 1 | b@javateamsix.com |
|
||||
| 6 | Java Team Six | NULL | NULL | 0 | d@javateamsix.com |
|
||||
|
||||
## Summary
|
||||
|
||||
The `WHERE` clause and its associated operators are fundamental tools for precisely selecting data subsets, essential for efficient database interaction from Java applications.
|
||||
105
landing/docs/SQL-101/007-order-and-group-by.md
Normal file
105
landing/docs/SQL-101/007-order-and-group-by.md
Normal file
@@ -0,0 +1,105 @@
|
||||
# ORDER By, GROUP By, HAVING
|
||||
|
||||
Applying structure and performance considerations when querying data is paramount. `ORDER BY` provides sorted result sets, essential for presentation and predictable processing. `GROUP BY` aggregates data, enabling summary reporting and analytical operations, often combined with functions like `COUNT`, `MIN `, or `MAX`. The `HAVING` clause refines these aggregations, filtering grouped data based on conditions applied after aggregation.
|
||||
|
||||
## ORDER BY
|
||||
|
||||
Use `ORDER BY` to enforce a specific order on your query results. Specify one or more columns ; multiple columns are comma-separated.
|
||||
|
||||
Consider a simple selection from a `users` table without ordering:
|
||||
|
||||
```sql
|
||||
SELECT id, username FROM users;
|
||||
```
|
||||
|
||||
Typical output without `ORDER BY` relies on internal database storage order (often clustered by primary key), not a guaranteed sequence:
|
||||
|
||||
| id | username |
|
||||
| :-- | :------------ |
|
||||
| 2 | shinobi |
|
||||
| 3 | Java Team Six |
|
||||
| 4 | tony |
|
||||
| 5 | shinobi |
|
||||
| 6 | Java Team Six |
|
||||
| 7 | tony |
|
||||
|
||||
To ensure results are sorted by username alphabetically (ascending):
|
||||
|
||||
```sql
|
||||
SELECT id, username FROM users ORDER BY username;
|
||||
```
|
||||
|
||||
Output ordered by `username`:
|
||||
|
||||
| id | username |
|
||||
| :-- | :------------ |
|
||||
| 2 | shinobi |
|
||||
| 5 | shinobi |
|
||||
| 3 | Java Team Six |
|
||||
| 6 | Java Team Six |
|
||||
| 4 | tony |
|
||||
| 7 | tony |
|
||||
|
||||
`ORDER BY` defaults to ascending (`ASC`). Explicitly specify `DESC` for descending order.
|
||||
|
||||
Sort usernames in reverse alphabetical order:
|
||||
|
||||
```sql
|
||||
SELECT id, username FROM users ORDER BY username DESC;
|
||||
```
|
||||
|
||||
Output in descending username order:
|
||||
|
||||
| id | username |
|
||||
| :-- | :------------ |
|
||||
| 4 | tony |
|
||||
| 7 | tony |
|
||||
| 3 | Java Team Six |
|
||||
| 6 | Java Team Six |
|
||||
| 2 | shinobi |
|
||||
| 5 | shinobi |
|
||||
|
||||
Place `ORDER BY` after the `WHERE` clause when both are used.
|
||||
|
||||
## GROUP BY
|
||||
|
||||
`GROUP BY` aggregates rows with identical values in specified columns into summary rows. This clause is typically used with aggregate functions (`COUNT`, `SUM`, `AVG`, `MIN`, `MAX`) to perform calculations on each group.
|
||||
|
||||
To count users sharing the same username:
|
||||
|
||||
```sql
|
||||
SELECT COUNT(username), username FROM users GROUP BY username;
|
||||
```
|
||||
|
||||
This groups users by identical usernames and counts entries within each group:
|
||||
|
||||
| COUNT(username) | username |
|
||||
|:-------------- | :------------ |
|
||||
| 2 | shinobi |
|
||||
| 2 | Java Team Six |
|
||||
| 2 | tony |
|
||||
|
||||
`GROUP BY` follows `FROM` and `WHERE` clauses.
|
||||
|
||||
## HAVING Clause
|
||||
|
||||
`HAVING` filters groups created by `GROUP BY`. Unlike `WHERE`, which filters individual rows before grouping, `HAVING` filters grouped rows based on conditions, often involving aggregate functions.
|
||||
|
||||
Identify usernames that appear more than once:
|
||||
|
||||
```sql
|
||||
SELECT COUNT (username), username
|
||||
FROM users
|
||||
GROUP BY username
|
||||
HAVING COUNT(username) > 1;
|
||||
```
|
||||
|
||||
This groups users by username, counts occurrences, and then filters to show only groups where the count is greater than 1:
|
||||
|
||||
| COUNT(username) | username |
|
||||
| :-------------- | :------------ |
|
||||
| 2 | shinobi |
|
||||
| 2 | Java Team Six |
|
||||
| 2 | tony |
|
||||
|
||||
`WHERE` filters rows before aggregation; `HAVING` filters groups after aggregation.
|
||||
@@ -6,9 +6,9 @@ The syntax is the following:
|
||||
|
||||
```sql
|
||||
INSERT INTO table_name
|
||||
(column_name_1,column_name_2,column_name_n)
|
||||
(column_name_1,column_name_2,column_name_n)
|
||||
VALUES
|
||||
('value_1', 'value_2', 'value_3');
|
||||
('value_1', 'value_2', 'value_3');
|
||||
```
|
||||
|
||||
You would start with the `INSERT INTO` statement, followed by the table that you want to insert the data into. Then you would specify the list of the columns that you want to insert the data into. Finally, with the `VALUES` statement, you specify the data that you want to insert.
|
||||
@@ -21,9 +21,9 @@ Let's use the table that we created in the last chapter and insert 1 user into o
|
||||
|
||||
```sql
|
||||
INSERT INTO users
|
||||
(username, email, active)
|
||||
(username, email, active)
|
||||
VALUES
|
||||
('greisi', 'g@devdojo.com', true);
|
||||
('greisi', 'g@valorantdigital.com', true);
|
||||
```
|
||||
|
||||
Rundown of the insert statement:
|
||||
@@ -39,24 +39,24 @@ We've briefly covered this in one of the previous chapters, but in some cases, y
|
||||
Let's say that we wanted to create 5 new users, rather than running 5 different queries like this:
|
||||
|
||||
```sql
|
||||
INSERT INTO users (username, email, active) VALUES ('user1', 'user1@devdojo.com', true);
|
||||
INSERT INTO users (username, email, active) VALUES ('user1', 'user2@devdojo.com', true);
|
||||
INSERT INTO users (username, email, active) VALUES ('user1', 'user3@devdojo.com', true);
|
||||
INSERT INTO users (username, email, active) VALUES ('user1', 'user4@devdojo.com', true);
|
||||
INSERT INTO users (username, email, active) VALUES ('user1', 'user5@devdojo.com', true);
|
||||
INSERT INTO users (username, email, active) VALUES ('user1', 'user1@valorantdigital.com', true);
|
||||
INSERT INTO users (username, email, active) VALUES ('user1', 'user2@valorantdigital.com', true);
|
||||
INSERT INTO users (username, email, active) VALUES ('user1', 'user3@valorantdigital.com', true);
|
||||
INSERT INTO users (username, email, active) VALUES ('user1', 'user4@valorantdigital.com', true);
|
||||
INSERT INTO users (username, email, active) VALUES ('user1', 'user5@valorantdigital.com', true);
|
||||
```
|
||||
|
||||
What you could do is to combine this into one `INSERT` statement by providing a list of the values that you want to insert as follows:
|
||||
|
||||
```sql
|
||||
INSERT INTO users
|
||||
(username, email, active)
|
||||
(username, email, active)
|
||||
VALUES
|
||||
('user1', 'user1@devdojo.com', true),
|
||||
('user2', 'user2@devdojo.com', true),
|
||||
('user3', 'user3@devdojo.com', true),
|
||||
('user4', 'user4@devdojo.com', true),
|
||||
('user5', 'user5@devdojo.com', true);
|
||||
('user1', 'user1@valorantdigital.com', true),
|
||||
('user2', 'user2@valorantdigital.com', true),
|
||||
('user3', 'user3@valorantdigital.com', true),
|
||||
('user4', 'user4@valorantdigital.com', true),
|
||||
('user5', 'user5@valorantdigital.com', true);
|
||||
```
|
||||
|
||||
That way, you will add 5 new entries in your `users` table with a single `INSERT` statement. This is going to be much more efficient.
|
||||
@@ -66,7 +66,7 @@ That way, you will add 5 new entries in your `users` table with a single `INSERT
|
||||
In the previous section, we have discussed how we can insert multiple records using a single INSERT query.
|
||||
But sometimes there are cases where we need to insert multiple records which are residing in some other table.
|
||||
|
||||
In this section, we are going to learn how we can insert multiple records at once using a single INSERT query.
|
||||
In this section, we are going to learn how we can insert multiple records at once using a single INSERT query.
|
||||
|
||||
Consider a table, say `prospect_users`, which stores the information of the people who want to become the users of our service, but they are not yet actual users.
|
||||
|
||||
@@ -83,4 +83,4 @@ FROM prospect_users
|
||||
WHERE active=true;
|
||||
```
|
||||
|
||||
Using the above statement, an entry for each active prospect users will be made in our `users` table.
|
||||
Using the above statement, an entry for each active prospect users will be made in our `users` table.
|
||||
92
landing/docs/SQL-101/009-update.md
Normal file
92
landing/docs/SQL-101/009-update.md
Normal file
@@ -0,0 +1,92 @@
|
||||
# UPDATE
|
||||
|
||||
The `UPDATE` statement modifies existing data within a database table. Utilize this for atomic data changes based on specified criteria, ensuring data accuracy in application workflows.
|
||||
|
||||
Update syntax:
|
||||
|
||||
```sql
|
||||
UPDATE users SET username='software shinobi' WHERE id=1;
|
||||
```
|
||||
|
||||
## Syntax breakdown:
|
||||
|
||||
* `UPDATE users`: Identifies the target table (`users`) for the modification.
|
||||
* `SET username='software shinobi'`: Specifies the column (`username`) to update and its new value.
|
||||
* `WHERE id=1`: Filters which rows are affected. Only the row where `id` equals `1` will be updated.
|
||||
|
||||
**Critical Impact:** Omitting the `WHERE` clause updates *every* row in the table. This operation is destructive; confirm intent before executing an `UPDATE` without a filter.
|
||||
|
||||
## Update Multiple Rows
|
||||
|
||||
Consider a `users` table state prior to updates:
|
||||
|
||||
| id | username | about |
|
||||
| :-- | :------------ | :---- |
|
||||
| 2 | shinobi | NULL |
|
||||
| 3 | java team six | NULL |
|
||||
| 4 | tony | NULL |
|
||||
| 5 | shinobi | NULL |
|
||||
| 6 | java team six | NULL |
|
||||
| 7 | tony | NULL |
|
||||
|
||||
Update all rows in the `about` column:
|
||||
|
||||
```sql
|
||||
UPDATE users SET about='404 bio not found';
|
||||
```
|
||||
|
||||
This query affects all six rows:
|
||||
|
||||
```
|
||||
Query OK, 6 rows affected (0 .02 sec)
|
||||
Rows matched: 6 Changed: 6 Warnings: 0
|
||||
```
|
||||
|
||||
`users` table state after updating all rows:
|
||||
|
||||
| id | username | about |
|
||||
| :-- | :------------ | :---------------- |
|
||||
| 2 | shinobi | 404 bio not found |
|
||||
| 3 | java team six | 404 bio not found |
|
||||
| 4 | tony | 404 bio not found |
|
||||
| 5 | shinobi | 404 bio not found |
|
||||
| 6 | java team six | 404 bio not found |
|
||||
| 7 | tony | 404 bio not found |
|
||||
|
||||
## Update Specific Row
|
||||
|
||||
To update only a specific row, use the `WHERE` clause. Update the `about` column for the user with `id` 2:
|
||||
|
||||
```sql
|
||||
UPDATE users SET about ='Hello World :)' WHERE id=2;
|
||||
```
|
||||
|
||||
This targets a single row:
|
||||
|
||||
```
|
||||
Query OK, 1 row affected (0.01 sec)
|
||||
Rows matched: 1 Changed: 1 Warnings: 0
|
||||
```
|
||||
|
||||
`users` table state after updating a single row:
|
||||
|
||||
| id | username | about |
|
||||
| :-- | :------------ | :---------------- |
|
||||
| 2 | shinobi | Hello World :) |
|
||||
| 3 | java team six | 404 bio not found |
|
||||
| 4 | tony | 404 bio not found |
|
||||
| 5 | shinobi | 404 bio not found |
|
||||
| 6 | java team six | 404 bio not found |
|
||||
| 7 | tony | 404 bio not found |
|
||||
|
||||
## Updating Records Using Another Table
|
||||
|
||||
Modify records in one table based on data from another table. This is achieved by joining or listing the tables involved in the `UPDATE` statement and specifying the join condition in the `WHERE` clause.
|
||||
|
||||
Update the `about ` field in the `users` table using corresponding data from the `prospect_users` table where usernames match:
|
||||
|
||||
```sql
|
||||
update users, prospect_users
|
||||
set users.about = prospect_users.about
|
||||
where prospect_users.username = users.username;
|
||||
```
|
||||
50
landing/docs/SQL-101/010-delete.md
Normal file
50
landing/docs/SQL-101/010-delete.md
Normal file
@@ -0,0 +1,50 @@
|
||||
# DELETE
|
||||
|
||||
## Overview
|
||||
|
||||
The `DELETE` statement is fundamental for data management, enabling the removal of rows from a database table. Proper use ensures data integrity and efficiency within your application's data layer.
|
||||
|
||||
## Basic DELETE
|
||||
|
||||
Removes specific rows based on a condition. The `WHERE` clause is critical for precise targeting. Omitting it will affect all rows in the table.
|
||||
|
||||
```sql
|
||||
DELETE FROM users WHERE id=5;
|
||||
```
|
||||
|
||||
A successful operation indicates the number of rows removed.
|
||||
|
||||
```
|
||||
Query OK, 1 row affected (0.01 sec)
|
||||
```
|
||||
|
||||
## Critical Warning
|
||||
|
||||
Executing `DELETE` without a `WHERE` clause removes all data from the specified table.
|
||||
|
||||
```sql
|
||||
DELETE FROM users;
|
||||
```
|
||||
|
||||
Output reflects the total count of rows deleted.
|
||||
|
||||
```
|
||||
Query OK, x row(s) affected (0.047 sec)
|
||||
```
|
||||
|
||||
Unlike operations within a transaction that can be rolled back, standard `DELETE` operations are permanent. Recovery typically requires restoring from a backup.
|
||||
|
||||
## Deleting Based on Related Tables
|
||||
|
||||
Rows can be deleted from one table based on criteria evaluated against another table. This commonly involves using `JOIN` clauses within the `DELETE` statement to link related data. While the `FROM` clause may reference multiple tables, the `DELETE` clause specifies only the table from which rows are removed.
|
||||
|
||||
For instance, to remove users from the `users` table if their corresponding entry in `prospect_users` is marked inactive:
|
||||
|
||||
```sql
|
||||
delete users
|
||||
from users, prospect_users
|
||||
where users.username = prospect_users.username
|
||||
and NOT prospect_users.active;
|
||||
```
|
||||
|
||||
This approach efficiently removes dependent data, maintaining data consistency across related tables.
|
||||
351
landing/docs/SQL-101/011-join.md
Normal file
351
landing/docs/SQL-101/011-join.md
Normal file
@@ -0,0 +1,351 @@
|
||||
# JOINs
|
||||
|
||||
Relational databases store data across multiple tables to enforce structure and minimize redundancy. Effective querying of this distributed data necessitates the use of `JOIN` operations. The `JOIN` clause provides a mechanism to consolidate data from two or more tables into a single, cohesive result set.
|
||||
|
||||
Selecting columns from multiple tables requires specifying the table name followed by a dot (`.`) before the column name (e.g., `table1.column1`, `table2.column2`) in the `SELECT` list, separated by commas.
|
||||
|
||||
This document covers the fundamental `JOIN` types essential for application development:
|
||||
|
||||
* `CROSS JOIN`
|
||||
* `INNER JOIN`
|
||||
* `LEFT JOIN`
|
||||
* `RIGHT JOIN`
|
||||
|
||||
To illustrate these concepts, establish the following database and tables:
|
||||
|
||||
1. Create a database named `demo_joins`:
|
||||
|
||||
```sql
|
||||
CREATE DATABASE demo_joins;
|
||||
```
|
||||
|
||||
2. Switch to the newly created database:
|
||||
|
||||
```sql
|
||||
USE demo_ joins;
|
||||
```
|
||||
|
||||
3. Define a `users` table with `id` and `username` columns:
|
||||
|
||||
```sql
|
||||
CREATE TABLE users
|
||||
(
|
||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
username VARCHAR(2 55) NOT NULL
|
||||
);
|
||||
```
|
||||
|
||||
4. Define a `posts` table with `id`, `user_id`, and `title` columns. The `user_id` column links posts to users, establishing a one-to -many relationship (one user can have many posts).
|
||||
|
||||
```sql
|
||||
CREATE TABLE posts
|
||||
(
|
||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
user_id INT,
|
||||
title VARCHAR(255 ) NOT NULL
|
||||
);
|
||||
```
|
||||
|
||||
Populate these tables with sample data:
|
||||
|
||||
```sql
|
||||
INSERT INTO users
|
||||
( username )
|
||||
VALUES
|
||||
('shinobi'),
|
||||
('javateamsix'),
|
||||
('ton y'),
|
||||
('greisi');
|
||||
```
|
||||
|
||||
```sql
|
||||
INSERT INTO posts
|
||||
( user_id, title )
|
||||
VALUES
|
||||
('1', 'Hello World!'),
|
||||
('2', 'Getting started with SQL '),
|
||||
('3', 'SQL is awesome'),
|
||||
('2', 'MySQL is up!'),
|
||||
('1', 'SQL - structured query language');
|
||||
```
|
||||
|
||||
With the database and data prepared, explore the application of different join types.
|
||||
|
||||
## CROSS JOIN
|
||||
|
||||
A `CROSS JOIN` combines every row from the first table with every row from the second table. This generates a Cartesian product of the two tables, without requiring any join condition.
|
||||
|
||||
Executing an unqualified `CROSS JOIN` on large tables yields a substantial result set, rarely applicable in typical application logic. Its primary use is often conceptual or in specific scenarios requiring a complete pairing of records from two sources.
|
||||
|
||||
Consider joining the `users` and `posts` tables using `CROSS JOIN`:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users CROSS JOIN posts;
|
||||
```
|
||||
|
||||
The output lists every user paired with every post:
|
||||
|
||||
| id | username | id | user_id | title |
|
||||
|:---|:------------|:---|:--------|:-----------------------------|
|
||||
| 4 | greisi | 1 | 1 | Hello World! |
|
||||
| 3 | tony | 1 | 1 | Hello World! |
|
||||
| 2 | javateamsix | 1 | 1 | Hello World! |
|
||||
| 1 | shinobi | 1 | 1 | Hello World! |
|
||||
| 4 | greisi | 2 | 2 | Getting started with SQL |
|
||||
| 3 | tony | 2 | 2 | Getting started with SQL |
|
||||
| 2 | javateamsix | 2 | 2 | Getting started with SQL |
|
||||
| 1 | shinobi | 2 | 2 | Getting started with SQL |
|
||||
| 4 | greisi | 3 | 3 | SQL is awesome |
|
||||
| 3 | tony | 3 | 3 | SQL is awesome |
|
||||
| 2 | javateamsix | 3 | 3 | SQL is awesome |
|
||||
| 1 | shinobi | 3 | 3 | SQL is awesome |
|
||||
| 4 | greisi | 4 | 2 | MySQL is up! |
|
||||
| 3 | tony | 4 | 2 | MySQL is up! |
|
||||
| 2 | javateamsix | 4 | 2 | MySQL is up! |
|
||||
| 1 | shinobi | 4 | 2 | MySQL is up! |
|
||||
| 4 | greisi | 5 | 1 | SQL - structured query language |
|
||||
| 3 | tony | 5 | 1 | SQL - structured query language |
|
||||
| 2 | javateamsix | 5 | 1 | SQL - structured query language |
|
||||
| 1 | shinobi | 5 | 1 | SQL - structured query language |
|
||||
|
||||
While simple in syntax, an unqualified `CROSS JOIN` generates a row count equal to the product of the row counts of the joined tables. For tables with many records, this operation is computationally expensive and yields a large, often unmanageable, result set. Practical join operations typically employ conditions to relate rows between tables.
|
||||
|
||||
In many SQL dialects, including MySQL, `CROSS JOIN` without an `ON` clause is syntactically equivalent to `INNER JOIN` without an `ON` clause.
|
||||
|
||||
## INNER JOIN
|
||||
|
||||
An `INNER JOIN ` retrieves rows from both tables where a specified join condition is met. This is the most common type of join, used to combine records that have matching values in a defined relationship column.
|
||||
|
||||
Although not strictly required by all SQL implementations for `INNER JOIN`, defining relationships using primary and foreign keys is a standard database design practice that facilitates join operations. In this example, `users.id` serves as the primary key and `posts.user_id` as the foreign key referencing the `users` table.
|
||||
|
||||
To retrieve users and their associated posts, matching based on the `user_id` relationship:
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM users
|
||||
INNER JOIN posts
|
||||
ON users.id = posts.user_id;
|
||||
```
|
||||
|
||||
This query operates as follows:
|
||||
* `SELECT * FROM users`: Selects all columns from the `users` table.
|
||||
* `INNER JOIN posts`: Specifies the intention to join with the `posts` table.
|
||||
* `ON users.id = posts.user_id`: Defines the join condition, matching rows where the `id` from `users` equals the `user_id` from `posts `.
|
||||
|
||||
The result set includes only the rows where a user `id` matches a post `user_id`:
|
||||
|
||||
| id | username | id | user_id | title |
|
||||
|:---|:------------|:---|: --------|:-----------------------------|
|
||||
| 1 | shinobi | 1 | 1 | Hello World! |
|
||||
| 2 | javateamsix | 2 | 2 | Getting started with SQL |
|
||||
| 3 | tony | 3 | 3 | SQL is awesome |
|
||||
| 2 | javateamsix | 4 | 2 | MySQL is up! |
|
||||
| 1 | shinobi | 5 | 1 | SQL - structured query language |
|
||||
|
||||
Note that the user 'greisi', who has no associated posts in the `posts` table, is not included in this result. `INNER JOIN` explicitly excludes rows with no matches in the joined table.
|
||||
|
||||
In MySQL, the `INNER` keyword is optional for an `INNER JOIN`, meaning `JOIN` is equivalent.
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM users
|
||||
JOIN posts
|
||||
ON users.id = posts.user_id;
|
||||
```
|
||||
|
||||
Key takeaways for `INNER JOIN`:
|
||||
* Requires a join condition specified by `ON`.
|
||||
* Only returns rows where the condition is met in *both* tables.
|
||||
* Discards rows where no match is found in the joined table, effectively excluding `NULL` matches based on the join key.
|
||||
|
||||
### Types of INNER JOIN
|
||||
|
||||
Relational algebra defines specialized forms of `INNER JOIN` based on the join condition:
|
||||
|
||||
1. **Theta Join ( θ )**: Joins rows from tables based on an arbitrary condition (θ ). The condition can use any comparison operator (`<`, `>`, `=`, `<=`, `>=`, `!=`).
|
||||
Notation: R₁ ⋈<sub>θ</sub> R₂
|
||||
|
||||
Example: Select mobile and laptop models where the mobile price is less than the laptop price.
|
||||
|
||||
```sql
|
||||
SELECT mobile.model, laptop.model
|
||||
FROM mobile, laptop
|
||||
WHERE mobile.price < laptop.price;
|
||||
```
|
||||
|
||||
2. **Equijoin**: A specific type of Theta Join where the join condition exclusively uses the equality operator (`=`).
|
||||
|
||||
Example: Select mobile and laptop models where prices are equal.
|
||||
|
||||
```sql
|
||||
SELECT mobile.model, laptop.model
|
||||
FROM mobile, laptop
|
||||
WHERE mobile.price = laptop.price;
|
||||
```
|
||||
|
||||
3. **Natural Join ( ⋈ )**: Joins tables implicitly based on columns that share the same name and data type in both tables. No `ON` clause is used; the database system automatically finds matching columns. For a Natural Join to be valid, at least one such common column must exist.
|
||||
|
||||
Example: Assume `mobile` and `laptop` tables both have a `price` column.
|
||||
|
||||
```sql
|
||||
SELECT * FROM mobile NATURAL JOIN laptop;
|
||||
```
|
||||
|
||||
This joins `mobile` and `laptop ` on their common `price` column.
|
||||
|
||||
## LEFT JOIN
|
||||
|
||||
A `LEFT JOIN` (or `LEFT OUTER JOIN`) returns all rows from the *left* table (the first table mentioned) and the matched rows from the *right* table. If a row from the left table has no matching row in the right table according to the join condition, columns from the right table in the result set will contain `NULL` values.
|
||||
|
||||
This is crucial for retrieving all records from one table, even if corresponding entries do not exist in another. For example, to list all users and any posts they might have, including users with no posts:
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM users
|
||||
LEFT JOIN posts
|
||||
ON users.id = posts.user_id;
|
||||
```
|
||||
|
||||
The output includes all users, and for those without matching posts, the post-related columns are `NULL`.
|
||||
|
||||
| id | username | id | user_ id | title |
|
||||
|:---|:------------|:-----|:--------|:-------------------------------|
|
||||
| 1 | shinobi | 1 | 1 | Hello World! |
|
||||
| 2 | javateamsix | 2 | 2 | Getting started with SQL |
|
||||
| 3 | tony | 3 | 3 | SQL is awesome |
|
||||
| 2 | jav ateamsix | 4 | 2 | MySQL is up! |
|
||||
| 1 | shinobi | 5 | 1 | SQL - structured query language|
|
||||
| 4 | greisi | NULL | NULL | NULL |
|
||||
|
||||
The user 'greisi' appears in the result set because they are in the left table (`users`), even though they have no matching record in the right table (`posts`).
|
||||
|
||||
## RIGHT JOIN
|
||||
|
||||
A `RIGHT JOIN` (or `RIGHT OUTER JOIN`) is the inverse of `LEFT JOIN`. It returns all rows from the *right* table and the matched rows from the *left* table. If a row from the right table has no match in the left table based on the join condition, columns from the left table in the result set will be `NULL`.
|
||||
|
||||
Consider a post entry without a corresponding user. Add such a post:
|
||||
|
||||
```sql
|
||||
INSERT INTO posts
|
||||
( user_id, title )
|
||||
VALUES
|
||||
('123', 'No user post!');
|
||||
```
|
||||
|
||||
User ID `123` does not exist in the `users ` table.
|
||||
|
||||
A `LEFT JOIN` would exclude this 'No user post!' entry. A `RIGHT JOIN`, however, will include it, as `posts` is now the right table:
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM users
|
||||
RIGHT JOIN posts
|
||||
ON users.id = posts.user_id;
|
||||
```
|
||||
|
||||
The output includes all posts, even the one without a matching user. The 'greisi' user, lacking posts, is not present.
|
||||
|
||||
| id | username | id | user_id | title |
|
||||
|:-----|:------------|:---|:--------|:-------------------------------|
|
||||
| 1 | shinobi | 1 | 1 | Hello World! |
|
||||
| 2 | javateamsix | 2 | 2 | Getting started with SQL |
|
||||
| 3 | tony | 3 | 3 | SQL is awesome |
|
||||
| 2 | javateamsix | 4 | 2 | MySQL is up! |
|
||||
| 1 | shinobi | 5 | 1 | SQL - structured query language|
|
||||
| NULL | NULL | 6 | 123 | No user post! |
|
||||
|
||||
Joins can be combined with `WHERE` clauses to filter results *after* the join operation. For example, restricting the previous `RIGHT JOIN` results to only show data related to username 'shinobi':
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM users
|
||||
RIGHT JOIN posts
|
||||
ON users.id = posts.user_id
|
||||
WHERE username = 'shinobi';
|
||||
```
|
||||
|
||||
Output shows only the rows where the `username` is 'shinobi' and a match was found in the join. The row for 'No user post!' is excluded because its `username` is `NULL`, failing the `WHERE` condition.
|
||||
|
||||
| id | username | id | user_id | title |
|
||||
|:---|:---------|:---|:--------|:-------------------------------|
|
||||
| 1 | shinobi | 1 | 1 | Hello World ! |
|
||||
| 1 | shinobi | 5 | 1 | SQL - structured query language|
|
||||
|
||||
## The Impact of Conditions: JOIN vs. WHERE
|
||||
|
||||
The placement of conditions significantly alters query results, particularly in `LEFT` and `RIGHT` joins. Conditions in the `ON` clause filter data *during* the join, while conditions in the `WHERE` clause filter data *after* the join is complete.
|
||||
|
||||
Consider retrieving posts with "SQL" in their title, along with user data:
|
||||
|
||||
Placing the condition in the `WHERE` clause:
|
||||
|
||||
```sql
|
||||
SELECT users.*, posts.*
|
||||
FROM users
|
||||
LEFT JOIN posts
|
||||
ON posts.user_id = users .id
|
||||
WHERE posts.title LIKE '%SQL%';
|
||||
```
|
||||
|
||||
This performs the `LEFT JOIN` first (including all users, even those without matching posts), and then filters the result set to include only rows where the `posts.title` contains "SQL ". Users without posts will not appear if they do not meet the `WHERE` clause criteria (which is impossible since `posts.title` would be NULL).
|
||||
|
||||
| id | username | id | user_id | title |
|
||||
| :---|:------------|:---|:--------|:-----------------------------|
|
||||
| 2 | javateamsix | 2 | 2 | Getting started with SQL |
|
||||
| 3 | tony | 3 | 3 | SQL is awesome |
|
||||
| 2 | javateamsix | 4 | 2 | MySQL is up! |
|
||||
| 1 | shinobi | 5 | 1 | SQL - structured query language |
|
||||
|
||||
Shifting the condition to the `ON` clause:
|
||||
|
||||
```sql
|
||||
SELECT users.*, posts.*
|
||||
FROM users
|
||||
LEFT JOIN posts
|
||||
ON posts.user_id = users.id
|
||||
AND posts.title LIKE '%SQL%';
|
||||
```
|
||||
|
||||
This query incorporates the `posts.title` condition into the join process itself. The `LEFT JOIN` proceeds, including all users. However, for the *right* side (posts), it only matches posts where the `user_id` corresponds *AND* the `title` contains "SQL". If a user has posts but none contain "SQL", those post columns will be `NULL` in the result for that user.
|
||||
|
||||
| id | username | id | user_id | title |
|
||||
|:---|:------------|:-----|:--------|:-------------------------------|
|
||||
| 1 | shinobi | 5 | 1 | SQL - structured query language|
|
||||
| 2 | javateamsix | 4 | 2 | MySQL is up! |
|
||||
| 2 | javateamsix | 2 | 2 | Getting started with SQL |
|
||||
| 3 | tony | 3 | 3 | SQL is awesome |
|
||||
| 4 | greisi | NULL | NULL | NULL |
|
||||
|
||||
Notice the difference: the `ON` clause condition includes user 'greisi' (with NULL post data) because the `LEFT JOIN` guarantees all rows from the left table (`users`) are included. The post records for other users only appear if they match the `ON` condition.
|
||||
|
||||
## Equivalence of RIGHT and LEFT JOINs
|
||||
|
||||
`RIGHT JOIN` and `LEFT JOIN` operations are functionally interchangeable. Any query written with a `RIGHT JOIN` can be rewritten as a `LEFT JOIN` by simply swapping the order of the tables in the `FROM` clause.
|
||||
|
||||
This `LEFT JOIN`:
|
||||
|
||||
```sql
|
||||
SELECT users.*, posts.*
|
||||
FROM posts
|
||||
LEFT JOIN users
|
||||
ON posts.user_id = users .id;
|
||||
```
|
||||
|
||||
Is equivalent to this `RIGHT JOIN`:
|
||||
|
||||
```sql
|
||||
SELECT users.*, posts.*
|
||||
FROM users
|
||||
RIGHT JOIN posts
|
||||
ON posts.user_id = users.id;
|
||||
```
|
||||
|
||||
Both queries produce the same result set, illustrating that the direction of the "outer" join is determined by the order of the tables and the `LEFT` or `RIGHT` keyword.
|
||||
|
||||
## Conclusion
|
||||
|
||||
Mastering `JOIN` operations is foundational for effective data retrieval and manipulation in relational databases. Each join type serves a distinct purpose in combining data based on defined relationships between tables. Understanding their behavior, particularly concerning matching records and the treatment of non-matching rows (`NULL ` values), is critical.
|
||||
|
||||
Experimentation is key to solidifying comprehension. Practice writing queries with each `JOIN` type, varying the join conditions and observing the resulting data sets.
|
||||
|
||||
For comprehensive technical specifications, refer to the official database documentation for your specific SQL dialect.
|
||||
151
landing/docs/SQL-101/012-sql-commnad-categories.md
Normal file
151
landing/docs/SQL-101/012-sql-commnad-categories.md
Normal file
@@ -0,0 +1,151 @@
|
||||
# DDL, DQL, DML, DCL, TCL
|
||||
|
||||
SQL provides the standard interface for interacting with databases. Understanding its command categories is fundamental for building applications that manage and retrieve data efficiently. This document outlines the core SQL command types and their practical use cases for Java developers.
|
||||
|
||||
## Data Definition Language (DDL )
|
||||
|
||||
DDL commands manage database schema structure. They define, modify, or drop database objects. Developers typically use DDL during application setup, migration scripts, or when evolving the data model.
|
||||
|
||||
### DDL Commands:
|
||||
|
||||
* `CREATE`: Constructs a new database, table, index, view, stored procedure, or trigger. Defines the schema for persistent data storage.
|
||||
|
||||
```sql
|
||||
CREATE TABLE Persons (
|
||||
PersonID int,
|
||||
LastName varchar(25 5),
|
||||
FirstName varchar(255),
|
||||
Address varchar(255),
|
||||
City varchar(255)
|
||||
);
|
||||
```
|
||||
* `DROP`: Deletes objects from the database. Irreversible and should be used with caution, particularly in production environments.
|
||||
|
||||
```sql
|
||||
DROP TABLE table_name;
|
||||
```
|
||||
* `ALTER`: Modifies the structure of existing database objects, such as adding, deleting, or modifying columns in a table. Essential for schema evolution.
|
||||
|
||||
```sql
|
||||
ALTER TABLE Persons
|
||||
ADD Age int;
|
||||
```
|
||||
* `TRUNCATE`: Removes all rows from a table. This operation is significantly faster than `DELETE` for clearing an entire table because it logs fewer operations and resets the table's identity column.
|
||||
|
||||
```sql
|
||||
TRUNCATE TABLE Persons;
|
||||
```
|
||||
* `COMMENT`: Adds descriptive text to the data dictionary. Useful for documenting schema elements.
|
||||
|
||||
```sql
|
||||
-- Example of an inline comment
|
||||
SELECT * FROM Persons;
|
||||
```
|
||||
* `RENAME`: Changes the name of a database object.
|
||||
|
||||
```sql
|
||||
ALTER TABLE Persons
|
||||
RENAME COLUMN Age TO Year;
|
||||
```
|
||||
|
||||
## Data Query Language (DQL)
|
||||
|
||||
DQL commands retrieve data from the database based on specified criteria. The `SELECT` statement is the primary command. Understanding DQL is critical for fetching the necessary information to populate application interfaces or perform backend logic.
|
||||
|
||||
### DQL Command:
|
||||
|
||||
* `SELECT`: Fetches data from one or more tables. The foundation for most read operations in applications.
|
||||
|
||||
```sql
|
||||
SELECT * FROM table_name;
|
||||
```
|
||||
|
||||
Example Result Set:
|
||||
|
||||
```
|
||||
+--------+--------------+------------+--------+---------+
|
||||
| emp_id | emp_name | hire_date | salary | dept_id |
|
||||
+--------+--------------+------------+--------+---------+
|
||||
| 1 | Ethan Hunt | 2001-05-01 | 5000 | 4 |
|
||||
| 2 | Tony Montana | 2002-07-15 | 6500 | 1 |
|
||||
| 3 | Sarah Connor | 2005 -10-18 | 8000 | 5 |
|
||||
| 4 | Rick Deckard | 2007-01-03 | 7200 | 3 |
|
||||
| 5 | Martin Blank | 2008-06-24 | 5600 | NULL |
|
||||
+--------+--------------+------------+--------+---------+
|
||||
```
|
||||
|
||||
## Data Manipulation Language (DML)
|
||||
|
||||
DML commands manage the data *within* schema objects. They perform insert, update, and delete operations. DML operations form the core of application logic interacting with the database's contents.
|
||||
|
||||
### DML Commands :
|
||||
|
||||
* `INSERT`: Adds new rows of data into a table. Essential for persisting new records created by the application.
|
||||
|
||||
```sql
|
||||
INSERT INTO Customers
|
||||
(CustomerName, ContactName, Address, City, PostalCode, Country )
|
||||
VALUES
|
||||
('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
|
||||
```
|
||||
* `UPDATE`: Modifies existing data within a table. Used to reflect changes to records from the application.
|
||||
|
||||
```sql
|
||||
UPDATE Customers
|
||||
SET ContactName='Alfred Schmidt', City='Frankfurt'
|
||||
WHERE CustomerID = 1;
|
||||
```
|
||||
* `DELETE`: Removes one or more rows from a table. Use `WHERE` clauses carefully to avoid unintended data loss.
|
||||
|
||||
```sql
|
||||
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
|
||||
``` * `LOCK`: Controls concurrent access to tables. Important for managing transactional integrity in high-concurrency applications.
|
||||
|
||||
```sql
|
||||
LOCK TABLES table_name [READ | WRITE]
|
||||
UNLOCK TABLES;
|
||||
```
|
||||
* `CALL `: Executes a stored procedure or function. Useful for encapsulating complex database logic.
|
||||
|
||||
```sql
|
||||
-- Example Stored Procedure Definition (database specific syntax may vary)
|
||||
CREATE PROCEDURE procedure_name
|
||||
AS sql_statement
|
||||
GO ;
|
||||
|
||||
-- Example Execution
|
||||
EXEC procedure_name;
|
||||
```
|
||||
* `EXPLAIN PLAN`: (Database specific, e.g., Oracle, PostgreSQL) Provides details on how the database will execute a query. In valuable for performance tuning.
|
||||
|
||||
## Data Control Language (DCL)
|
||||
|
||||
DCL commands manage database security by defining privileges and permissions for users. `GRANT` and `REVOKE` control user access to database objects and capabilities.
|
||||
|
||||
### DCL Commands :
|
||||
|
||||
* `GRANT`: Assigns specific access privileges on database objects to users or roles.
|
||||
|
||||
```sql
|
||||
-- Grant SELECT privilege on the Persons table to a user
|
||||
GRANT SELECT ON Persons TO 'username';
|
||||
```
|
||||
* `REVOKE`: Removes previously granted access privileges.
|
||||
|
||||
```sql
|
||||
-- Revoke the SELECT privilege on the Persons table from a user
|
||||
REVOKE SELECT ON Persons FROM 'username';
|
||||
```
|
||||
|
||||
## Transaction Control Language (TCL)
|
||||
|
||||
TCL commands manage transactions within a database. A transaction is a sequence of operations performed as a single logical unit of work. TCL ensures data integrity by guaranteeing that transactions are atomic, consistent, isolated, and durable (ACID).
|
||||
|
||||
### TCL Commands:
|
||||
|
||||
* `COMMIT`: Makes all changes performed in the current transaction permanent. Essential after a series of successful DML operations.
|
||||
* `ROLLBACK`: Undoes all changes performed in the current transaction since the last `COMMIT` or `SAVEPOINT`. Used to revert changes if an error occurs or business logic dictates.
|
||||
* `SAVEPOINT`: Sets a marker within a transaction. Allows rolling back to a specific point without rolling back the entire transaction.
|
||||
* `SET TRANSACTION`: Configures characteristics of the current transaction, such as isolation level.
|
||||
|
||||
These command categories provide the fundamental building blocks for database interaction. Mastery of DDL, DQL, DML, DCL, and TCL empowers developers to build robust, efficient, and secure database-driven applications.
|
||||
143
landing/docs/SQL-101/013-sub-queries.md
Normal file
143
landing/docs/SQL-101/013-sub-queries.md
Normal file
@@ -0,0 +1,143 @@
|
||||
# Sub Queries
|
||||
|
||||
A subquery is a SQL query nested within a larger query. This powerful technique allows you to build complex data operations, treating the output of the inner query as input for the outer one.
|
||||
|
||||
Subqueries are crucial for filtering, aggregation, and data manipulation tasks that simple queries cannot address effectively.
|
||||
|
||||
Subqueries can appear in several key clauses:
|
||||
|
||||
- SELECT clause
|
||||
- FROM clause
|
||||
- WHERE clause
|
||||
- HAVING clause
|
||||
|
||||
The inner query executes first, its results informing the execution of the parent query. This execution order is fundamental to understanding subquery behavior.
|
||||
|
||||
Employ subqueries within SELECT, INSERT, UPDATE, or DELETE statements to:
|
||||
|
||||
- Compare an expression against the result of another query.
|
||||
- Ascertain if an expression is present within a query's results.
|
||||
- Verify if a query returns any rows.
|
||||
|
||||
## Subqueries with SELECT
|
||||
|
||||
Subqueries frequently appear in the `WHERE` clause of `SELECT` statements to filter data based on criteria derived from another query's result set.
|
||||
|
||||
Consider the following `CUSTOMERS` table:
|
||||
|
||||
| ID | NAME | AGE | ADDRESS | SALARY |
|
||||
|-----|----------|-----|-----------|-----------|
|
||||
| 1 | Ramesh | 35 | Ahmedabad | 2000.0 0 |
|
||||
| 2 | Khilan | 25 | Delhi | 1500.00 |
|
||||
| 3 | Kaushik | 23 | Kota | 2000.00 |
|
||||
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
|
||||
| 5 | Hardik | 27 | Bhopal | 8500.00 |
|
||||
| 6 | Komal | 22 | MP | 4500.00 |
|
||||
| 7 | Muffy | 24 | Indore | 10000.00 |
|
||||
|
||||
Example: Retrieve customers with a salary greater than 4500.
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM CUSTOMERS
|
||||
WHERE ID IN (
|
||||
SELECT ID
|
||||
FROM CUSTOMERS
|
||||
WHERE SALARY > 4500
|
||||
);
|
||||
```
|
||||
|
||||
This query first identifies the `ID`s of customers earning more than 4500. The outer query then selects all information for customers whose `ID` is in that list.
|
||||
|
||||
Result:
|
||||
|
||||
| ID | NAME | AGE | ADDRESS | SALARY |
|
||||
|-----|----------|-----|---------|---------- |
|
||||
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
|
||||
| 5 | Hardik | 27 | Bhopal | 8500 .00 |
|
||||
| 7 | Muffy | 24 | Indore | 10000.00 |
|
||||
|
||||
## Subqueries with UPDATE
|
||||
|
||||
Subqueries can update single or multiple columns based on criteria determined by the subquery's result.
|
||||
|
||||
Assuming a `CUSTOMERS_BKP` table exists as a backup. The following example updates the `SALARY` in the `CUSTOMERS` table by multiplying it by 0 .25 for customers whose `AGE` is 27 or greater, based on the `CUSTOMERS_BKP` table.
|
||||
|
||||
```sql
|
||||
UPDATE CUSTOMERS
|
||||
SET SALARY = SALARY * 0.25
|
||||
WHERE AGE IN (
|
||||
SELECT AGE
|
||||
FROM CUSTOMERS_BKP
|
||||
WHERE AGE >= 27
|
||||
);
|
||||
```
|
||||
|
||||
This statement identifies ages from `CUSTOMERS_BKP` that are 27 or greater. The outer `UPDATE` then applies the salary adjustment to rows in `CUSTOMERS` with matching ages.
|
||||
|
||||
Initial `CUSTOMERS` table:
|
||||
|
||||
| ID | NAME | AGE | ADDRESS | SALARY |
|
||||
|-----|----------|-----|-----------|----------- |
|
||||
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
|
||||
| 2 | Khilan | 25 | Delhi | 15 00.00 |
|
||||
| 3 | Kaushik | 23 | Kota | 2000.00 |
|
||||
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
|
||||
| 5 | Hardik | 27 | Bhopal | 8500.00 |
|
||||
| 6 | Komal | 22 | MP | 4500.00 |
|
||||
| 7 | Muffy | 24 | Indore | 10000. 00 |
|
||||
|
||||
After executing the `UPDATE`, the `CUSTOMERS` table will contain:
|
||||
|
||||
| ID | NAME | AGE | ADDRESS | SALARY |
|
||||
|-----|----------|-----|-----------|-----------|
|
||||
| 1 | Ramesh | 35 | Ahmedabad | 500.00 |
|
||||
| 2 | Khilan | 25 | Delhi | 1500.00 |
|
||||
| 3 | Kaushik | 23 | Kota | 2000.00 |
|
||||
| 4 | Chaitali | 25 | Mumbai | 65 00.00 |
|
||||
| 5 | Hardik | 27 | Bhopal | 2125.00 |
|
||||
| 6 | Komal | 22 | MP | 4500.00 |
|
||||
| 7 | Muffy | 24 | Indore | 10000.00 |
|
||||
|
||||
Note: Ramesh (Age 35) and Hardik (Age 27) are affected as their age is >= 27.
|
||||
|
||||
## Subqueries with DELETE
|
||||
|
||||
Subqueries enable deleting rows based on conditions derived from the subquery's output .
|
||||
|
||||
Assuming a `CUSTOMERS_BKP` table is available. The following example deletes records from the `CUSTOMERS` table for customers whose `AGE` is 27 or greater, as found in the `CUSTOMERS_BKP` table.
|
||||
|
||||
```sql
|
||||
DELETE FROM CUSTOMERS
|
||||
WHERE AGE IN (
|
||||
SELECT AGE
|
||||
FROM CUSTOMERS_BKP
|
||||
WHERE AGE >= 27
|
||||
);
|
||||
```
|
||||
|
||||
This query identifies ages from `CUSTOMERS_BKP` that meet the condition. The outer `DELETE` then removes rows from `CUSTOMERS` with those corresponding ages.
|
||||
|
||||
Initial `CUSTOMERS` table:
|
||||
|
||||
| ID | NAME | AGE | ADDRESS | SALARY |
|
||||
|-----|----------|-----|-----------|-----------|
|
||||
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
|
||||
| 2 | Khilan | 25 | Delhi | 1500.00 |
|
||||
| 3 | Kaushik | 23 | Kota | 2 000.00 |
|
||||
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
|
||||
| 5 | Hardik | 27 | Bhopal | 8500.00 |
|
||||
| 6 | Komal | 22 | MP | 4500.00 |
|
||||
| 7 | Muffy | 24 | Indore | 10000.00 |
|
||||
|
||||
After executing the `DELETE`, the `CUSTOMERS` table will contain:
|
||||
|
||||
| ID | NAME | AGE | ADDRESS | SALARY |
|
||||
|-----|----------|-----|---------|----------|
|
||||
| 2 | Khilan | 25 | Delhi | 1500.00 |
|
||||
| 3 | Kaushik | 23 | Kota | 2000.00 |
|
||||
| 4 | Chaitali | 25 | Mumbai | 6500.0 0 |
|
||||
| 6 | Komal | 22 | MP | 4500.00 |
|
||||
| 7 | Muffy | 24 | Indore | 10000.00 |
|
||||
|
||||
Rows with Age 35 (Ramesh) and 27 (Hardik) are removed.
|
||||
102
landing/docs/SQL-101/014-unions.md
Normal file
102
landing/docs/SQL-101/014-unions.md
Normal file
@@ -0,0 +1,102 @@
|
||||
# UNION and UNION ALL
|
||||
|
||||
The `UNION` clause combines results from multiple `SELECT` statements. It automatically eliminates duplicate rows, delivering a distinct dataset crucial for consolidated reporting or unique data identification across different query outputs.
|
||||
|
||||
For effective use, each `SELECT ` statement within a `UNION` operation **must**:
|
||||
|
||||
* Select the identical count of columns.
|
||||
* Include the same number of column expressions.
|
||||
* Maintain the same data type order across corresponding columns.
|
||||
|
||||
Column lengths do not need to match .
|
||||
|
||||
## The UNION Clause
|
||||
|
||||
Consider the following structures:
|
||||
|
||||
The `customers` table:
|
||||
|
||||
| id | name | age | address | salary |
|
||||
|----|----------|-----|-----------|----------|
|
||||
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
|
||||
| 2 | Khilan | 25 | Delhi | 1500.00 |
|
||||
| 3 | kaushik | 23 | Kota | 2000.00 |
|
||||
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
|
||||
| 5 | Hardik | 27 | Bhopal | 8500.00 |
|
||||
| 6 | Komal | 22 | MP | 4500.00 |
|
||||
| 7 | Muffy | 24 | Indore | 10000.00 |
|
||||
|
||||
The `orders` table:
|
||||
|
||||
| oid | date | customer_id | amount |
|
||||
|-----|---------------------|-------------|--------|
|
||||
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
|
||||
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
|
||||
| 101 | 2009-11-2 0 00:00:00 | 2 | 1560 |
|
||||
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
|
||||
|
||||
Combining results with `UNION`:
|
||||
|
||||
```sql
|
||||
SELECT id, name, amount, date
|
||||
FROM customers
|
||||
LEFT JOIN orders
|
||||
ON customers.id = orders.customer_id
|
||||
UNION
|
||||
SELECT id, name, amount, date
|
||||
FROM customers
|
||||
RIGHT JOIN orders
|
||||
ON customers.id = orders.customer_id;
|
||||
```
|
||||
|
||||
Resulting data set:
|
||||
|
||||
| id | name | amount | date |
|
||||
|------|----------|--------|---------------------|
|
||||
| 1 | Ramesh | NULL | NULL |
|
||||
| 2 | Khilan | 1560 | 2009- 11-20 00:00:00 |
|
||||
| 3 | kaushik | 3000 | 2009-10-08 00:00 :00 |
|
||||
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
|
||||
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
|
||||
| 5 | Hardik | NULL | NULL |
|
||||
| 6 | Komal | NULL | NULL |
|
||||
| 7 | Muffy | NULL | NULL |
|
||||
|
||||
## The UNION ALL Clause
|
||||
|
||||
The `UNION ALL` operator concatenates the result sets of two or more `SELECT ` statements. It explicitly includes all rows, including duplicates, which is critical when the frequency of specific data points is important.
|
||||
|
||||
The requirements for column count, expressions, and data types mirroring across `SELECT` statements remain identical to `UNION`.
|
||||
|
||||
Using the same `customers` and `orders` tables:
|
||||
|
||||
Combining results with `UNION ALL`:
|
||||
|
||||
```sql
|
||||
SELECT id, name, amount, date
|
||||
FROM customers
|
||||
LEFT JOIN orders
|
||||
ON customers.id = orders.customer _id
|
||||
UNION ALL
|
||||
SELECT id, name, amount, date
|
||||
FROM customers
|
||||
RIGHT JOIN orders
|
||||
ON customers.id = orders.customer_id;
|
||||
```
|
||||
|
||||
Resulting data set:
|
||||
|
||||
| id | name | amount | date |
|
||||
|------|----------|--------|---------------------|
|
||||
| 1 | Ramesh | NULL | NULL |
|
||||
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
|
||||
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
|
||||
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
|
||||
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
|
||||
| 5 | Hardik | NULL | NULL |
|
||||
| 6 | Komal | NULL | NULL |
|
||||
| 7 | Muffy | NULL | NULL |
|
||||
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
|
||||
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
|
||||
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
|
||||
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
|
||||
50
landing/docs/SQL-101/015-Keys-in-a-Relational Database.md
Normal file
50
landing/docs/SQL-101/015-Keys-in-a-Relational Database.md
Normal file
@@ -0,0 +1,50 @@
|
||||
# Table Keys
|
||||
|
||||
Robust application development hinges on a solid understanding of database fundamentals. Keys are the bedrock of relational database integrity and efficient data access. Comprehending their function and purpose is non-negotiable for Java Team Six developers building resilient systems. These constructs prevent data inconsistency and enable precise data manipulation.
|
||||
|
||||
## Types of Relational Keys
|
||||
|
||||
Database relations (tables) must uniquely identify individual records (tuples) to prevent duplication and ensure data accuracy. Relational keys provide the mechanisms for this critical requirement.
|
||||
|
||||
## Super Keys
|
||||
|
||||
A Super Key is any combination of one or more attributes that uniquely identifies a tuple within a relation. It's a superset of uniqueness; adding more attributes to a Super Key retains its Super Key property. Think of it as any column or set of columns guaranteeing you hit only one row.
|
||||
|
||||
For example, in a `Customer` table, `CustomerID` alone might be unique. The combination `{CustomerID, CustomerName}` is also a Super Key, even if `CustomerName` isn't unique by itself. It simply over-specifies the identification.
|
||||
|
||||
## Candidate Keys
|
||||
|
||||
A Candidate Key is a *minimal* Super Key. This means it uniquely identifies tuples, but no subset of its attributes can achieve that same unique identification. These are the viable choices for primary identifiers of records.
|
||||
|
||||
For the `Customer` table, potential Candidate Keys might be:
|
||||
* `CustomerID`
|
||||
* `{CustomerName, CustomerAddress}` (assuming this combination is unique)
|
||||
* `{CustomerName, CustomerContactNumber}` (assuming this combination is unique)
|
||||
|
||||
Each of these sets uniquely identifies a customer, and removing any attribute from the set would break that uniqueness.
|
||||
|
||||
## Primary Key
|
||||
|
||||
From the set of Candidate Keys, one is designated as the Primary Key. This is the *official*, chosen identifier for records in that relation. There can be only one Primary Key per table.
|
||||
|
||||
The Primary Key enforces two critical constraints for application data integrity:
|
||||
1. **Uniqueness:** No two records can have the same Primary Key value.
|
||||
2. **NOT NULL:** The Primary Key column(s) cannot contain null values.
|
||||
|
||||
Selecting the Primary Key is a design decision. Opt for a key that is stable and unlikely to change, such as a generated ID (`CustomerID`) rather than mutable data like a name or address. This stability is crucial for maintaining reliable references from other tables.
|
||||
|
||||
## Alternate Keys
|
||||
|
||||
Alternate Keys are simply the Candidate Keys that were *not* chosen as the Primary Key. They still possess the unique identification property but serve as secondary unique identifiers if needed.
|
||||
|
||||
Based on the previous example, if `CustomerID` is chosen as the Primary Key, then `{CustomerName, CustomerAddress}` and `{CustomerName, CustomerContactNumber}` would be Alternate Keys.
|
||||
|
||||
## Foreign Key
|
||||
|
||||
A Foreign Key establishes a link between two tables. It is a column or set of columns in one table (`referencing table`) that references the Primary Key (or occasionally a Unique Key) in another table (`referenced table `).
|
||||
|
||||
This constraint is fundamental to enforcing referential integrity. It guarantees that values in the Foreign Key column(s) of the referencing table must exist as values in the referenced table 's Primary Key column(s). This prevents orphaned records and ensures relationships between data are valid.
|
||||
|
||||
A table can have multiple Foreign Keys, enabling complex relationships between different entities in the database.
|
||||
|
||||
For instance, in an `Orders` table (`referencing table`) with columns `OrderID`, `CustomerID`, `OrderDate`, the `CustomerID` column would be a Foreign Key referencing the `CustomerID` Primary Key in the `Customer` table (`referenced table`). This ensures every order record is linked to a valid customer record.
|
||||
16
landing/docs/SQL-101/016-Logical-operator-keywords.md
Normal file
16
landing/docs/SQL-101/016-Logical-operator-keywords.md
Normal file
@@ -0,0 +1,16 @@
|
||||
# SQL Logical Operators
|
||||
|
||||
SQL Logical Operators evaluate boolean conditions to filter data, primarily used in `WHERE` and `HAVING` clauses. They are fundamental for constructing precise data retrieval queries and controlling program flow based on dataset characteristics. Understanding their behavior is essential for writing effective and performant database interactions.
|
||||
|
||||
## Logical Operator Keywords
|
||||
|
||||
| Logical Operator | Explanation |
|
||||
| :--------------- | :----------------------------------------------------------------- |
|
||||
| ALL | Returns TRUE if all comparisons in a subquery are TRUE. |
|
||||
| ANY | Returns TRUE if any comparison in a subquery is TRUE. |
|
||||
| AND | Returns TRUE if both boolean expressions are TRUE. |
|
||||
| EXISTS | Evaluates to TRUE if the subquery returns one or more rows. |
|
||||
| IN | Checks if a value matches any value in a list or subquery. |
|
||||
| BETWEEN | Tests if a value is within a given range (inclusive). |
|
||||
| NOT | Negates a boolean expression. |
|
||||
| OR | Returns TRUE if either boolean expression is TRUE. |
|
||||
219
landing/docs/SQL-101/017-having-clause_aggregate-functions.md
Normal file
219
landing/docs/SQL-101/017-having-clause_aggregate-functions.md
Normal file
@@ -0,0 +1,219 @@
|
||||
# HAVING and Aggregate Functions
|
||||
|
||||
This document details the strategic application of the SQL `HAVING` clause and core aggregate functions. Mastery enables developers to write high-impact queries that efficiently process and filter grouped data, a critical requirement for performant applications.
|
||||
|
||||
Unlike the `WHERE` clause, which filters individual rows * before* grouping and aggregation, `HAVING` operates on grouped data *after* these operations have occurred. This distinction is fundamental for filtering based on aggregate results.
|
||||
|
||||
## Syntax
|
||||
|
||||
The `HAVING` clause is applied after `GROUP BY` and before `ORDER BY`.
|
||||
|
||||
```sql
|
||||
SELECT column_name(s)
|
||||
FROM table_name
|
||||
WHERE condition -- Filters individual rows (optional)
|
||||
GROUP BY column_name(s) -- Groups rows with identical values
|
||||
HAVING condition -- Filters groups based on aggregate results
|
||||
ORDER BY column_name(s); -- Sorts the final result set (optional)
|
||||
```
|
||||
|
||||
The `HAVING` condition typically involves one or more aggregate functions and comparison/logical operators.
|
||||
|
||||
## Aggregate Functions
|
||||
|
||||
SQL aggregate functions transform a collection of values from multiple rows into a single summary value. They are indispensable for data analysis, reporting, and gaining insights from datasets. These functions operate on a set of values, not individual data points.
|
||||
|
||||
## Core Aggregate Functions
|
||||
|
||||
| Function | Description | Application |
|
||||
| :------- | :----------------------------------------------------- | :-------------------------------------- |
|
||||
| `AVG()` | Calculates the average value of a numeric column. | Mean purchase amount, average salary. |
|
||||
| `SUM()` | Calculates the total sum of a numeric column. | Total revenue, sum of expenses. |
|
||||
| `COUNT()`| Counts the number of rows or non-null values. | Total transactions, user signups. |
|
||||
| `MAX()` | Returns the largest value in a column. | Highest price, maximum score. |
|
||||
| `MIN() ` | Returns the smallest value in a column. | Lowest price, minimum score. |
|
||||
|
||||
Most aggregate functions disregard `NULL` values, with the exception of `COUNT(*)` which counts all rows regardless of `NULL` values.
|
||||
|
||||
## Aggregate Function Examples
|
||||
|
||||
Consider the following tables:
|
||||
|
||||
**Students**
|
||||
|
||||
| rollno | name | class |
|
||||
| :----- | :---- | :---- |
|
||||
| 1 | Troy | TE |
|
||||
| 1 | Shree | BE |
|
||||
| 2 | Harry | TE |
|
||||
| 3 | John | TE |
|
||||
| 3 | Shiv ani | TE |
|
||||
|
||||
**purchase**
|
||||
|
||||
| item | price | customer_name |
|
||||
| :----------- | :---- | :------------ |
|
||||
| Pen | 10 | Troy |
|
||||
| Bag | 1000 | Troy |
|
||||
| Vegetables | 500 | Troy |
|
||||
| Shoes | 5000 | Troy |
|
||||
| Water Bottle | 800 | XYZ |
|
||||
| Mouse | 120 | ABC |
|
||||
| Sun Glasses | 1350 | ABC |
|
||||
|
||||
## `AVG` function
|
||||
|
||||
Calculate the average purchase amount per customer.
|
||||
|
||||
```sql
|
||||
SELECT AVG(price) AS Avg_Purchase, customer_name
|
||||
FROM purchase
|
||||
GROUP BY customer_name;
|
||||
```
|
||||
|
||||
| Avg_Purchase | customer_name |
|
||||
| :----------- | :------------ |
|
||||
| 1 627.5000 | Troy |
|
||||
| 800.0000 | XYZ |
|
||||
| 735.0000 | ABC |
|
||||
|
||||
## `SUM` function
|
||||
|
||||
Calculate the total expenditure for each customer.
|
||||
|
||||
```sql
|
||||
SELECT SUM(price) AS Total_Bill, customer_name
|
||||
FROM purchase
|
||||
GROUP BY customer_name;
|
||||
```
|
||||
|
||||
| Total_Bill | customer_name |
|
||||
| :--------- | :------------ |
|
||||
| 6510 | Troy |
|
||||
| 800 | XYZ |
|
||||
| 1470 | ABC |
|
||||
|
||||
## `COUNT ` function
|
||||
|
||||
Determine the number of items purchased by each customer.
|
||||
|
||||
```sql
|
||||
SELECT COUNT(item) AS Total_Items, customer_name
|
||||
FROM purchase
|
||||
GROUP BY customer_name;
|
||||
```
|
||||
|
||||
| Total_Items | customer _name |
|
||||
| :---------- | :------------ |
|
||||
| 4 | Troy |
|
||||
| 1 | XYZ |
|
||||
| 2 | ABC |
|
||||
|
||||
## `MAX` function
|
||||
|
||||
Identify the highest single purchase value for each customer.
|
||||
|
||||
```sql
|
||||
SELECT MAX(price) AS Highest_Purchase, customer_name
|
||||
FROM purchase
|
||||
GROUP BY customer_name;
|
||||
```
|
||||
|
||||
| Highest_Purchase | customer_name |
|
||||
| :--------------- | :------------ |
|
||||
| 5000 | Troy |
|
||||
| 800 | XYZ |
|
||||
| 1350 | ABC |
|
||||
|
||||
## `MIN` function
|
||||
|
||||
Find the lowest single purchase value for each customer.
|
||||
|
||||
```sql
|
||||
SELECT MIN(price) AS Lowest_Purchase, customer_name
|
||||
FROM purchase
|
||||
GROUP BY customer_name;
|
||||
```
|
||||
|
||||
| Lowest_Purchase | customer_name |
|
||||
| :-------------- | :------------ |
|
||||
| 10 | Troy |
|
||||
| 800 | XYZ |
|
||||
| 120 | ABC |
|
||||
|
||||
## Having Clause Examples
|
||||
|
||||
These examples demonstrate using `HAVING` to filter results based on aggregate function output.
|
||||
|
||||
### Example 1: Filtering by Group Count
|
||||
|
||||
Identify classes with more than 2 students.
|
||||
|
||||
```sql
|
||||
SELECT COUNT(class) AS strength, class
|
||||
FROM Students
|
||||
GROUP BY class
|
||||
HAVING COUNT(class) > 2;
|
||||
```
|
||||
|
||||
This query provides the count of students per class, filtered to include only those classes where the count exceeds 2.
|
||||
|
||||
| strength | class |
|
||||
| :------- | :---- |
|
||||
| 4 | TE |
|
||||
|
||||
### Example 2: Filtering by Minimum Aggregate Value
|
||||
|
||||
Find customers whose minimum purchase price is greater than 10.
|
||||
|
||||
```sql
|
||||
SELECT customer_name, MIN(price) AS MIN_PURCHASE
|
||||
FROM purchase
|
||||
GROUP BY customer_name
|
||||
HAVING MIN(price) > 10;
|
||||
```
|
||||
|
||||
This query calculates the minimum purchase for each customer and includes only those customers where this minimum is above 10.
|
||||
|
||||
| customer_name | MIN_PURCHASE |
|
||||
| :------------ | :----------- |
|
||||
| XYZ | 800 |
|
||||
| ABC | 120 |
|
||||
|
||||
### Example 3: Filtering and Ordering by Average Aggregate Value
|
||||
|
||||
List customers with an average purchase price greater than 550, ordered by name descending.
|
||||
|
||||
```sql
|
||||
SELECT customer_name, AVG(price) AS Average_Purchase
|
||||
FROM purchase
|
||||
GROUP BY customer_name
|
||||
HAVING AVG(price) > 550
|
||||
ORDER BY customer_name DESC;
|
||||
```
|
||||
|
||||
This query computes the average purchase price per customer, filters for averages above 550, and presents the results in descending order of customer name.
|
||||
|
||||
| customer_name | Average_Purchase |
|
||||
| :------------ | :--------------- |
|
||||
| XYZ | 800.0000 |
|
||||
| Troy | 1627.5000 |
|
||||
| ABC | 735.0000 |
|
||||
|
||||
### Example 4: Combining WHERE and HAVING
|
||||
|
||||
Calculate the total purchase amount for customers whose names start with "S" and whose total purchase exceeds 1000.
|
||||
|
||||
```sql
|
||||
SELECT customer_name, SUM(price) AS Total_Purchase
|
||||
FROM purchase
|
||||
WHERE customer_ name LIKE "S%" -- WHERE filters rows before grouping
|
||||
GROUP BY customer_name
|
||||
HAVING SUM(price) > 1000; -- HAVING filters groups after aggregation
|
||||
```
|
||||
|
||||
This query first filters rows to include only customers whose names start with 'S', then groups by customer name, calculates the total purchase, and finally filters these groups to include only those with a total exceeding 1000. Combining `WHERE` and `HAVING` allows for efficient multi -stage filtering.
|
||||
|
||||
| customer_name | Total_Purchase |
|
||||
| :------------ | :------------- |
|
||||
| Troy | 6510 |
|
||||
229
landing/docs/SQL-101/018-essential-mysql-functions.md
Normal file
229
landing/docs/SQL-101/018-essential-mysql-functions.md
Normal file
@@ -0,0 +1,229 @@
|
||||
# Built In Functions
|
||||
|
||||
MySQL provides numerous built-in functions that streamline data manipulation and retrieval directly within your SQL queries.
|
||||
|
||||
Utilizing these functions minimizes application-level processing, leading to more robust and performant code. This guide covers essential MySQL functions, focusing on their practical utility for Java developers.
|
||||
|
||||
## Numeric Functions
|
||||
|
||||
Optimize calculations directly in the database layer.
|
||||
|
||||
```sql
|
||||
-- Rounds 5.73 to the nearest whole number.
|
||||
SELECT ROUND(5.73);
|
||||
```
|
||||
Output: 6
|
||||
|
||||
```sql
|
||||
-- Rounds 5.73 to one decimal place.
|
||||
SELECT ROUND(5.73, 1);
|
||||
```
|
||||
Output: 5.7
|
||||
|
||||
```sql
|
||||
-- Truncates 5.758 2 to two decimal places without rounding.
|
||||
SELECT TRUNCATE(5.7582, 2);
|
||||
```
|
||||
Output: 5.75
|
||||
|
||||
```sql
|
||||
-- Returns the smallest integer greater than or equal to 5.2 .
|
||||
SELECT CEILING(5.2);
|
||||
```
|
||||
Output: 6
|
||||
|
||||
```sql
|
||||
-- Returns the largest integer less than or equal to 5.7.
|
||||
SELECT FLOOR(5.7);
|
||||
```
|
||||
Output : 5
|
||||
|
||||
```sql
|
||||
-- Returns the absolute value of -5.2.
|
||||
SELECT ABS(-5.2);
|
||||
```
|
||||
Output: 5.2
|
||||
|
||||
```sql
|
||||
-- Generates a random floating-point number between 0 and 1. Useful for sampling or generating random data.
|
||||
SELECT RAND();
|
||||
```
|
||||
|
||||
## String Functions
|
||||
|
||||
Manipulate character data efficiently within queries.
|
||||
|
||||
```sql
|
||||
-- Returns the length of the string 'sky'.
|
||||
SELECT LENGTH('sky');
|
||||
```
|
||||
Output: 3
|
||||
|
||||
```sql
|
||||
-- Converts the string 'sky' to uppercase.
|
||||
SELECT UPPER('sky');
|
||||
```
|
||||
Output: SKY
|
||||
|
||||
```sql
|
||||
-- Converts the string 'sky' to lowercase.
|
||||
SELECT LOWER('sky');
|
||||
```
|
||||
Output: sky
|
||||
|
||||
```sql
|
||||
-- Removes leading spaces from ' sky'.
|
||||
SELECT LTRIM(' sky');
|
||||
```
|
||||
Output: sky
|
||||
|
||||
```sql
|
||||
-- Removes trailing spaces from 'sky '.
|
||||
SELECT RTRIM('sky ');
|
||||
```
|
||||
Output: sky
|
||||
|
||||
```sql
|
||||
-- Removes leading and trailing spaces from ' sky '.
|
||||
SELECT TRIM(' sky ');
|
||||
``` Output: sky
|
||||
|
||||
```sql
|
||||
-- Extracts the leftmost 4 characters from 'Kindergarten'.
|
||||
SELECT LEFT('Kindergarten', 4);
|
||||
```
|
||||
Output: Kind
|
||||
|
||||
```sql
|
||||
-- Extracts the rightmost 6 characters from 'Kindergarten'.
|
||||
SELECT RIGHT('Kindergarten', 6);
|
||||
```
|
||||
Output: garten
|
||||
|
||||
```sql
|
||||
-- Extracts 5 characters from 'Kindergarten' starting at position 3.
|
||||
SELECT SUBSTRING('Kindergarten', 3, 5);
|
||||
```
|
||||
Output: nderg
|
||||
|
||||
```sql
|
||||
-- Returns the position of the first occurrence of 'n' in 'Kindergarten'. Returns 0 if not found.
|
||||
SELECT LOCATE('n','Kindergarten');
|
||||
```
|
||||
Output: 3
|
||||
|
||||
```sql
|
||||
-- Replaces all occurrences of 'garten' with 'garden' in 'Kindergarten'.
|
||||
SELECT REPLACE('Kindergarten', 'garten', 'garden');
|
||||
```
|
||||
Output: Kindergarden
|
||||
|
||||
```sql
|
||||
-- Concatenates 'first' and 'last'.
|
||||
SELECT CONCAT('first', 'last');
|
||||
```
|
||||
Output: firstlast
|
||||
|
||||
## Date Functions
|
||||
|
||||
Retrieve and extract components of date and time values.
|
||||
|
||||
```sql
|
||||
-- Returns the current date and time (YYYY-MM-DD HH:MI:SS format). [1]
|
||||
SELECT NOW();
|
||||
```
|
||||
Example Output: 2025-06-19 16:31:0 0
|
||||
|
||||
```sql
|
||||
-- Returns the current date (YYYY-MM-DD format). [1]
|
||||
SELECT CURDATE();
|
||||
```
|
||||
Example Output: 2025-06-19
|
||||
|
||||
```sql
|
||||
-- Returns the current time ( HH:MI:SS format). [1]
|
||||
SELECT CURTIME();
|
||||
```
|
||||
Example Output: 16:31:00
|
||||
|
||||
```sql
|
||||
-- Extracts the month as a number from a date/datetime. [1]
|
||||
SELECT MONTH(NOW());
|
||||
```
|
||||
Example Output: 6
|
||||
|
||||
```sql
|
||||
-- Extracts the year as a number from a date/datetime. [1]
|
||||
SELECT YEAR(NOW());
|
||||
```
|
||||
Example Output: 20 25
|
||||
|
||||
```sql
|
||||
-- Extracts the hour as a number from a time/datetime. [1]
|
||||
SELECT HOUR(NOW());
|
||||
```
|
||||
Example Output: 16
|
||||
|
||||
## Formatting Dates and Times
|
||||
|
||||
Customize date and time output strings for application display.
|
||||
|
||||
The default MySQL date format is "YYYY-MM-DD". Use `DATE_FORMAT()` and `TIME_FORMAT()` to control the output string representation.
|
||||
|
||||
```sql
|
||||
-- Form ats the current date and time. [1, 4]
|
||||
SELECT DATE_FORMAT(NOW(), '%M %D %Y');
|
||||
```
|
||||
Example Output: June 19th 2025
|
||||
|
||||
```sql
|
||||
-- Formats the current date with numeric month and day. [1, 4]
|
||||
SELECT DATE_FORMAT(NOW(), '%m %d %y');
|
||||
```
|
||||
Example Output: 06 19 25
|
||||
|
||||
```sql
|
||||
-- Formats the current date with numeric month and day with English suffix. [1, 4]
|
||||
SELECT DATE_FORMAT(NOW(), '%m %D %y');
|
||||
```
|
||||
Example Output: 06 19th 2 5
|
||||
|
||||
```sql
|
||||
-- Formats the current time. [1, 4]
|
||||
SELECT TIME_FORMAT(NOW(), '%H %i %p');
|
||||
```
|
||||
Example Output: 16 31 PM
|
||||
|
||||
## Calculating Dates and Times
|
||||
|
||||
Perform date and time arithmetic directly in queries.
|
||||
|
||||
```sql
|
||||
-- Adds 1 day to the current date and time. [1, 2]
|
||||
SELECT DATE_ADD(NOW(), INTERVAL 1 DAY);
|
||||
```
|
||||
Example Output: 2025-06-20 16:31:00
|
||||
|
||||
```sql
|
||||
-- Subtracts 1 year from the current date and time. [1, 2]
|
||||
SELECT DATE_ADD(NOW(), INTERVAL -1 YEAR);
|
||||
```
|
||||
Example Output: 2024-06-19 16:31:00
|
||||
|
||||
```sql
|
||||
-- Also subtracts 1 year from the current date and time. [1, 2]
|
||||
SELECT DATE_SUB(NOW(), INTERVAL 1 YEAR);
|
||||
```
|
||||
Example Output: 2024-06-19 16:31 :00
|
||||
|
||||
```sql
|
||||
-- Returns the difference in days between two dates. Time components are ignored for the difference calculation. [1, 7]
|
||||
SELECT DATEDIFF('2025-06-19 09:00', '2025-04-10 17:00');
|
||||
```
|
||||
Output: 70
|
||||
|
||||
```sql
|
||||
-- Calculates the difference between two times in seconds by converting them to seconds past midnight. [5, 7]
|
||||
SELECT TIME_TO_SEC('09:00') - TIME_TO_SEC('09:02');
|
||||
```
|
||||
Output: -120
|
||||
169
landing/docs/SQL-101/020-TCL-commands.md
Normal file
169
landing/docs/SQL-101/020-TCL-commands.md
Normal file
@@ -0,0 +1,169 @@
|
||||
# SQL Transaction Control
|
||||
|
||||
Transaction Control Language (TCL) manages transactions within a database, ensuring data consistency and reliability. A transaction is a logical unit of work comprising one or more SQL statements, executed co-relationally against data.
|
||||
|
||||
## TCL Commands
|
||||
|
||||
- `COMMIT`
|
||||
- `ROLLBACK`
|
||||
- `SAVEPOINT`
|
||||
|
||||
## COMMIT
|
||||
|
||||
The `COMMIT` command final izes a transaction. All data modifications made within the transaction become permanent and visible to other database sessions. Executing `COMMIT` guarantees data persistence up to that point.
|
||||
|
||||
### Syntax
|
||||
|
||||
```sql
|
||||
COMMIT;
|
||||
```
|
||||
|
||||
## ROLLBACK
|
||||
|
||||
`ROLLBACK` discards all changes made since the transaction started or since the last `SAVEPOINT`. It restores the database to a previous state, effectively undoing operations within the transaction. This is crucial for error handling and partial transaction reversal.
|
||||
|
||||
### Syntax
|
||||
|
||||
```sql
|
||||
ROLLBACK TO savepoint-name;
|
||||
```
|
||||
*Note: Without the `TO savepoint-name` clause, `ROLLBACK` undoes the entire current transaction.*
|
||||
|
||||
## SAVEPOINT
|
||||
|
||||
A `SAVEPOINT` establishes a marker within a transaction. You can `ROLLBACK` to a specific savepoint, partially undoing changes while retaining prior modifications within the same transaction. This allows fine-grained control over transaction scope.
|
||||
|
||||
### Syntax
|
||||
|
||||
```sql
|
||||
SAVE POINT savepoint-name;
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
Using the `purchase` table to demonstrate TCL command behavior.
|
||||
|
||||
| item | price | customer_name |
|
||||
|--------------|-------|---------------|
|
||||
| Pen | 10 | Troy |
|
||||
| Bag | 1000 | Troy |
|
||||
| Vegetables | 500 | Troy |
|
||||
| Shoes | 5000 | Troy |
|
||||
| Water Bottle | 800 | XYZ |
|
||||
| Mouse | 120 | ABC |
|
||||
| Sun Glasses | 1350 | ABC |
|
||||
|
||||
Update the price of "Pen" from 10 to 20.
|
||||
|
||||
```sql
|
||||
UPDATE purchase SET price = 20 WHERE item = "Pen";
|
||||
```
|
||||
|
||||
Output indicates success. The change is applied (though not necessarily permanent yet depending on database settings). ```
|
||||
Query OK, 1 row affected (...)
|
||||
```
|
||||
|
||||
View the updated table state.
|
||||
|
||||
```sql
|
||||
SELECT * FROM purchase;
|
||||
```
|
||||
|
||||
| item | price | customer_name |
|
||||
|--------------|-------|---------------|
|
||||
| Pen | 20 | Troy |
|
||||
| Bag | 1000 | Troy |
|
||||
| Vegetables | 500 | Troy |
|
||||
| Shoes | 5 000 | Troy |
|
||||
| Water Bottle | 800 | XYZ |
|
||||
| Mouse | 120 | ABC |
|
||||
| Sun Glasses | 1350 | ABC |
|
||||
|
||||
Begin a transaction explicitly (some databases default to autocommit).
|
||||
|
||||
```sql
|
||||
START TRANSACTION;
|
||||
```
|
||||
|
||||
Commit the changes made so far within this explicit or implicit transaction. This makes the "Pen" price update (10 to 20) permanent.
|
||||
|
||||
```sql
|
||||
COMMIT;
|
||||
```
|
||||
|
||||
Attempting to rollback now has no effect on the committed transaction.
|
||||
|
||||
```sql
|
||||
ROLLBACK;
|
||||
```
|
||||
|
||||
Querying the table shows the committed change persists.
|
||||
|
||||
```sql
|
||||
SELECT * FROM purchase;
|
||||
```
|
||||
|
||||
| item | price | customer_name |
|
||||
|--------------|-------|---------------|
|
||||
| Pen | 20 | Troy |
|
||||
| Bag | 1000 | Troy |
|
||||
| Vegetables | 500 | Troy |
|
||||
| Shoes | 5000 | Troy |
|
||||
| Water Bottle | 800 | XYZ |
|
||||
| Mouse | 120 | ABC |
|
||||
| Sun Glasses | 1350 | ABC |
|
||||
|
||||
Create a savepoint named `sv_update` in the current transaction. Changes before this point are protected from rollbacks targeting this savepoint.
|
||||
|
||||
```sql
|
||||
SAVEPOINT sv_update;
|
||||
```
|
||||
|
||||
Update the price of "Pen" again, from 20 to 30. This change occurs after the `sv_update` savepoint .
|
||||
|
||||
```sql
|
||||
UPDATE purchase SET price = 30 WHERE item = "Pen";
|
||||
```
|
||||
|
||||
Output indicates success.
|
||||
```
|
||||
Query OK, 1 row affected (...)
|
||||
```
|
||||
|
||||
View the table state showing the new price (30).
|
||||
|
||||
```sql
|
||||
SELECT * FROM purchase;
|
||||
```
|
||||
|
||||
| item | price | customer_name |
|
||||
|--------------|-------|---------------|
|
||||
| Pen | 30 | Troy |
|
||||
| Bag | 1000 | Troy |
|
||||
| Vegetables | 500 | Troy |
|
||||
| Shoes | 5000 | Troy |
|
||||
| Water Bottle | 800 | XYZ |
|
||||
| Mouse | 120 | ABC |
|
||||
| Sun Glasses | 1350 | ABC |
|
||||
|
||||
Rollback the transaction specifically to the `sv_update` savepoint. This undoes the price change from 20 to 30, but *not* the prior change from 10 to 20 because it was committed.
|
||||
|
||||
```sql
|
||||
ROLLBACK to sv_update;
|
||||
```
|
||||
|
||||
Querying the table shows the state after the partial rollback. The price of "Pen" is restored to 20, as this was the state at the `sv_update` savepoint.
|
||||
|
||||
```sql
|
||||
SELECT * FROM purchase;
|
||||
```
|
||||
|
||||
| item | price | customer_name |
|
||||
|--------------|-------|---------------|
|
||||
| Pen | 20 | Troy |
|
||||
| Bag | 1000 | Troy |
|
||||
| Vegetables | 500 | Troy |
|
||||
| Shoes | 5000 | Troy |
|
||||
| Water Bottle | 800 | XYZ |
|
||||
| Mouse | 120 | ABC |
|
||||
| Sun Glasses | 1350 | ABC |
|
||||
30
landing/docs/SQL-101/index.md
Normal file
30
landing/docs/SQL-101/index.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# TABLES
|
||||
|
||||
A database, often referred to as a schema in a relational context, is an organized collection of structured data. It's the persistence layer for your application, essential for storing and managing information that outlasts application processes.
|
||||
|
||||
Think of it as a reliable system ensuring data validity and enforcing relationships without requiring excessive application-level checks.
|
||||
|
||||
## Tables and Columns
|
||||
|
||||
The fundamental unit of a database is the table. Tables organize data into rows and columns, similar in concept to a spreadsheet but with enforced structure and data types.
|
||||
|
||||
Each column within a table holds a specific type of data (e.g., text, numbers, dates), defining the structure for every entry.
|
||||
|
||||
Consider a simple task management application. Key information would reside in distinct tables:
|
||||
|
||||
* **Users:** Stores user-specific data. Columns might include `username`, `name`, and `active` status.
|
||||
* **Tasks:** Contains task details. Relevant columns could be `task_name`, `status`, `due_date`, and `priority`.
|
||||
|
||||
The `Users` table structure illustrates this:
|
||||
|
||||
| id | username | name | active |
|
||||
| :-- | :---------- | :-------------- | :----- |
|
||||
| 1 | shinobi | Software Shinobi| true |
|
||||
| 2 | grisi | Greisi I. | true |
|
||||
| 3 | javateamsix | Java Team Six | false |
|
||||
|
||||
## Table Structure Summary
|
||||
|
||||
* The table is defined by four columns: `id`, `username`, `name`, and `active`.
|
||||
* Each row represents a distinct record, with three entries (users) shown here.
|
||||
* The `id` column serves as the unique identifier for each record, typically configured for automatic incrementing.
|
||||
@@ -1,145 +0,0 @@
|
||||
# Basic Syntax
|
||||
|
||||
In this chapter, we will go over the basic SQL syntax.
|
||||
|
||||
SQL statements are basically the 'commands' that you run against a specific database. Through the SQL statements, you are telling MySQL what you want it to do, for example, if you wanted to get the `username` of all of your users stored in the `users` table, you would run the following SQL statement:
|
||||
|
||||
```sql
|
||||
SELECT username FROM users;
|
||||
```
|
||||
|
||||
Rundown of the statement:
|
||||
|
||||
* `SELECT`: First, we specify the `SELECT` keyword, which indicates that we want to select some data from the database. Other popular keywords are: `INSERT`, `UPDATE` and `DELETE`.
|
||||
* `username`: Then we specify which column we want to select.
|
||||
* `FROM users`: After that, we specify the table that we want to select the data from using the `FROM` keyword.
|
||||
* The semicolon `;` is highly recommended to put at the end. Standard SQL syntax requires it, but some "Database Management Systems' (DBMS)" are tolerant about it, but it's not worth the risk.
|
||||
|
||||
If you run the above statement, you will get no results as the new `users` table that we've just created is empty.
|
||||
|
||||
> As a good practice, all SQL keywords should be with uppercase, however, it would work just fine if you use lower case as well.
|
||||
|
||||
Let's go ahead and cover the basic operations next.
|
||||
|
||||
## INSERT
|
||||
|
||||
To add data to your database, you would use the `INSERT` statement.
|
||||
|
||||
Let's use the table that we created in the last chapter and insert 1 user into our `users` table:
|
||||
|
||||
```sql
|
||||
INSERT INTO users (username, email, active)
|
||||
VALUES ('bobby', 'bobby@bobbyiliev.com', true);
|
||||
```
|
||||
|
||||
Rundown of the insert statement:
|
||||
|
||||
* `INSERT INTO`: first, we specify the `INSERT INTO` keyword, which tells MySQL that we want to insert data a table.
|
||||
* `users (username, email, active)`: then, we specify the table name `users` and the columns that we want to insert data into.
|
||||
* `VALUES`: then, we specify the values that we want to insert in. The order of attributes is the same as in `users (...)`.
|
||||
|
||||
## SELECT
|
||||
|
||||
Once we've inserted that user, let's go ahead and retrieve the information.
|
||||
|
||||
To retrieve information from your database, you could use the `SELECT` statement:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| id | username | about | birthday | active | email |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| 1 | bobby | NULL | NULL | 1 | bobby@b...com |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
```
|
||||
|
||||
We specify `*` right after the `SELECT` keyword, this means that we want to get all of the columns from the `users` table.
|
||||
|
||||
If we wanted to retrieve only the `username` and the `email` columns instead, we would change the statement to:
|
||||
|
||||
```sql
|
||||
SELECT username, email FROM users;
|
||||
```
|
||||
|
||||
This will return all of the users, but as of the time being we have only 1:
|
||||
|
||||
```
|
||||
+----------+----------------------+
|
||||
| username | email |
|
||||
+----------+----------------------+
|
||||
| bobby | bobby@bobbyiliev.com |
|
||||
+----------+----------------------+
|
||||
```
|
||||
|
||||
## UPDATE
|
||||
|
||||
In order to modify data in your database, you could use the `UPDATE` statement.
|
||||
|
||||
The syntax would look like this:
|
||||
|
||||
```sql
|
||||
UPDATE users SET username='bobbyiliev' WHERE id=1;
|
||||
```
|
||||
|
||||
Rundown of the statement:
|
||||
|
||||
* `UPDATE users`: First, we specify the `UPDATE` keyword followed by the table that we want to update.
|
||||
* `SET username='bobbyiliev'`: Then we specify the columns that we want to update and the new value that we want to set.
|
||||
* `WHERE id=1`: Finally, by using the `WHERE` clause, we specify which user should be updated. In our case it is the user with ID 1.
|
||||
|
||||
> NOTE: If we don't specify a `WHERE` clause, all of the entries inside the `users` table would be updated, and all users would have the `username` set to `bobbyiliev`. You need to be careful when you use the `UPDATE` statement without a `WHERE` clause, as every single row will be updated.
|
||||
|
||||
We are going to cover `WHERE` more in-depth in the next few chapters.
|
||||
|
||||
## DELETE
|
||||
|
||||
As the name suggests, the `DELETE` statement would remove data from your database.
|
||||
|
||||
The syntax is as follows:
|
||||
|
||||
```sql
|
||||
DELETE FROM users WHERE id=1;
|
||||
```
|
||||
|
||||
Similar to the `UPDATE` statement, if you don't specify a `WHERE` clause, all of the entries from the table will be affected, meaning that all of your users will be deleted.
|
||||
|
||||
## Comments
|
||||
|
||||
In case that you are writing a larger SQL script, it might be helpful to add some comments so that later on, when you come back to the script, you would know what each line does.
|
||||
|
||||
As with all programming languages, you can add comments in SQL as well.
|
||||
|
||||
There are two types of comments:
|
||||
|
||||
* Inline comments:
|
||||
|
||||
To do so, you just need to add `--` before the text that you want to comment out:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users; -- Get all users
|
||||
```
|
||||
|
||||
* Multiple-line comments:
|
||||
|
||||
Similar to some other programming languages in order to comment multiple lines, you could wrap the text in `/*` `*/` as follows:
|
||||
|
||||
```sql
|
||||
/*
|
||||
Get all of the users
|
||||
from your database
|
||||
*/
|
||||
SELECT * FROM users;
|
||||
```
|
||||
|
||||
You could write that in a `.sql` file and then run it later on, or execute the few lines directly.
|
||||
|
||||
## Conclusion
|
||||
|
||||
Those were some of the most common basic SQL statements.
|
||||
|
||||
In the next chapters, we are going to go over each of the above statements more in-depth.
|
||||
@@ -1,359 +0,0 @@
|
||||
# SELECT
|
||||
|
||||
As we briefly covered in the previous chapter, the `SELECT` statement allows us to retrieve data from single or multiple tables on the database. In this chapter, we will be performing the query on a single table.
|
||||
|
||||
It corresponds to the projection operation of Relational Algebra.
|
||||
|
||||
You can use `SELECT` to get all of your users or a list of users that match a certain criteria.
|
||||
|
||||
Before we dive into the `SELECT` statement let's quickly create a database:
|
||||
|
||||
```sql
|
||||
CREATE DATABASE sql_demo;
|
||||
```
|
||||
|
||||
Switch to that database:
|
||||
|
||||
```sql
|
||||
USE sql_demo;
|
||||
```
|
||||
|
||||
Create a new users table:
|
||||
|
||||
```sql
|
||||
CREATE TABLE users
|
||||
(
|
||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
username VARCHAR(255) NOT NULL,
|
||||
about TEXT,
|
||||
email VARCHAR(255),
|
||||
birthday DATE,
|
||||
active BOOL
|
||||
);
|
||||
```
|
||||
|
||||
Insert some data that we could work with:
|
||||
|
||||
```sql
|
||||
INSERT INTO users
|
||||
( username, email, active )
|
||||
VALUES
|
||||
('bobby', 'b@devdojo.com', true),
|
||||
('devdojo', 'd@devdojo.com', false),
|
||||
('tony', 't@devdojo.com', true);
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
Query OK, 3 rows affected (0.00 sec)
|
||||
Records: 3 Duplicates: 0 Warnings: 0
|
||||
```
|
||||
|
||||
We are going to learn more about the `INSERT` statement in the following chapters.
|
||||
|
||||
## SELECT all columns
|
||||
|
||||
Now that we've got some data in the `users` table, let's go ahead and retrieve all of the entries from that table:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users;
|
||||
```
|
||||
|
||||
Rundown of the statement:
|
||||
|
||||
* `SELECT`: First, we specify the action that we want to execute, in our case, we want to select or get some data from the database.
|
||||
* `*`: The star here indicates that we want to get all of the columns associated with the table that we are selecting from.
|
||||
* `FROM`: The from statement tells MySQL which table we want to select the data from. You need to keep in mind that you can select from multiple tables, but this is a bit more advanced, and we are going to cover this in the next few chapters.
|
||||
* `users`: This is the table name that we want to select the data from.
|
||||
|
||||
This will return all of the entries in the `users` table along with all of the columns:
|
||||
|
||||
```
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| id | username | about | birthday | active | email |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| 1 | bobby | NULL | NULL | 1 | b@devdojo.com |
|
||||
| 2 | devdojo | NULL | NULL | 0 | d@devdojo.com |
|
||||
| 3 | tony | NULL | NULL | 1 | t@devdojo.com |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
3 rows in set (0.00 sec)
|
||||
```
|
||||
|
||||
As you can see, we get a list of the 3 users that we've just created, including all of the columns in that table. In some cases, the table might have a lot of columns, and you might not want to see all of them. For example, we have the `about` and `birthday` columns that are all `NULL` at the moment. So let's see how we could limit that and get only a list of specific columns.
|
||||
|
||||
## Pattern matching
|
||||
SQL pattern matching let's you to search for patterns if you don't know the exact word or phrase you are looking for. To do this, we use so-called wildcard characters to match a pattern together with LIKE and ILIKE operators.
|
||||
|
||||
Two of the most common wildcard characters are `_` and `%`.
|
||||
|
||||
`_` matches any single character and `%` matches an arbitrary number of characters.
|
||||
|
||||
Let's see an example how you would look for a `username` ending with `y`:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE username LIKE '%y';
|
||||
```
|
||||
|
||||
Output:
|
||||
```
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| id | username | about | birthday | active | email |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| 1 | bobby | NULL | NULL | 1 | b@devdojo.com |
|
||||
| 3 | tony | NULL | NULL | 1 | t@devdojo.com |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
```
|
||||
As you can see above, we used `%` to match any number of characters preceding the character `y`.
|
||||
|
||||
If we know the exact number of characters we want to match, we can use `_`. Each `_` represents a single character.
|
||||
|
||||
So, if we want to look up an username that has `e` as its second character, we would do something like this:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE username LIKE '_e%';
|
||||
```
|
||||
|
||||
Output:
|
||||
```
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| id | username | about | birthday | active | email |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| 2 | devdojo | NULL | NULL | 0 | d@devdojo.com |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
```
|
||||
|
||||
Please, keep in mind that `LIKE` operator is case sensitive, meaning it won't mach capital letters with lowercase letters and vice versa. If you wish to ignore capitalization, use `ILIKE` operator instead.
|
||||
|
||||
|
||||
## Formatting
|
||||
|
||||
As we mentioned in the previous chapters, each SQL statement needs to end with a semi-colon: `;`. Alternatively, rather than using a semi-colon, you could use the `\G` characters which would format the output in a list rather than a table.
|
||||
|
||||
The syntax is absolutely the same but you just change the `;` with `\G`:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users \G
|
||||
```
|
||||
|
||||
The output will be formatted like this:
|
||||
|
||||
```
|
||||
*************************** 1. row ***************************
|
||||
id: 1
|
||||
username: bobby
|
||||
about: NULL
|
||||
birthday: NULL
|
||||
active: 1
|
||||
email: b@devdojo.com
|
||||
*************************** 2. row ***************************
|
||||
id: 2
|
||||
username: devdojo
|
||||
about: NULL
|
||||
birthday: NULL
|
||||
active: 0
|
||||
email: d@devdojo.com
|
||||
...
|
||||
```
|
||||
|
||||
This is very handy whenever your table consists of a large number of columns and they can't fit on the screen, which makes it very hard to read the result set.
|
||||
|
||||
## SELECT specific columns only
|
||||
|
||||
You could limit this to a specific set of columns. Let's say that you only needed the `username` and the `active` columns. In this case, you would change the `*` symbol with the columns that you want to select divided by a comma:
|
||||
|
||||
```sql
|
||||
SELECT username,active FROM users;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----------+--------+
|
||||
| username | active |
|
||||
+----------+--------+
|
||||
| bobby | 1 |
|
||||
| devdojo | 0 |
|
||||
| tony | 1 |
|
||||
+----------+--------+
|
||||
```
|
||||
|
||||
As you can see, we are getting back only the 2 columns that we've specified in the `SELECT` statement.
|
||||
|
||||
> **NOTE:** _SQL names are case insensitive. For example, username ≡ USERNAME ≡ userName._
|
||||
|
||||
## SELECT with no FROM Clause
|
||||
|
||||
In a SQL statement, a column can be a literal with no `FROM` clause.
|
||||
|
||||
```sql
|
||||
SELECT 'Sunil' as username;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----------+
|
||||
| username |
|
||||
+----------+
|
||||
| Sunil |
|
||||
+----------+
|
||||
```
|
||||
|
||||
## SELECT with Arithmetic Operations
|
||||
|
||||
The select clause can contain arithmetic expressions involving the operation +, –, *, and /.
|
||||
|
||||
```sql
|
||||
SELECT username, active*5 as new_active FROM users;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----------+------------+
|
||||
| username | new_active |
|
||||
+----------+------------+
|
||||
| bobby | 5 |
|
||||
| devdojo | 0 |
|
||||
| tony | 5 |
|
||||
+----------+------------+
|
||||
```
|
||||
|
||||
## LIMIT
|
||||
|
||||
The `LIMIT` clause is very handy in case that you want to limit the number of results that you get back. For example, at the moment, we have 3 users in our database, but let's say that you only wanted to get 1 entry back when you run the `SELECT` statement.
|
||||
|
||||
This can be achieved by adding the `LIMIT` clause at the end of your statement, followed by the number of entries that you want to get. For example, let's say that we wanted to get only 1 entry back. We would run the following query:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users LIMIT 1;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| id | username | about | birthday | active | email |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| 2 | bobby | NULL | NULL | 1 | b@devdojo.com |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
```
|
||||
|
||||
If you wanted to get 2 entries, you would change `LIMIT 2` and so on.
|
||||
|
||||
## COUNT
|
||||
|
||||
In case that you wanted to get only the number of entries in a specific column, you could use the `COUNT` function. This is a function that I personally use very often.
|
||||
|
||||
The syntax is the following:
|
||||
|
||||
```sql
|
||||
SELECT COUNT(*) FROM users;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----------+
|
||||
| COUNT(*) |
|
||||
+----------+
|
||||
| 3 |
|
||||
+----------+
|
||||
```
|
||||
|
||||
## MIN, MAX, AVG, and SUM
|
||||
|
||||
Another useful set of functions similar to `COUNT` that would make your life easier are:
|
||||
|
||||
* `MIN`: This would give you the smallest value of a specific column. For example, if you had an online shop and you wanted to get the lowest price, you would use the `MIN` function. In our case, if we wanted to get the lowest user ID, we would run the following:
|
||||
|
||||
```sql
|
||||
SELECT MIN(id) FROM users;
|
||||
```
|
||||
|
||||
This would return `1` as the lowest user ID that we have is 1.
|
||||
|
||||
* `MAX`: Just like `MIN`, but it would return the highest value:
|
||||
|
||||
```sql
|
||||
SELECT MAX(id) FROM users;
|
||||
```
|
||||
|
||||
In our case, this would be `3` as we have only 3 users, and the highest value of the `id` column is 3.
|
||||
|
||||
* `AVG`: As the name suggests, it would sum up all of the values of a specific column and return the average value. As we have 3 users with ids 1, 2, and 3, the average would be 6 divided by 3 users which is 2.
|
||||
|
||||
```sql
|
||||
SELECT AVG(id) FROM users;
|
||||
```
|
||||
|
||||
* `SUM`: This function takes all of the values from the specified column and sums them up:
|
||||
|
||||
```sql
|
||||
SELECT SUM(id) FROM users;
|
||||
```
|
||||
|
||||
## DISTINCT
|
||||
|
||||
In some cases, you might have duplicate entries in a table, and in order to get only the unique values, you could use `DISTINCT`.
|
||||
|
||||
To better demonstrate this, let's run the insert statement one more time so that we could duplicate the existing users and have 6 users in the users table:
|
||||
|
||||
```sql
|
||||
INSERT INTO users
|
||||
( username, email, active )
|
||||
VALUES
|
||||
('bobby', 'b@devdojo.com', true),
|
||||
('devdojo', 'd@devdojo.com', false),
|
||||
('tony', 't@devdojo.com', true);
|
||||
```
|
||||
|
||||
Now, if you run `SELECT COUNT(*) FROM users;` you would get `6` back.
|
||||
|
||||
Let's also select all users and show only the `username` column:
|
||||
|
||||
```sql
|
||||
SELECT username FROM users;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----------+
|
||||
| username |
|
||||
+----------+
|
||||
| bobby |
|
||||
| devdojo |
|
||||
| tony |
|
||||
| bobby |
|
||||
| devdojo |
|
||||
| tony |
|
||||
+----------+
|
||||
```
|
||||
|
||||
As you can see, each name is present multiple times in the list. We have `bobby`, `devdjo` and `tony` showing up twice.
|
||||
|
||||
If we wanted to show only the unique `usernames`, we could add the `DISTINCT` keyword to our select statement:
|
||||
|
||||
```sql
|
||||
SELECT DISTINCT username FROM users;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----------+
|
||||
| username |
|
||||
+----------+
|
||||
| bobby |
|
||||
| devdojo |
|
||||
| tony |
|
||||
+----------+
|
||||
```
|
||||
|
||||
As you can see, the duplicate entries have been removed from the output.
|
||||
|
||||
## Conclusion
|
||||
|
||||
The `SELECT` statement is essential whenever working with SQL. In the next chapter, we are going to learn how to use the `WHERE` clause and take the `SELECT` statements to the next level.
|
||||
@@ -1,225 +0,0 @@
|
||||
# WHERE
|
||||
|
||||
The `WHERE` clause allows you to specify different conditions so that you could filter out the data and get a specific result set.
|
||||
|
||||
You would add the `WHERE` clause after the `FROM` clause.
|
||||
|
||||
The syntax would look like this:
|
||||
|
||||
```sql
|
||||
SELECT column_name FROM table_name WHERE column=some_value;
|
||||
```
|
||||
|
||||
## WHERE Clause example
|
||||
|
||||
If we take the example `users` table from the last chapter, let's say that we wanted to get only the active users. The SQL statement would look like this:
|
||||
|
||||
```sql
|
||||
SELECT DISTINCT username, email, activem FROM users WHERE active=true;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----------+---------------+--------+
|
||||
| username | email | active |
|
||||
+----------+---------------+--------+
|
||||
| bobby | b@devdojo.com | 1 |
|
||||
| tony | t@devdojo.com | 1 |
|
||||
+----------+---------------+--------+
|
||||
```
|
||||
|
||||
As you can see, we are only getting `tony` and `bobby` back as their `active` column is `true` or `1`. If we wanted to get the inactive users, we would have to change the `WHERE` clause and set the `active` to `false`:
|
||||
|
||||
```
|
||||
+----------+---------------+--------+
|
||||
| username | email | active |
|
||||
+----------+---------------+--------+
|
||||
| devdojo | d@devdojo.com | 0 |
|
||||
+----------+---------------+--------+
|
||||
```
|
||||
|
||||
As another example, let's say that we wanted to select all users with the username `bobby`. The query, in this case, would be:
|
||||
|
||||
```sql
|
||||
SELECT username, email, active FROM users WHERE username='bobby';
|
||||
```
|
||||
|
||||
The output would look like this:
|
||||
|
||||
```
|
||||
+----------+---------------+--------+
|
||||
| username | email | active |
|
||||
+----------+---------------+--------+
|
||||
| bobby | b@devdojo.com | 1 |
|
||||
| bobby | b@devdojo.com | 1 |
|
||||
+----------+---------------+--------+
|
||||
```
|
||||
|
||||
We are getting 2 entries back as we have 2 users in our database with the username `bobby`.
|
||||
|
||||
## Operators
|
||||
|
||||
In the example, we used the `=` operator, which checks if the result set matches the value that we are looking for.
|
||||
|
||||
A list of popular operators are:
|
||||
|
||||
* `!=` : Not equal operator
|
||||
* `>` : Greater than
|
||||
* `>=` : Greater than or equal operator
|
||||
* `<` : Less than operator
|
||||
* `<=` : Less than or equal operator
|
||||
|
||||
For more information about other available operators, make sure to check the official documentation [here](https://dev.mysql.com/doc/refman/8.0/en/non-typed-operators.html).
|
||||
|
||||
## AND keyword
|
||||
|
||||
In some cases, you might want to specify multiple criteria. For example, you might want to get all users that are active, and the username matches a specific value. This could be achieved with the `AND` keyword.
|
||||
|
||||
Syntax:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE username='bobby' AND active=true;
|
||||
```
|
||||
|
||||
The result set would contain the data that matches both conditions. In our case, the output would be:
|
||||
|
||||
```
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| id | username | about | birthday | active | email |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| 2 | bobby | NULL | NULL | 1 | b@devdojo.com |
|
||||
| 5 | bobby | NULL | NULL | 1 | b@devdojo.com |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
```
|
||||
|
||||
If we were to change the `AND` statement to `active=false`, we would not get any results back as none of the entries in our database match that condition:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE username='bobby' AND active=false;
|
||||
```
|
||||
```
|
||||
-- Output:
|
||||
Empty set (0.01 sec)
|
||||
```
|
||||
|
||||
## OR keyword
|
||||
|
||||
In some cases, you might want to specify multiple criteria. For example, you might want to get all users that are active, or their username matches a specific value. This could be achieved with the `OR` keyword.
|
||||
|
||||
As with any other programming language, the main difference between `AND` and `OR` is that with `AND`, the result would only return the values that match the two conditions, and with `OR`, you would get a result that matches either of the conditions.
|
||||
|
||||
For example, if we were to run the same query as above but change the `AND` to `OR`, we would get all users that have the username `bobby` and also all users that are not active:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE username='bobby' OR active=false;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| id | username | about | birthday | active | email |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| 2 | bobby | NULL | NULL | 1 | b@devdojo.com |
|
||||
| 3 | devdojo | NULL | NULL | 0 | d@devdojo.com |
|
||||
| 5 | bobby | NULL | NULL | 1 | b@devdojo.com |
|
||||
| 6 | devdojo | NULL | NULL | 0 | d@devdojo.com |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
```
|
||||
|
||||
## LIKE operator
|
||||
|
||||
Unlike the `=` operator, the `LIKE` operator allows you to do wildcard matching similar to the `*` symbol in Linux.
|
||||
|
||||
For example, if you wanted to get all users that have the `y` letter in them, you would run the following:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE username LIKE '%y%';
|
||||
```
|
||||
|
||||
Output
|
||||
|
||||
```
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| id | username | about | birthday | active | email |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| 2 | bobby | NULL | NULL | 1 | b@devdojo.com |
|
||||
| 4 | tony | NULL | NULL | 1 | t@devdojo.com |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
```
|
||||
|
||||
As you can see, we are getting only `tony` and `bobby` but not `devdojo` as there is no `y` in `devdojo`.
|
||||
|
||||
This is quite handy when you are building some search functionality for your application.
|
||||
|
||||
# IN operator
|
||||
|
||||
The `IN` operator allows you to provide a list expression and would return the results that match that list of values.
|
||||
|
||||
For example, if you wanted to get all users that have the username `bobby` and `devdojo`, you could use the following:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE username IN ('bobby', 'devdojo');
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| id | username | about | birthday | active | email |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| 2 | bobby | NULL | NULL | 1 | b@devdojo.com |
|
||||
| 3 | devdojo | NULL | NULL | 0 | d@devdojo.com |
|
||||
| 5 | bobby | NULL | NULL | 1 | b@devdojo.com |
|
||||
| 6 | devdojo | NULL | NULL | 0 | d@devdojo.com |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
```
|
||||
|
||||
This allows you to simplify your `WHERE` expression so that you don't have to add numerous `OR` statements.
|
||||
|
||||
## IS operator
|
||||
|
||||
If you were to run `SELECT * FROM users WHERE about=NULL;` you would get an empty result set as the `=` operator can't be used to check for NULL values. Instead, you would need to use the `IS` operator instead.
|
||||
|
||||
The `IS` operator is only used to check `NULL` values, and the syntax is the following:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE about IS NULL;
|
||||
```
|
||||
|
||||
If you wanted to get the results where the value is not NULL, you just need to change `IS` to `IS NOT`:
|
||||
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE about IS NOT NULL;
|
||||
```
|
||||
|
||||
## BETWEEN operator
|
||||
|
||||
The `BETWEEN` operator allows to select value with a given range.The values can be numbers, text, or dates.
|
||||
BETWEEN operator is inclusive: begin and end values are included.
|
||||
|
||||
For Example if you want to select those user which have id between 3 and 6.
|
||||
|
||||
```sql
|
||||
SELECT * FROM users WHERE id BETWEEN 3 AND 6;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| id | username | about | birthday | active | email |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
| 3 | devdojo | NULL | NULL | 0 | d@devdojo.com |
|
||||
| 5 | bobby | NULL | NULL | 1 | b@devdojo.com |
|
||||
| 6 | devdojo | NULL | NULL | 0 | d@devdojo.com |
|
||||
+----+----------+-------+----------+--------+---------------+
|
||||
```
|
||||
|
||||
## Conclusion
|
||||
|
||||
In this chapter, you've learned how to use the `WHERE` clause with different operators to get different type of results based on the parameters that you provide.
|
||||
|
||||
In the next chapter, we will learn how to order the result set.
|
||||
@@ -1,143 +0,0 @@
|
||||
# Sorting with ORDER and GROUP BY
|
||||
|
||||
In the last chapter, you've learned how to use the `SELECT` statement with the `WHERE` clause and filter the result set based on some conditions.
|
||||
|
||||
More often than not, you would want to order the results in a specific way based on a particular column. For example, you might want to order the users alphabetically based on their username.
|
||||
|
||||
In this chapter, you will learn how to use the `ORDER BY` and `GROUP BY` clauses.
|
||||
|
||||
## ORDER BY
|
||||
|
||||
The main thing that you need to keep in mind when using `ORDER BY` is to specify the column or columns you want to order by. In case you want to specify multiple columns to order by, you need to separate each column with a comma.
|
||||
|
||||
If we were to run the following statement without providing an `ORDER BY` clause:
|
||||
|
||||
```sql
|
||||
SELECT id, username FROM users;
|
||||
```
|
||||
|
||||
We will get the following output:
|
||||
|
||||
```
|
||||
+----+----------+
|
||||
| id | username |
|
||||
+----+----------+
|
||||
| 2 | bobby |
|
||||
| 3 | devdojo |
|
||||
| 4 | tony |
|
||||
| 5 | bobby |
|
||||
| 6 | devdojo |
|
||||
| 7 | tony |
|
||||
+----+----------+
|
||||
```
|
||||
|
||||
As you can see, the result set is sorted by the primary key, which, in our case, is each user's id. If we wanted to sort the output by `username`, we would run the following query:
|
||||
|
||||
```sql
|
||||
SELECT id, username FROM users ORDER BY username;
|
||||
```
|
||||
|
||||
> Note: The `ORDER BY` statement is followed by the column's name that we want to order by.
|
||||
|
||||
The output, in this case, will be:
|
||||
|
||||
```
|
||||
+----+----------+
|
||||
| id | username |
|
||||
+----+----------+
|
||||
| 2 | bobby |
|
||||
| 5 | bobby |
|
||||
| 3 | devdojo |
|
||||
| 6 | devdojo |
|
||||
| 4 | tony |
|
||||
| 7 | tony |
|
||||
+----+----------+
|
||||
```
|
||||
|
||||
> Note: You can use `ORDER BY` with and without specifying a `WHERE` clause. If you've used a `WHERE` clause, you must put the `ORDER BY` clause after the `WHERE` clause.
|
||||
|
||||
The default sorting is ascending and is specified with the `ASC` keyword, and you don't need to add it explicitly, but if you want to sort by descending order, you need to use the `DESC` keyword.
|
||||
|
||||
If we use the query above and add `DESC` at the end as follows:
|
||||
|
||||
|
||||
```sql
|
||||
SELECT id, username FROM users ORDER BY username DESC;
|
||||
```
|
||||
|
||||
We will see the following output:
|
||||
|
||||
```
|
||||
+----+----------+
|
||||
| id | username |
|
||||
+----+----------+
|
||||
| 4 | tony |
|
||||
| 7 | tony |
|
||||
| 3 | devdojo |
|
||||
| 6 | devdojo |
|
||||
| 2 | bobby |
|
||||
| 5 | bobby |
|
||||
+----+----------+
|
||||
```
|
||||
|
||||
As you can see, we've got the same list of users sorted alphabetically but in reverse order.
|
||||
|
||||
## GROUP BY
|
||||
|
||||
The `GROUP BY` statement allows you to use a function like `COUNT`, `MIN`, `MAX` etc., with multiple columns.
|
||||
|
||||
For example, let's say that we wanted to get all user counts grouped by username.
|
||||
|
||||
In our case, we have two users with the username `bobby`, two users with the username `tony`, and two users with the username `devdojo`. This represented in an SQL statement would look like this:
|
||||
|
||||
```sql
|
||||
SELECT COUNT(username), username FROM users GROUP BY username;
|
||||
```
|
||||
|
||||
The output, in this case, would be:
|
||||
|
||||
```
|
||||
+-----------------+----------+
|
||||
| COUNT(username) | username |
|
||||
+-----------------+----------+
|
||||
| 2 | bobby |
|
||||
| 2 | devdojo |
|
||||
| 2 | tony |
|
||||
+-----------------+----------+
|
||||
```
|
||||
|
||||
The `GROUP BY` statement grouped the identical usernames. Then it ran a `COUNT` on each of `bobby`, `tony` and `devdojo`.
|
||||
|
||||
The main thing to remember here is that the `GROUP BY` should be added after the `FROM` clause and after the `WHERE` clause.
|
||||
|
||||
## HAVING Clause
|
||||
|
||||
The `HAVING` clause allows you to filter out the results on the groups formed by the `GROUP BY` clause.
|
||||
|
||||
For example, let's say that we wanted to get all usernames that are duplicates, i.e., all the usernames present in more than one table record.
|
||||
|
||||
In our case, we have two users with the username `bobby`, two users with the username `tony`, and two users with username `devdojo`. This represented in an SQL statement would look like this:
|
||||
|
||||
```sql
|
||||
SELECT COUNT(username), username
|
||||
FROM users
|
||||
GROUP BY username
|
||||
HAVING COUNT(username) > 1;
|
||||
```
|
||||
|
||||
The output, in this case, would be:
|
||||
|
||||
```
|
||||
+-----------------+----------+
|
||||
| COUNT(username) | username |
|
||||
+-----------------+----------+
|
||||
| 2 | bobby |
|
||||
| 2 | devdojo |
|
||||
| 2 | tony |
|
||||
+-----------------+----------+
|
||||
```
|
||||
|
||||
The `GROUP BY` clause grouped the identical usernames, calculated their counts and filtered out the groups using the `HAVING` clause.
|
||||
|
||||
> **NOTE**:- _The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups created by the GROUP BY clause._
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
# UPDATE
|
||||
|
||||
As the name suggests, whenever you have to update some data in your database, you would use the `UPDATE` statement.
|
||||
|
||||
You can use the `UPDATE` statement to update multiple columns in a single table.
|
||||
|
||||
The syntax would look like this:
|
||||
|
||||
```sql
|
||||
UPDATE users SET username='bobbyiliev' WHERE id=1;
|
||||
```
|
||||
|
||||
Rundown of the statement:
|
||||
|
||||
* `UPDATE users`: First, we specify the `UPDATE` keyword followed by the table that we want to update.
|
||||
* `username='bobbyiliev'`: Then we specify the columns that we want to update and the new value that we want to set.
|
||||
* `WHERE id=1`: Finally, by using the `WHERE` clause, we specify which user should be updated. In our case, it is the user with ID 1.
|
||||
|
||||
The most important thing that you need to keep in mind is that if you don't specify a `WHERE` clause, all of the entries inside the `users` table would be updated, and all users would have the `username` set to `bobbyiliev`.
|
||||
|
||||
> Important: You need to be careful when you use the `UPDATE` statement without a `WHERE` clause as every single row will be updated.
|
||||
|
||||
If you have been following along all of the user entries in our `users` table, it currently have no data in the `about` column:
|
||||
|
||||
```
|
||||
+----+----------+-------+
|
||||
| id | username | about |
|
||||
+----+----------+-------+
|
||||
| 2 | bobby | NULL |
|
||||
| 3 | devdojo | NULL |
|
||||
| 4 | tony | NULL |
|
||||
| 5 | bobby | NULL |
|
||||
| 6 | devdojo | NULL |
|
||||
| 7 | tony | NULL |
|
||||
+----+----------+-------+
|
||||
```
|
||||
|
||||
Let's go ahead and update this for all users and set the column value to `404 bio not found`, For example:
|
||||
|
||||
```sql
|
||||
UPDATE users SET about='404 bio not found';
|
||||
```
|
||||
|
||||
The output would let you know how many rows have been affected by the query:
|
||||
|
||||
```
|
||||
Query OK, 6 rows affected (0.02 sec)
|
||||
Rows matched: 6 Changed: 6 Warnings: 0
|
||||
```
|
||||
|
||||
Now, if you were to run a select for all `users`, you would get the following result:
|
||||
|
||||
```
|
||||
+----+----------+-------------------+
|
||||
| id | username | about |
|
||||
+----+----------+-------------------+
|
||||
| 2 | bobby | 404 bio not found |
|
||||
| 3 | devdojo | 404 bio not found |
|
||||
| 4 | tony | 404 bio not found |
|
||||
| 5 | bobby | 404 bio not found |
|
||||
| 6 | devdojo | 404 bio not found |
|
||||
| 7 | tony | 404 bio not found |
|
||||
+----+----------+-------------------+
|
||||
```
|
||||
|
||||
Let's now say that we wanted to update the `about` column for the user with an id of 2. In this case, we need to specify a `WHERE` clause followed by the ID of the user that we want to update as follows:
|
||||
|
||||
```sql
|
||||
UPDATE users SET about='Hello World :)' WHERE id=2;
|
||||
```
|
||||
|
||||
The output here should indicate that only 1 row was updated:
|
||||
|
||||
```
|
||||
Query OK, 1 row affected (0.01 sec)
|
||||
Rows matched: 1 Changed: 1 Warnings: 0
|
||||
```
|
||||
|
||||
Now, if you again run the `SELECT id, username, about FROM users` query, you would see that the user with `id` of 2 now has an updated `about` column data:
|
||||
|
||||
```
|
||||
+----+----------+-------------------+
|
||||
| id | username | about |
|
||||
+----+----------+-------------------+
|
||||
| 2 | bobby | Hello World :) |
|
||||
| 3 | devdojo | 404 bio not found |
|
||||
| 4 | tony | 404 bio not found |
|
||||
| 5 | bobby | 404 bio not found |
|
||||
| 6 | devdojo | 404 bio not found |
|
||||
| 7 | tony | 404 bio not found |
|
||||
+----+----------+-------------------+
|
||||
```
|
||||
|
||||
## Updating records using another table
|
||||
|
||||
As we've seen in the previous section, you can insert multiple rows in your table using another table. You can use the same principle for the update command.
|
||||
|
||||
To do that you simply have to list all needed table in the `update` section, then you have to explain which action you want to perform on the table, and then you need to link the table together.
|
||||
|
||||
For example, if you want to update the `about` field in the `users` table using the content of the `about` field in the `prospect_users` table, you would do something like this:
|
||||
|
||||
```sql
|
||||
update users, prospect_users
|
||||
set users.about = prospect_users.about
|
||||
where prospect_users.username = users.username;
|
||||
```
|
||||
@@ -1,41 +0,0 @@
|
||||
# DELETE
|
||||
|
||||
As the name suggests, the `DELETE` statement would remove data from your database.
|
||||
|
||||
The syntax is as follows:
|
||||
|
||||
```sql
|
||||
DELETE FROM users WHERE id=5;
|
||||
```
|
||||
|
||||
The output should indicate that 1 row was affected:
|
||||
|
||||
```
|
||||
Query OK, 1 row affected (0.01 sec)
|
||||
```
|
||||
|
||||
> Important: Just like the `UPDATE` statement, if you don't specify a `WHERE` clause, all of the entries from the table will be affected, meaning that all of your users will be deleted. So, it is critical to always add a `WHERE` clause when executing a `DELETE` statement.
|
||||
|
||||
```sql
|
||||
DELETE FROM users;
|
||||
```
|
||||
|
||||
The output should indicate (where x is the number of tuples in the table):
|
||||
```
|
||||
Query OK, x row(s) affected (0.047 sec)
|
||||
```
|
||||
|
||||
Similar to the Linux `rm` command, when you use the `DELETE` statement, the data would be gone permanently, and the only way to recover your data would be by restoring a backup.
|
||||
|
||||
## Delete from another table
|
||||
|
||||
As we saw in the two precedents sections you can `INSERT` or `UPDPATE` tables rows based on other table data. You can do the same for the `DELETE`.
|
||||
|
||||
For example, if you want to delete the records from the `users` table if the corresponding prospect has been disabled, you could do it this way:
|
||||
|
||||
```sql
|
||||
delete users
|
||||
from users, prospect_users
|
||||
where users.username = prospect_users.username
|
||||
and NOT prospect_users.active
|
||||
```
|
||||
@@ -1,370 +0,0 @@
|
||||
# JOIN
|
||||
|
||||
The `JOIN` clause allows you to combine the data from 2 or more tables into one result set.
|
||||
|
||||
As we will be selecting from multiple columns, we need to include the list of the columns we want to choose data from after the `FROM` clause is separated by a comma.
|
||||
|
||||
In this chapter, we will go over the following `JOIN` types:
|
||||
|
||||
* `CROSS` Join
|
||||
* `INNER` Join
|
||||
* `LEFT` Join
|
||||
* `RIGHT` Join
|
||||
|
||||
Before we get started, let's create a new database and two tables that we are going to work with:
|
||||
|
||||
* We are going to call the database `demo_joins`:
|
||||
|
||||
```sql
|
||||
CREATE DATABASE demo_joins;
|
||||
```
|
||||
|
||||
* Then, switch to the new database:
|
||||
|
||||
```sql
|
||||
USE demo_joins;
|
||||
```
|
||||
|
||||
* Then, the first table will be called `users`, and it will only have two columns: `id` and `username`:
|
||||
|
||||
```sql
|
||||
CREATE TABLE users
|
||||
(
|
||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
username VARCHAR(255) NOT NULL
|
||||
);
|
||||
```
|
||||
|
||||
* Then, let's create a second table called `posts`, and to keep things simple, we will have three two columns: `id`, `user_id` and `title`:
|
||||
|
||||
```sql
|
||||
CREATE TABLE posts
|
||||
(
|
||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
user_id INT,
|
||||
title VARCHAR(255) NOT NULL
|
||||
);
|
||||
```
|
||||
|
||||
> The `user_id` column would be used to reference the user's ID that the post belongs to. It is going to be a one to many relations, e.g. one user could have many posts:
|
||||
|
||||

|
||||
|
||||
* Now, let's add some data into the two tables first by creating a few users:
|
||||
|
||||
```sql
|
||||
INSERT INTO users
|
||||
( username )
|
||||
VALUES
|
||||
('bobby'),
|
||||
('devdojo'),
|
||||
('tony'),
|
||||
('greisi');
|
||||
```
|
||||
|
||||
* And finally add some posts:
|
||||
|
||||
```sql
|
||||
INSERT INTO posts
|
||||
( user_id, title )
|
||||
VALUES
|
||||
('1', 'Hello World!'),
|
||||
('2', 'Getting started with SQL'),
|
||||
('3', 'SQL is awesome'),
|
||||
('2', 'MySQL is up!'),
|
||||
('1', 'SQL - structured query language');
|
||||
```
|
||||
|
||||
Now that we've got our tables and demo data ready, let's go ahead and learn how to use joins.
|
||||
|
||||
## CROSS JOIN
|
||||
|
||||
The `CROSS` join allows you to put the result of two tables next to each other without specifying any `WHERE` conditions. This makes the `CROSS` join the simplest one, but it is also not of much use in a real-life scenario.
|
||||
|
||||
So if we were to select all of the users and all of the posts side by side, we would use the following query:
|
||||
|
||||
```sql
|
||||
SELECT * FROM users CROSS JOIN posts;
|
||||
```
|
||||
|
||||
The output will be all of your users and all of the posts side by side:
|
||||
|
||||
```
|
||||
+----+----------+----+--------+-----------------+
|
||||
| id | username | id |user_id | title |
|
||||
+----+----------+----+--------+-----------------+
|
||||
| 4 | greisi | 1 | 1 | Hello World! |
|
||||
| 3 | tony | 1 | 1 | Hello World! |
|
||||
| 2 | devdojo | 1 | 1 | Hello World! |
|
||||
| 1 | bobby | 1 | 1 | Hello World! |
|
||||
| 4 | greisi | 2 | 2 | Getting started |
|
||||
| 3 | tony | 2 | 2 | Getting started |
|
||||
| 2 | devdojo | 2 | 2 | Getting started |
|
||||
| 1 | bobby | 2 | 2 | Getting started |
|
||||
| 4 | greisi | 3 | 3 | SQL is awesome |
|
||||
| 3 | tony | 3 | 3 | SQL is awesome |
|
||||
| 2 | devdojo | 3 | 3 | SQL is awesome |
|
||||
| 1 | bobby | 3 | 3 | SQL is awesome |
|
||||
| 4 | greisi | 4 | 2 | MySQL is up! |
|
||||
| 3 | tony | 4 | 2 | MySQL is up! |
|
||||
| 2 | devdojo | 4 | 2 | MySQL is up! |
|
||||
| 1 | bobby | 4 | 2 | MySQL is up! |
|
||||
| 4 | greisi | 5 | 1 | SQL |
|
||||
| 3 | tony | 5 | 1 | SQL |
|
||||
| 2 | devdojo | 5 | 1 | SQL |
|
||||
| 1 | bobby | 5 | 1 | SQL |
|
||||
+----+----------+----+--------+-----------------+
|
||||
```
|
||||
|
||||
As mentioned above, you will highly unlikely run a `CROSS` join for two whole tables in a real-life scenario. If the tables have tens of thousands of rows, an unqualified CROSS JOIN can take minutes to complete.
|
||||
|
||||
You would most likely use one of the following with a specific condition.
|
||||
|
||||
In MySQL, CROSS JOIN and INNER JOIN are equivalent to JOIN.
|
||||
|
||||
## INNER JOIN
|
||||
|
||||
The `INNER` join is used to join two tables. However, unlike the `CROSS` join, by convention, it is based on a condition. By using an `INNER` join, you can match the first table to the second one.
|
||||
|
||||
As we have a one-to-many relationship, a best practice would be to use a primary key for the posts `id` column and a foreign key for the `user_id`; that way, we can 'link' or relate the users table to the posts table. However, this is beyond the scope of this SQL basics eBook, though I might extend it in the future and add more chapters.
|
||||
|
||||
As an example and to make things a bit clearer, let's say that you wanted to get all of your users and the posts associated with each user. The query that we would use will look like this:
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM users
|
||||
INNER JOIN posts
|
||||
ON users.id = posts.user_id;
|
||||
```
|
||||
|
||||
Rundown of the query:
|
||||
|
||||
* `SELECT * FROM users`: This is a standard select we've covered many times in the previous chapters.
|
||||
* `INNER JOIN posts`: Then, we specify the second table and which table we want to join the result set.
|
||||
* `ON users.id = posts.user_id`: Finally, we specify how we want the data in these two tables to be merged. The `user.id` is the `id` column of the `user` table, which is also the primary ID, and `posts.user_id` is the foreign key in the email address table referring to the ID column in the users table.
|
||||
|
||||
The output will be the following, associating each user with their post based on the `user_id` column:
|
||||
|
||||
```
|
||||
+----+----------+----+---------+-----------------+
|
||||
| id | username | id | user_id | title |
|
||||
+----+----------+----+---------+-----------------+
|
||||
| 1 | bobby | 1 | 1 | Hello World! |
|
||||
| 2 | devdojo | 2 | 2 | Getting started |
|
||||
| 3 | tony | 3 | 3 | SQL is awesome |
|
||||
| 2 | devdojo | 4 | 2 | MySQL is up! |
|
||||
| 1 | bobby | 5 | 1 | SQL |
|
||||
+----+----------+----+---------+-----------------+
|
||||
```
|
||||
Note that the INNER JOIN could (in MySQL) equivalently be written merely as JOIN, but that can vary for other SQL dialects:
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM users
|
||||
JOIN posts
|
||||
ON users.id = posts.user_id;
|
||||
```
|
||||
|
||||
The main things that you need to keep in mind here are the `INNER JOIN` and `ON` clauses.
|
||||
|
||||
With the inner join, the `NULL` values are discarded. For example, if you have a user who does not have a post associated with it, the user with NULL posts will not be displayed when running the above `INNER` join query.
|
||||
|
||||
To get the null values as well, you would need to use an outer join.
|
||||
|
||||
### Types of INNER JOIN
|
||||
|
||||
1. **Theta Join ( θ )** :- Theta join combines rows from different tables provided they satisfy the theta condition.
|
||||
The join condition is denoted by the symbol `θ`. \
|
||||
Here the comparison operators `(≤, ≥, ˂, ˃, =, ̚ )` come into picture. \
|
||||
**Notation** :- R<sub>1</sub> ⋈<sub>θ</sub> R<sub>2</sub>. \
|
||||
\
|
||||
For example, suppose we want to buy a mobile and a laptop, based on our budget we have thought of buying both such that mobile price should be less than that of laptop. \
|
||||
\
|
||||
`SELECT mobile.model, laptop.model
|
||||
FROM mobile, laptop
|
||||
WHERE mobile.price < laptop.price;`
|
||||
|
||||
2. **Equijoin** :- When Theta join uses only equality (=) comparison operator, it is said to be equijoin. \
|
||||
For example, suppose we want to buy a mobile and a laptop, based on our budget we have thought of buying both of the same prices. \
|
||||
\
|
||||
`SELECT mobile.model, laptop.model
|
||||
FROM mobile, laptop
|
||||
WHERE mobile.price = laptop.price;`
|
||||
|
||||
3. **Natural Join ( ⋈ )** :- Natural join does not use any comparison operator. It does not concatenate the way a Cartesian product does. \
|
||||
We can perform a Natural Join only if at least one standard column exists between two tables. In addition, the column must have the same name and domain. \
|
||||
\
|
||||
`SELECT * FROM mobile NATURAL JOIN laptop;`
|
||||
|
||||
|
||||
## LEFT JOIN
|
||||
|
||||
Using the `LEFT OUTER` join, you would get all rows from the first table that you've specified, and if there are no associated records within the second table, you will get a `NULL` value.
|
||||
|
||||
In our case, we have a user called `graisi`, which is not associated with a specific post. As you can see from the output from the previous query, the `graisi` user was not present there. To show that user, even though it does not have an associated post with it, you could use a `LEFT OUTER` join:
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM users
|
||||
LEFT JOIN posts
|
||||
ON users.id = posts.user_id;
|
||||
```
|
||||
|
||||
The output will look like this:
|
||||
|
||||
```
|
||||
+----+----------+------+---------+-----------------+
|
||||
| id | username | id | user_id | title |
|
||||
+----+----------+------+---------+-----------------+
|
||||
| 1 | bobby | 1 | 1 | Hello World! |
|
||||
| 2 | devdojo | 2 | 2 | Getting started |
|
||||
| 3 | tony | 3 | 3 | SQL is awesome |
|
||||
| 2 | devdojo | 4 | 2 | MySQL is up! |
|
||||
| 1 | bobby | 5 | 1 | SQL |
|
||||
| 4 | greisi | NULL | NULL | NULL |
|
||||
+----+----------+------+---------+-----------------+
|
||||
```
|
||||
|
||||
## RIGHT JOIN
|
||||
|
||||
The `RIGHT OUTER` join is the exact opposite of the `LEFT OUTER` join. It will display all of the rows from the second table and give you a `NULL` value in case that it does not match with an entry from the first table.
|
||||
|
||||
Let's create a post that does not have a matching user id:
|
||||
|
||||
```sql
|
||||
INSERT INTO posts
|
||||
( user_id, title )
|
||||
VALUES
|
||||
('123', 'No user post!');
|
||||
```
|
||||
|
||||
We specify `123` as the user ID, but we don't have such a user in our `users` table.
|
||||
|
||||
Now, if you were to run the `LEFT` outer join, you would not see the post as it has a null value for the corresponding `users` table.
|
||||
|
||||
But if you were to run a `RIGHT` outer join, you would see the post but not the `greisi` user as it does not have any posts:
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM users
|
||||
RIGHT JOIN posts
|
||||
ON users.id = posts.user_id;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+------+----------+----+---------+-----------------+
|
||||
| id | username | id | user_id | title |
|
||||
+------+----------+----+---------+-----------------+
|
||||
| 1 | bobby | 1 | 1 | Hello World! |
|
||||
| 2 | devdojo | 2 | 2 | Getting started |
|
||||
| 3 | tony | 3 | 3 | SQL is awesome |
|
||||
| 2 | devdojo | 4 | 2 | MySQL is up! |
|
||||
| 1 | bobby | 5 | 1 | SQL |
|
||||
| NULL | NULL | 6 | 123 | No user post! |
|
||||
+------+----------+----+---------+-----------------+
|
||||
```
|
||||
|
||||
Joins can also be limited with WHERE conditions. For instance, in the preceding example, if we wanted to join the tables and then restrict to only username `bobby`.
|
||||
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM users
|
||||
RIGHT JOIN posts
|
||||
ON users.id = posts.user_id
|
||||
WHERE username = 'bobby';
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
+------+----------+----+---------+-----------------+
|
||||
| id | username | id | user_id | title |
|
||||
+------+----------+----+---------+-----------------+
|
||||
| 1 | bobby | 1 | 1 | Hello World! |
|
||||
| 1 | bobby | 5 | 1 | SQL |
|
||||
+------+----------+----+---------+-----------------+
|
||||
```
|
||||
|
||||
## The Impact of Conditions in JOIN vs. WHERE Clauses
|
||||
|
||||
The placement of conditions within a SQL query, specifically in the `JOIN` vs. the `WHERE` clause, can yield different results.
|
||||
|
||||
Take a look at the following example, which retrieves `POSTS` containing the word "SQL" along with their associated user data:
|
||||
|
||||
```sql
|
||||
SELECT users.*, posts.*
|
||||
FROM users
|
||||
LEFT JOIN posts
|
||||
ON posts.user_id = users.id
|
||||
WHERE posts.title LIKE '%SQL%';
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```sql
|
||||
+--+--------+--+-------+-------------------------------+
|
||||
|id|username|id|user_id|title |
|
||||
+--+--------+--+-------+-------------------------------+
|
||||
|2 |devdojo |2 |2 |Getting started with SQL |
|
||||
|3 |tony |3 |3 |SQL is awesome |
|
||||
|2 |devdojo |4 |2 |MySQL is up! |
|
||||
|1 |bobby |5 |1 |SQL - structured query language|
|
||||
+--+--------+--+-------+-------------------------------+
|
||||
```
|
||||
|
||||
However, by shifting the condition to the `JOIN` clause, all users are displayed, but only posts with titles containing "SQL" are included:
|
||||
|
||||
```sql
|
||||
SELECT users.*, posts.*
|
||||
FROM users
|
||||
LEFT JOIN posts
|
||||
ON posts.user_id = users.id
|
||||
AND posts.title LIKE '%SQL%';
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```sql
|
||||
+--+--------+----+-------+-------------------------------+
|
||||
|id|username|id |user_id|title |
|
||||
+--+--------+----+-------+-------------------------------+
|
||||
|1 |bobby |5 |1 |SQL - structured query language|
|
||||
|2 |devdojo |4 |2 |MySQL is up! |
|
||||
|2 |devdojo |2 |2 |Getting started with SQL |
|
||||
|3 |tony |3 |3 |SQL is awesome |
|
||||
|4 |greisi |null|null |null |
|
||||
+--+--------+----+-------+-------------------------------+
|
||||
```
|
||||
|
||||
## Equivalence of RIGHT and LEFT JOINs
|
||||
|
||||
The `RIGHT JOIN` and `LEFT JOIN` operations in SQL are fundamentally equivalent. They can be interchanged by simply swapping the tables involved. Here's an illustration:
|
||||
|
||||
The following `LEFT JOIN`:
|
||||
|
||||
```sql
|
||||
SELECT users.*, posts.*
|
||||
FROM posts
|
||||
LEFT JOIN users
|
||||
ON posts.user_id = users.id;
|
||||
```
|
||||
|
||||
Can be equivalently written using `RIGHT JOIN` as:
|
||||
|
||||
```sql
|
||||
SELECT users.*, posts.*
|
||||
FROM users
|
||||
RIGHT JOIN posts
|
||||
ON posts.user_id = users.id;
|
||||
```
|
||||
|
||||
## Conclusion
|
||||
|
||||
Joins are fundamental to using SQL with data. The whole concept of joins might be very confusing initially but would make a lot of sense once you get used to it.
|
||||
|
||||
The best way to wrap your head around it is to write some queries, play around with each type of `JOIN`, and see how the result set changes.
|
||||
|
||||
For more information, you could take a look at the official documentation [here](https://dev.mysql.com/doc/refman/8.0/en/join.html).
|
||||
@@ -1,121 +0,0 @@
|
||||
# SQL | DDL, DQL, DML, DCL and TCL Commands
|
||||
Structured Query Language(SQL), as we all know, is the database language by which we can perform certain operations on the existing database. Also, we can use this language to create a database. SQL uses specific commands like Create, Drop, Insert, etc., to carry out the required tasks.
|
||||
1. **DDL** – Data Definition Language
|
||||
2. **DQL** – Data Query Language
|
||||
3. **DML** – Data Manipulation Language
|
||||
4. **DCL** – Data Control Language
|
||||
|
||||
#### Though many resources claim there to be another category of SQL clauses TCL – Transaction Control Language, so we will see in detail about TCL as well.
|
||||

|
||||
|
||||
### DDL (Data Definition Language):
|
||||
DDL or Data Definition Language consists of the SQL commands used to define the database schema. It simply deals with descriptions of the database schema and is used to create and modify the structure of database objects in the database. These commands usually are not used by a general user, who should be accessing the database via an application.
|
||||
|
||||
#### List of DDL commands:
|
||||
- `CREATE`: This command is used to create the database or its objects (like table, index, function, views, store procedure, and triggers).
|
||||
```sql
|
||||
CREATE TABLE Persons (
|
||||
PersonID int,
|
||||
LastName varchar(255),
|
||||
FirstName varchar(255),
|
||||
Address varchar(255),
|
||||
City varchar(255)
|
||||
);
|
||||
```
|
||||
- `DROP`: This command is used to delete objects from the database.
|
||||
|
||||
```sql
|
||||
DROP TABLE table_name;
|
||||
```
|
||||
- `ALTER`: This is used to alter the structure of the database.
|
||||
```sql
|
||||
ALTER TABLE Persons
|
||||
ADD Age int;
|
||||
```
|
||||
- `TRUNCATE`: This is used to remove all records from a table, including all spaces allocated for the records.
|
||||
```sql
|
||||
TRUNCATE TABLE Persons;
|
||||
```
|
||||
- `COMMENT`: This is used to add comments to the data dictionary.
|
||||
```sql
|
||||
--SELECT * FROM Customers;
|
||||
SELECT * FROM Persons;
|
||||
```
|
||||
-` RENAME`: This is used to rename an object existing in the database.
|
||||
```sql
|
||||
ALTER TABLE Persons
|
||||
RENAME COLUMN Age TO Year;
|
||||
```
|
||||
|
||||
#### DQL (Data Query Language):
|
||||
**DQL** statements are used for performing queries on the data within schema objects. The purpose of the DQL Command is to get some schema relation based on the query passed to it. We can define DQL as follows. It is a component of the SQL statement that allows getting data from the database and imposing order upon it. It includes the SELECT statement. This command allows getting the data out of the database to perform operations with it. When a SELECT is fired against a table(s), the result is compiled into a different temporary table, which is displayed or perhaps received by the program, i.e. a front-end.
|
||||
|
||||
#### List of DQL:
|
||||
`SELECT`: It is used to retrieve data from the database.
|
||||
```sql
|
||||
SELECT * FROM table_name;
|
||||
```
|
||||
```
|
||||
+--------+--------------+------------+--------+---------+
|
||||
| emp_id | emp_name | hire_date | salary | dept_id |
|
||||
+--------+--------------+------------+--------+---------+
|
||||
| 1 | Ethan Hunt | 2001-05-01 | 5000 | 4 |
|
||||
| 2 | Tony Montana | 2002-07-15 | 6500 | 1 |
|
||||
| 3 | Sarah Connor | 2005-10-18 | 8000 | 5 |
|
||||
| 4 | Rick Deckard | 2007-01-03 | 7200 | 3 |
|
||||
| 5 | Martin Blank | 2008-06-24 | 5600 | NULL |
|
||||
+--------+--------------+------------+--------+---------+
|
||||
```
|
||||
The SQL commands that deal with the manipulation of data present in the database belong to DML or Data Manipulation Language, including most of the SQL statements. It is the component of the SQL statement that controls access to data and the database. DCL statements are grouped with DML statements.
|
||||
|
||||
#### List of DML commands:
|
||||
- `INSERT `: It is used to insert data into a table.
|
||||
```sql
|
||||
INSERT INTO Customers
|
||||
(CustomerName, ContactName, Address, City, PostalCode, Country)
|
||||
VALUES
|
||||
('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
|
||||
```
|
||||
- `UPDATE`: It is used to update existing data within a table.
|
||||
|
||||
```sql
|
||||
UPDATE Customers
|
||||
SET ContactName='Alfred Schmidt', City='Frankfurt'
|
||||
WHERE CustomerID = 1;
|
||||
```
|
||||
- `DELETE `: It is used to delete records from a database table.
|
||||
```sql
|
||||
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
|
||||
```
|
||||
- `LOCK`: Table control concurrency.
|
||||
```sql
|
||||
LOCK TABLES table_name [READ | WRITE]
|
||||
--------------------------------------
|
||||
UNLOCK TABLES;
|
||||
```
|
||||
- `CALL`: Call a PL/SQL or JAVA subprogram.
|
||||
```sql
|
||||
CREATE PROCEDURE procedure_name
|
||||
AS sql_statement
|
||||
GO;
|
||||
```
|
||||
#### Execute a Stored Procedure
|
||||
```sql
|
||||
EXEC procedure_name;
|
||||
```
|
||||
- `EXPLAIN PLAN`: It describes the access path to data.
|
||||
|
||||
#### DCL (Data Control Language):
|
||||
DCL includes commands such as GRANT and REVOKE, which mainly deal with the database system's rights, permissions, and other controls.
|
||||
|
||||
##### List of DCL commands:
|
||||
- `GRANT`: This command gives users access privileges to the database.
|
||||
- `REVOKE`: This command withdraws the user’s access privileges given by using the GRANT command.
|
||||
|
||||
Though many resources claim there to be another category of SQL clauses TCL – Transaction Control Language, we will see in detail about TCL. TCL commands deal with the transaction within the database.
|
||||
|
||||
##### List of TCL commands:
|
||||
- `COMMIT`: Commits a Transaction.
|
||||
- `ROLLBACK`: Rollbacks a transaction in case of any error occurs.
|
||||
- `SAVEPOINT`:Sets a savepoint within a transaction.
|
||||
- `SET TRANSACTION`: Specify characteristics for the transaction.
|
||||
@@ -1,112 +0,0 @@
|
||||
# SQL Sub Queries
|
||||
|
||||
### A subquery is a SQL query nested inside a larger query.
|
||||
|
||||
- A subquery may occur in
|
||||
- A SELECT clause
|
||||
- A FROM clause
|
||||
- A WHERE clause
|
||||
|
||||
- The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside another subquery.
|
||||
- A subquery is usually added within the WHERE Clause of another SQL SELECT statement.
|
||||
- The inner query executes first before its parent query so that the results of an inner query can be passed to the outer query.
|
||||
|
||||
#### You can use a subquery in a SELECT, INSERT, DELETE, or UPDATE statement to perform the following tasks:
|
||||
- Compare an expression to the result of the query.
|
||||
- Determine if an expression is included in the results of the query.
|
||||
- Check whether the query selects any rows.
|
||||
|
||||
**_Subqueries with the `SELECT` Statement_**:
|
||||
|
||||
Consider the CUSTOMERS table having the following records
|
||||
|
||||
+----+----------+-----+-----------+----------+
|
||||
| ID | NAME | AGE | ADDRESS | SALARY |
|
||||
+----+----------+-----+-----------+----------+
|
||||
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
|
||||
| 2 | Khilan | 25 | Delhi | 1500.00 |
|
||||
| 3 | Kaushik | 23 | Kota | 2000.00 |
|
||||
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
|
||||
| 5 | Hardik | 27 | Bhopal | 8500.00 |
|
||||
| 6 | Komal | 22 | MP | 4500.00 |
|
||||
| 7 | Muffy | 24 | Indore | 10000.00 |
|
||||
+----+----------+-----+-----------+----------+
|
||||
Now, let us check the following subquery with a SELECT statement.
|
||||
|
||||
_**Example**_:
|
||||
```sql
|
||||
SELECT *
|
||||
FROM CUSTOMERS
|
||||
WHERE ID IN (
|
||||
SELECT ID
|
||||
FROM CUSTOMERS
|
||||
WHERE SALARY > 4500
|
||||
);
|
||||
```
|
||||
This would produce the following result.
|
||||
|
||||
+----+----------+-----+---------+----------+
|
||||
| ID | NAME | AGE | ADDRESS | SALARY |
|
||||
+----+----------+-----+---------+----------+
|
||||
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
|
||||
| 5 | Hardik | 27 | Bhopal | 8500.00 |
|
||||
| 7 | Muffy | 24 | Indore | 10000.00 |
|
||||
+----+----------+-----+---------+----------+
|
||||
|
||||
|
||||
**_Subqueries with the `UPDATE` Statement_**:
|
||||
|
||||
The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement.
|
||||
|
||||
**_Example_**:
|
||||
|
||||
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table. The following example updates SALARY by 0.25 times in the CUSTOMERS table for all the customers whose AGE is greater than or equal to 27.
|
||||
```sql
|
||||
UPDATE CUSTOMERS
|
||||
SET SALARY = SALARY * 0.25
|
||||
WHERE AGE IN (
|
||||
SELECT AGE
|
||||
FROM CUSTOMERS_BKP
|
||||
WHERE AGE >= 27
|
||||
);
|
||||
```
|
||||
This would impact two rows and finally CUSTOMERS table would have the following records.
|
||||
|
||||
+----+----------+-----+-----------+----------+
|
||||
| ID | NAME | AGE | ADDRESS | SALARY |
|
||||
+----+----------+-----+-----------+----------+
|
||||
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
|
||||
| 2 | Khilan | 25 | Delhi | 1500.00 |
|
||||
| 3 | Kaushik | 23 | Kota | 2000.00 |
|
||||
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
|
||||
| 5 | Hardik | 27 | Bhopal | 2125.00 |
|
||||
| 6 | Komal | 22 | MP | 4500.00 |
|
||||
| 7 | Muffy | 24 | Indore | 10000.00 |
|
||||
+----+----------+-----+-----------+----------+
|
||||
|
||||
**_Subqueries with the `DELETE` Statement_**:
|
||||
|
||||
The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above.
|
||||
|
||||
**_Example_**:
|
||||
|
||||
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the CUSTOMERS table. The following example deletes the records from the CUSTOMERS table for all the customers whose AGE is greater than or equal to 27.
|
||||
```sql
|
||||
DELETE FROM CUSTOMERS
|
||||
WHERE AGE IN (
|
||||
SELECT AGE
|
||||
FROM CUSTOMERS_BKP
|
||||
WHERE AGE >= 27
|
||||
);
|
||||
```
|
||||
This would impact two rows and finally the CUSTOMERS table would have the following records.
|
||||
|
||||
+----+----------+-----+---------+----------+
|
||||
| ID | NAME | AGE | ADDRESS | SALARY |
|
||||
+----+----------+-----+---------+----------+
|
||||
| 2 | Khilan | 25 | Delhi | 1500.00 |
|
||||
| 3 | Kaushik | 23 | Kota | 2000.00 |
|
||||
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
|
||||
| 6 | Komal | 22 | MP | 4500.00 |
|
||||
| 7 | Muffy | 24 | Indore | 10000.00 |
|
||||
+----+----------+-----+---------+----------+
|
||||
@@ -1,124 +0,0 @@
|
||||
# SQL - UNIONS CLAUSE
|
||||
|
||||
The SQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows.
|
||||
|
||||
- While using this UNION clause, each SELECT statement must have:
|
||||
|
||||
- The same number of columns selected
|
||||
- The same number of column expressions
|
||||
- The same data type and
|
||||
- Have them in the same order
|
||||
|
||||
But they need not have to be in the same length.
|
||||
|
||||
_Example_
|
||||
|
||||
Consider the following two tables.
|
||||
|
||||
Table 1 − customers table is as follows:
|
||||
|
||||
+----+----------+-----+-----------+----------+
|
||||
| id | name | age | address | salary |
|
||||
+----+----------+-----+-----------+----------+
|
||||
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
|
||||
| 2 | Khilan | 25 | Delhi | 1500.00 |
|
||||
| 3 | kaushik | 23 | Kota | 2000.00 |
|
||||
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
|
||||
| 5 | Hardik | 27 | Bhopal | 8500.00 |
|
||||
| 6 | Komal | 22 | MP | 4500.00 |
|
||||
| 7 | Muffy | 24 | Indore | 10000.00 |
|
||||
+----+----------+-----+-----------+----------+
|
||||
|
||||
Table 2 − orders table is as follows:
|
||||
|
||||
+-----+---------------------+-------------+--------+
|
||||
| oid | date | customer_id | amount |
|
||||
+-----+---------------------+-------------+--------+
|
||||
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
|
||||
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
|
||||
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
|
||||
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
|
||||
+-----+---------------------+-------------+--------+
|
||||
|
||||
Now, let us join these two tables in our SELECT statement as follows:
|
||||
|
||||
```sql
|
||||
SELECT id, name, amount, date
|
||||
FROM customer
|
||||
LEFT JOIN orders
|
||||
ON customers.id = orders.customer_id
|
||||
UNION
|
||||
SELECT id, name, amount, date
|
||||
FROM customer
|
||||
RIGHT JOIN orders
|
||||
ON customers.id = orders.customer_id
|
||||
```
|
||||
|
||||
This would produce the following result:
|
||||
|
||||
### The UNION ALL Clause
|
||||
The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows.
|
||||
|
||||
The same rules that apply to the UNION clause will apply to the UNION ALL operator.
|
||||
|
||||
_Example_ -
|
||||
Consider the following two tables:
|
||||
|
||||
* Table 1 − customers table is as follows:
|
||||
|
||||
+----+----------+-----+-----------+----------+
|
||||
| id | name | age | address | salary |
|
||||
+----+----------+-----+-----------+----------+
|
||||
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
|
||||
| 2 | Khilan | 25 | Delhi | 1500.00 |
|
||||
| 3 | kaushik | 23 | Kota | 2000.00 |
|
||||
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
|
||||
| 5 | Hardik | 27 | Bhopal | 8500.00 |
|
||||
| 6 | Komal | 22 | MP | 4500.00 |
|
||||
| 7 | Muffy | 24 | Indore | 10000.00 |
|
||||
+----+----------+-----+-----------+----------+
|
||||
|
||||
* Table 2 − orders table is as follows:
|
||||
|
||||
+-----+---------------------+-------------+--------+
|
||||
| oid | date | customer_id | amount |
|
||||
+-----+---------------------+-------------+--------+
|
||||
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
|
||||
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
|
||||
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
|
||||
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
|
||||
+-----+---------------------+-------------+--------+
|
||||
|
||||
Now, let us join these two tables in our SELECT statement as follows :
|
||||
```sql
|
||||
SELECT id, name, amount, date
|
||||
FROM customers
|
||||
LEFT JOIN orders
|
||||
ON customers.id = order.customer_id
|
||||
UNION ALL
|
||||
SELECT id, name, amount, date
|
||||
FROM customers
|
||||
RIGHT JOIN orders
|
||||
ON customers.id = orders.customer_id;
|
||||
```
|
||||
|
||||
This would produce the following result:
|
||||
|
||||
+------+----------+--------+---------------------+
|
||||
| id | name | amount | date |
|
||||
+------+----------+--------+---------------------+
|
||||
| 1 | Ramesh | NULL | NULL |
|
||||
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
|
||||
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
|
||||
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
|
||||
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
|
||||
| 5 | Hardik | NULL | NULL |
|
||||
| 6 | Komal | NULL | NULL |
|
||||
| 7 | Muffy | NULL | NULL |
|
||||
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
|
||||
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
|
||||
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
|
||||
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
|
||||
+------+----------+--------+---------------------+
|
||||
|
||||
Note : **There are two other clauses (i.e., operators), which are like the UNION clause.**
|
||||
@@ -1,51 +0,0 @@
|
||||
# Relational Keys- Keys in a Relational Database
|
||||
|
||||
A database must be able to inhibit inconsistency occurring due to incorrect data. It must have certain identified attributes in relations to uniquely distinguish the tuples. No two tuples in a relation should have same value for all attributes since it will lead to duplicity of data. duplicity of data leads to inconsistency . Relational database systems have the concept of Relational Keys to distinguish between different records.
|
||||
|
||||
## Types of Relational Keys
|
||||
### *Super Keys*
|
||||
|
||||
A relation’s tuples can be uniquely identified by various combinations of attributes. Super Keys is defined as a set of one attribute or combinations of two or more attributes that help in distinguishing between tuples in a relation.
|
||||
|
||||
For example, the Customer ID attribute of the relation Customer is unique for all customers. The Customer ID can be used to identify each customer tuple in the relation. Customer ID is a Super Key for relation Customer.
|
||||
|
||||
Customer Name attribute of Customer cannot be considered as Super Key because many customers for the organization can have same name. However when combined with Customer ID it becomes a Super Key {CustomerID, CustomerName}. It means that Super Key can have additional attributes. Consider any key K which is identified as a super key. Any superset of key K is also a super key. For example the possible Super Keys for Customer Relation are
|
||||
|
||||
- [ CustomerID, CustomerName, Customer Address ]
|
||||
- [ CustomerID, CustomerName, Customer Contact Number ]
|
||||
- [ CustomerID, Customer Contact Number ]
|
||||
|
||||
### *Candidate Keys*
|
||||
|
||||
If we take a key from the set of super keys for which we don’t have any proper subset defined as a superkey, it is called a candidate key. In other words the minimal attribute super keys are termed as candidate keys.
|
||||
|
||||
If we can identify some distinct sets of attributes which identify the tuples uniquely they fall in the category of candidate keys. For example the possible Candidate Keys for Customer Relation are
|
||||
|
||||
- [ CustomerID ]
|
||||
- [ CustomerName, Customer Address ]
|
||||
- [ CustomerName, Customer Contact Number ]
|
||||
- [ Customer Address, Customer Contact Number ]
|
||||
|
||||
### *Primary Key*
|
||||
|
||||
Out of all possible candidate keys only one is chosen by the database designer as the key to identify the records in a relation in a database. This selected candidate key is called the Primary Key. It is the property of the relation and not of tuples. The primary key attribute(s) does not allow any duplicate values. It also inhibits leaving the primary key attribute without any value (NOT NULL).
|
||||
|
||||
**A relation can have only one primary key.**
|
||||
|
||||
In the Customer Database example {Customer ID} is the attribute taken as the primary key of customer relation. While picking up a candidate key as primary key the designer should ensure that it is an attribute or group of attributes that do not change or may change extremely rarely.
|
||||
|
||||
### *Alternate Keys*
|
||||
|
||||
After selecting one key among candidate keys as primary key, the rest of candidate keys are called the alternate keys. In the customer Database these candidate keys are the alternate keys.
|
||||
|
||||
- [ CustomerName, Customer Address ]
|
||||
- [ CustomerName, Customer Contact Number ]
|
||||
- [ Customer Address, Customer Contact Number ]
|
||||
|
||||
### *Foreign Key*
|
||||
|
||||
A foreign key is used to reference values from one relation into another relation. This is possible when the attribute or combination of attributes is primary key in the referenced relation. The relation in which the primary key of a relation is referenced is called the referencing table. The foreign key constraint implements the referential integrity in a database. The referencing relation attribute can have only those values which exist in the primary key attribute(s) of the referenced relation
|
||||
|
||||
**A relation can have multiple foreign key**
|
||||
|
||||
For example in the customer database the orders' relation (referencing relation) has the structure (Order ID, Customer ID, Order Date, Order Status, Total Billing Amount). The attribute Customer ID is the foreign key referencing Customer ID from customer relation (referenced relation). It means that orders can be placed only for the customers whose customer details are already available in the customer relation.
|
||||
@@ -1,17 +0,0 @@
|
||||
# Logical Operator Keywords
|
||||
|
||||
Here are the most important Logical Operators summarized in a table.
|
||||
|
||||
Logical Operators can be used for conditions as they show a result in form of a `boolean` (True/False) or Unknown.
|
||||
So, e.g. if an exact value is `True` for a value, a Logical Operator can proof that it's True.
|
||||
|
||||
| Logical Operator | Explanation |
|
||||
|------------------|-------------|
|
||||
| ALL | If all comparisons are True: return True |
|
||||
| ANY | If any comparison is True: return True |
|
||||
| AND | If both expressions are True: return True |
|
||||
| EXISTS | If a subquery contains rows: return True |
|
||||
| IN | If compared value is equal to at least one value: return True |
|
||||
| BETWEEN | If there are values in given range: return True |
|
||||
| NOT | Reverses the value of any boolean |
|
||||
| OR | If either expression is True: return True |
|
||||
@@ -1,186 +0,0 @@
|
||||
# `HAVING` Clause
|
||||
|
||||
Unlike where clause which imposes conditions on columns `Having` clause enables you to specify conditions that filter which group results appear in the results.
|
||||
|
||||
## Syntax
|
||||
|
||||
```sql
|
||||
SELECT column_name(s)
|
||||
FROM table_name
|
||||
WHERE condition
|
||||
GROUP BY column_name(s)
|
||||
HAVING condition
|
||||
ORDER BY column_name(s);
|
||||
```
|
||||
|
||||
## Description
|
||||
|
||||
- Used with `aggregate functions`
|
||||
- Must follow `GROUP BY` clause in the query
|
||||
|
||||
## Aggregate Functions
|
||||
- SQL aggregation is the task of collecting a set of values to return a single value.
|
||||
- An aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning.
|
||||
|
||||
## Aggregate Functions Examples
|
||||
|
||||
Suppose this are the table given to us
|
||||
|
||||
|Students | table||
|
||||
|--------|-----------|--------|
|
||||
| rollno | name | class |
|
||||
| 1 | Sanskriti | TE |
|
||||
| 1 | Shree | BE |
|
||||
| 2 | Harry | TE |
|
||||
| 3 | John | TE |
|
||||
| 3 | Shivani | TE |
|
||||
|
||||
|
||||
|purchase | table||
|
||||
|------------|-------|---------------|
|
||||
| item | price | customer_name |
|
||||
| Pen | 10 | Sanskriti |
|
||||
| Bag | 1000 | Sanskriti |
|
||||
| Vegetables | 500 | Sanskriti |
|
||||
| Shoes | 5000 | Sanskriti |
|
||||
| Water Bottle | 800 | XYZ |
|
||||
| Mouse | 120 | ABC |
|
||||
| Sun Glasses | 1350 | ABC |
|
||||
|
||||
|
||||
### AVG function
|
||||
|
||||
Calculates `average` of the given column of values
|
||||
|
||||
```sql
|
||||
SELECT AVG(price) AS Avg_Purchase, customer_name
|
||||
FROM purchase
|
||||
GROUP BY customer_name;
|
||||
```
|
||||
|
||||
| Avg_Purchase | customer_name |
|
||||
|--------------|---------------|
|
||||
| 1627.5000 | Sanskriti |
|
||||
|
||||
### SUM function
|
||||
|
||||
Calculates `sum` of values of given column.
|
||||
|
||||
```sql
|
||||
SELECT SUM(price) AS Total_Bill, customer_name
|
||||
FROM purchase
|
||||
GROUP BY customer_name;
|
||||
```
|
||||
|
||||
| Total_Bill | customer_name |
|
||||
|------------|---------------|
|
||||
| 6510 | Sanskriti |
|
||||
|
||||
### COUNT function
|
||||
|
||||
Gives `count` of entries/ values in given column.
|
||||
|
||||
```sql
|
||||
SELECT COUNT(item) AS Total_Items, customer_name
|
||||
FROM purchase
|
||||
GROUP BY customer_name;
|
||||
```
|
||||
|
||||
| Total_Items | customer_name |
|
||||
|-------------|---------------|
|
||||
| 4 | Sanskriti |
|
||||
|
||||
### MAX function
|
||||
|
||||
Return `maximum` value from the number of values in the column.
|
||||
|
||||
```sql
|
||||
SELECT MAX(price) AS Highest_Purchase, customer_name
|
||||
FROM purchase
|
||||
GROUP BY customer_name;
|
||||
```
|
||||
|
||||
| Highest_Purchase | customer_name |
|
||||
|-----------------|---------------|
|
||||
| 5000 | Sanskriti |
|
||||
|
||||
### MIN function
|
||||
|
||||
Return `minimum` value from the number of values in the column.
|
||||
|
||||
```sql
|
||||
SELECT MIN(price) AS Lowest_Purchase, customer_name
|
||||
FROM purchase
|
||||
GROUP BY customer_name;
|
||||
```
|
||||
| Lowest_Purchase | customer_name |
|
||||
|-----------------|---------------|
|
||||
| 10 | Sanskriti |
|
||||
|
||||
|
||||
## Having clause Examples
|
||||
|
||||
### Example 1
|
||||
|
||||
```sql
|
||||
SELECT COUNT(class) AS strength, class
|
||||
FROM Students
|
||||
GROUP BY class
|
||||
HAVING COUNT(class) > 2;
|
||||
```
|
||||
|
||||
Above query gives number of students in a class `having` number of students > 2
|
||||
|
||||
| strength | class |
|
||||
|----------|-------|
|
||||
| 4 | TE |
|
||||
|
||||
### Example 2
|
||||
|
||||
```sql
|
||||
SELECT customer_name, MIN(price) AS MIN_PURCHASE
|
||||
FROM purchase
|
||||
GROUP BY customer_name
|
||||
HAVING MIN(price) > 10;
|
||||
```
|
||||
Above query finds `minimum` price which is > 10
|
||||
|
||||
| customer_name | MIN_PURCHASE |
|
||||
|---------------|------------|
|
||||
| XYZ | 800 |
|
||||
| ABC | 120 |
|
||||
|
||||
### Example 3
|
||||
|
||||
```sql
|
||||
SELECT customer_name, AVG(price) AS Average_Purchase
|
||||
FROM purchase
|
||||
GROUP BY customer_name
|
||||
HAVING AVG(price) > 550
|
||||
ORDER BY customer_name DESC;
|
||||
```
|
||||
Above query calculates `average` of price and prints customer name and average price which is greater than 550 with descending `order` of customer names.
|
||||
|
||||
| customer_name | Average_Purchase |
|
||||
|---------------|------------------|
|
||||
| XYZ | 800.0000 |
|
||||
| Sanskriti | 1627.5000 |
|
||||
| ABC | 735.0000 |
|
||||
|
||||
### Example 4
|
||||
|
||||
```sql
|
||||
SELECT customer_name, SUM(price) AS Total_Purchase
|
||||
FROM purchase
|
||||
WHERE customer_name
|
||||
LIKE "S%"
|
||||
GROUP BY customer_name
|
||||
HAVING SUM(price) > 1000;
|
||||
```
|
||||
Calculates `SUM` of price and returns customer name and sum > 1000.
|
||||
|
||||
| customer_name | Total_Purchase |
|
||||
|---------------|----------------|
|
||||
| Sanskriti | 6510 |
|
||||
|
||||
|
||||
@@ -1,191 +0,0 @@
|
||||
# Essential MySQL Functions
|
||||
|
||||
MySQL has many built-in functions. We will covering some important most used built-in functions; for a complete list refer to the online MySQL Reference Manual (http://dev.mysql.com/doc/).
|
||||
|
||||
> NOTE: As of now we will be going through only function and their output, as they would be self explanatory.
|
||||
|
||||
## Numeric Functions
|
||||
```sql
|
||||
SELECT ROUND(5.73)
|
||||
```
|
||||
6
|
||||
|
||||
```sql
|
||||
SELECT ROUND(5.73, 1)
|
||||
```
|
||||
5.7
|
||||
|
||||
```sql
|
||||
SELECT TRUNCATE(5.7582, 2)
|
||||
```
|
||||
5.75
|
||||
|
||||
```sql
|
||||
SELECT CEILING(5.2)
|
||||
```
|
||||
6
|
||||
|
||||
```sql
|
||||
SELECT FLOOR(5.7)
|
||||
```
|
||||
5
|
||||
|
||||
```sql
|
||||
SELECT ABS(-5.2)
|
||||
```
|
||||
5.2
|
||||
|
||||
```sql
|
||||
SELECT RAND() -- Generates a random floating point number b/w 0 & 1
|
||||
```
|
||||
|
||||
## STRING Functions
|
||||
```sql
|
||||
SELECT LENGTH('sky')
|
||||
```
|
||||
3
|
||||
|
||||
```sql
|
||||
SELECT UPPER('sky')
|
||||
```
|
||||
SKY
|
||||
|
||||
```sql
|
||||
SELECT LOWER('sky)
|
||||
```
|
||||
sky
|
||||
|
||||
```sql
|
||||
SELECT LTRIM(' sky')
|
||||
```
|
||||
sky
|
||||
|
||||
```sql
|
||||
SELECT RTRIM('sky ')
|
||||
```
|
||||
sky
|
||||
|
||||
```sql
|
||||
SELECT TRIM(' sky ')
|
||||
```
|
||||
sky
|
||||
|
||||
```sql
|
||||
SELECT LEFT('Kindergarten', 4)
|
||||
```
|
||||
Kind
|
||||
|
||||
```sql
|
||||
SELECT RIGHT('Kindergarten', 6)
|
||||
```
|
||||
garten
|
||||
|
||||
```sql
|
||||
SELECT SUBSTRING('Kindergarten', 3, 5)
|
||||
```
|
||||
nderg
|
||||
|
||||
```sql
|
||||
SELECT LOCATE('n','Kindergarten') -- LOCATE returns the first occurrence of a character or character string, if found, otherwise it returns 0
|
||||
```
|
||||
3
|
||||
|
||||
```sql
|
||||
SELECT REPLACE('Kindergarten', 'garten', 'garden')
|
||||
```
|
||||
Kindergarden
|
||||
|
||||
```sql
|
||||
SELECT CONCAT('first', 'last')
|
||||
```
|
||||
firstlast
|
||||
|
||||
## DATE Functions
|
||||
```sql
|
||||
SELECT NOW()
|
||||
```
|
||||
2021-10-21 19:59:47
|
||||
|
||||
```sql
|
||||
SELECT CURDATE()
|
||||
```
|
||||
2021-10-21
|
||||
|
||||
```sql
|
||||
SELECT CURTIME()
|
||||
```
|
||||
20:01:12
|
||||
|
||||
```sql
|
||||
SELECT MONTH(NOW())
|
||||
```
|
||||
10
|
||||
|
||||
```sql
|
||||
SELECT YEAR(NOW())
|
||||
```
|
||||
2021
|
||||
|
||||
```sql
|
||||
SELECT HOUR(NOW())
|
||||
```
|
||||
13
|
||||
|
||||
```sql
|
||||
SELECT DAYTIME(NOW())
|
||||
```
|
||||
Thursday
|
||||
|
||||
## Formatting Dates and Times
|
||||
|
||||
> In MySQL, the default date format is "YYYY-MM-DD", ex: "2025-05-12", MySQL allows developers to format it the way they want. We will discuss some of them.
|
||||
```sql
|
||||
SELECT DATE_FORMAT(NOW(), '%M %D %Y')
|
||||
```
|
||||
October 22nd 2021
|
||||
|
||||
```sql
|
||||
SELECT DATE_FORMAT(NOW(), '%m %d %y')
|
||||
```
|
||||
10 22 21
|
||||
|
||||
```sql
|
||||
SELECT DATE_FORMAT(NOW(), '%m %D %y')
|
||||
```
|
||||
10 22nd 21
|
||||
|
||||
```sql
|
||||
SELECT TIME_FORMAT(NOW(), '%H %i %p')
|
||||
```
|
||||
14:11 PM
|
||||
|
||||
## Calculating Dates and Times
|
||||
|
||||
```sql
|
||||
SELECT DATE_ADD(NOW(), INTERVAL 1 DAY) --return tomorrows date and time
|
||||
```
|
||||
|
||||
2021-10-23 14:26:17
|
||||
|
||||
```sql
|
||||
SELECT DATE_ADD(NOW(), INTERVAL -1 YEAR)
|
||||
```
|
||||
or
|
||||
```sql
|
||||
SELECT DATE_SUB(NOW(), INTERVAL 1 YEAR)
|
||||
```
|
||||
> Both the queries will return the same output
|
||||
|
||||
2020-10-22 14:29:47
|
||||
|
||||
```sql
|
||||
SELECT DATEDIFF('2021-09-08 09:00', '2021-07-07 17:00') -- It will return the difference in number of days, time won't be considered
|
||||
```
|
||||
|
||||
63
|
||||
|
||||
```sql
|
||||
SELECT TIME_TO_SEC('09:00') - TIME_TO_SEC('09:02')
|
||||
```
|
||||
-120
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
# `Transaction Control Language`
|
||||
|
||||
- `Transaction Control Language` can be defined as the portion of a database language used for `maintaining consistency` of the database and `managing transactions` in the database.
|
||||
|
||||
- A set of `SQL statements` that are `co-related logically and executed on the data stored in the table` is known as a `transaction`.
|
||||
|
||||
## `TCL` Commands
|
||||
|
||||
- `COMMIT` Command
|
||||
- `ROLLBACK` Command
|
||||
- `SAVEPOINT` Command
|
||||
|
||||
## `COMMIT`
|
||||
|
||||
The main use of `COMMIT` command is to `make the transaction permanent`. If there is a need for any transaction to be done in the database that transaction permanent through commit command.
|
||||
|
||||
### Syntax
|
||||
```sql
|
||||
COMMIT;
|
||||
```
|
||||
|
||||
## `ROLLBACK`
|
||||
|
||||
Using this command, the database can be `restored to the last committed state`. Additionally, it is also used with savepoint command for jumping to a savepoint in a transaction.
|
||||
|
||||
### Syntax
|
||||
```sql
|
||||
ROLLBACK TO savepoint-name;
|
||||
```
|
||||
|
||||
## `SAVEPOINT`
|
||||
|
||||
The main use of the Savepoint command is to save a transaction temporarily. This way users can rollback to the point whenever it is needed.
|
||||
|
||||
### Syntax
|
||||
```sql
|
||||
SAVEPOINT savepoint-name;
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
#### This is purchase table that we are going to use through this tutorial
|
||||
|
||||
| item | price | customer_name |
|
||||
|--------------|-------|---------------|
|
||||
| Pen | 10 | Sanskriti |
|
||||
| Bag | 1000 | Sanskriti |
|
||||
| Vegetables | 500 | Sanskriti |
|
||||
| Shoes | 5000 | Sanskriti |
|
||||
| Water Bottle | 800 | XYZ |
|
||||
| Mouse | 120 | ABC |
|
||||
| Sun Glasses | 1350 | ABC |
|
||||
|
||||
```sql
|
||||
UPDATE purchase SET price = 20 WHERE item = "Pen";
|
||||
```
|
||||
##### O/P : Query OK, 1 row affected (3.02 sec) (Update the price of Pen set it from 10 to 20)
|
||||
|
||||
```sql
|
||||
SELECT * FROM purchase;
|
||||
```
|
||||
##### O/P
|
||||
| item | price | customer_name |
|
||||
|--------------|-------|---------------|
|
||||
| Pen | 20 | Sanskriti |
|
||||
| Bag | 1000 | Sanskriti |
|
||||
| Vegetables | 500 | Sanskriti |
|
||||
| Shoes | 5000 | Sanskriti |
|
||||
| Water Bottle | 800 | XYZ |
|
||||
| Mouse | 120 | ABC |
|
||||
| Sun Glasses | 1350 | ABC |
|
||||
|
||||
```sql
|
||||
START TRANSACTION;
|
||||
```
|
||||
##### Start transaction
|
||||
|
||||
```sql
|
||||
COMMIT;
|
||||
```
|
||||
##### Saved/ Confirmed the transactions till this point
|
||||
|
||||
```sql
|
||||
ROLLBACK;
|
||||
```
|
||||
##### Lets consider we tried to rollback above transaction
|
||||
|
||||
```sql
|
||||
SELECT * FROM purchase;
|
||||
```
|
||||
#### O/P:
|
||||
| item | price | customer_name |
|
||||
|--------------|-------|---------------|
|
||||
| Pen | 20 | Sanskriti |
|
||||
| Bag | 1000 | Sanskriti |
|
||||
| Vegetables | 500 | Sanskriti |
|
||||
| Shoes | 5000 | Sanskriti |
|
||||
| Water Bottle | 800 | XYZ |
|
||||
| Mouse | 120 | ABC |
|
||||
| Sun Glasses | 1350 | ABC |
|
||||
##### As we have committed the transactions the `rollback` will not affect anything
|
||||
|
||||
```sql
|
||||
SAVEPOINT sv_update;
|
||||
```
|
||||
##### Create the `savepoint` the transactions above this will not be rollbacked
|
||||
|
||||
```sql
|
||||
UPDATE purchase SET price = 30 WHERE item = "Pen";
|
||||
```
|
||||
#### O/P : Query OK, 1 row affected (0.57 sec)
|
||||
#### Rows matched: 1 Changed: 1 Warnings: 0
|
||||
|
||||
```sql
|
||||
SELECT * FROM purchase;
|
||||
```
|
||||
|
||||
| item | price | customer_name |
|
||||
|--------------|-------|---------------|
|
||||
| Pen | 30 | Sanskriti |
|
||||
| Bag | 1000 | Sanskriti |
|
||||
| Vegetables | 500 | Sanskriti |
|
||||
| Shoes | 5000 | Sanskriti |
|
||||
| Water Bottle | 800 | XYZ |
|
||||
| Mouse | 120 | ABC |
|
||||
| Sun Glasses | 1350 | ABC |
|
||||
##### price of pen is changed to 30 using the `update` command
|
||||
|
||||
```sql
|
||||
ROLLBACK to sv_update;
|
||||
```
|
||||
##### Now if we `rollback` to the `savepoint` price should be 20 after `rollback` lets see
|
||||
|
||||
```sql
|
||||
SELECT * FROM purchase;
|
||||
```
|
||||
|
||||
| item | price | customer_name |
|
||||
|--------------|-------|---------------|
|
||||
| Pen | 20 | Sanskriti |
|
||||
| Bag | 1000 | Sanskriti |
|
||||
| Vegetables | 500 | Sanskriti |
|
||||
| Shoes | 5000 | Sanskriti |
|
||||
| Water Bottle | 800 | XYZ |
|
||||
| Mouse | 120 | ABC |
|
||||
| Sun Glasses | 1350 | ABC |
|
||||
| Torch | 850 | ABC |
|
||||
##### As expected we can see `update` query is rollbacked to sv_update.
|
||||
|
||||
|
||||
|
||||
## Conclusion
|
||||
|
||||
With this short tutorial we have learnt TCL commands.
|
||||
@@ -1,39 +0,0 @@
|
||||
# Databases
|
||||
|
||||
Before we dive deep into SQL, let's quickly define what a database is.
|
||||
|
||||
The definition of databases from Wikipedia is:
|
||||
|
||||
> A database is an organized collection of data, generally stored and accessed electronically from a computer system.
|
||||
|
||||
In other words, a database is a collection of data stored and structured in different database tables.
|
||||
|
||||
## Tables and columns
|
||||
|
||||
You've most likely worked with spreadsheet systems like Excel or Google Sheets. At the very basic, database tables are quite similar to spreadsheets.
|
||||
|
||||
Each table has different **columns** which could contain different types of data.
|
||||
|
||||
For example, if you have a todo list app, you would have a database, and in your database, you would have different tables storing different information like:
|
||||
|
||||
* Users - In the users table, you would have some data for your users like: `username`, `name`, and `active`, for example.
|
||||
* Tasks - The tasks table would store all of the tasks that you are planning to do. The columns of the tasks table would be for example, `task_name`, `status`, `due_date` and `priority`.
|
||||
|
||||
The Users table will look like this:
|
||||
|
||||
```
|
||||
+----+----------+---------------+--------+
|
||||
| id | username | name | active |
|
||||
+----+----------+---------------+--------+
|
||||
| 1 | bobby | Bobby Iliev | true |
|
||||
| 2 | grisi | Greisi I. | true |
|
||||
| 3 | devdojo | Dev Dojo | false |
|
||||
+----+----------+---------------+--------+
|
||||
```
|
||||
|
||||
Rundown of the table structure:
|
||||
* We have 4 columns: `id`, `username`, `name` and `active`.
|
||||
* We also have 3 entries/users.
|
||||
* The `id` column is a unique identifier of each user and is auto-incremented.
|
||||
|
||||
In the next chapter, we will learn how to install MySQL and create our first database.
|
||||
Reference in New Issue
Block a user