├── DDL Commands ├── ddl.sql └── readme.md ├── DML Commands ├── dml.sql └── readme.md ├── Operators └── readme.md ├── SQL Grouping + Sorting └── readme.md ├── SQL Joins └── readme.md ├── SQL Subqueries └── readme.md ├── Stored Procedures └── readme.md ├── Temporal Datatypes └── readme.md ├── Views and User Defined Functions └── readme.md ├── Window Functions in SQL └── readme.md └── readme.md /DDL Commands/ddl.sql: -------------------------------------------------------------------------------- 1 | DROP DATABASE IF EXISTS campusx; 2 | CREATE DATABASE IF NOT EXISTS campusx; 3 | USE campusx; 4 | 5 | CREATE TABLE users( 6 | user_id INTEGER PRIMARY KEY, 7 | name VARCHAR(255) NOT NULL, 8 | email VARCHAR(255) NOT NULL, 9 | password VARCHAR(255), 10 | 11 | CONSTRAINT users_name_email_unique UNIQUE(name, email), 12 | CONSTRAINT users_password_unique UNIQUE(password) 13 | ); 14 | 15 | TRUNCATE TABLE users; 16 | DROP TABLE IF EXISTS users; 17 | 18 | -- FORIGN KEY EXAMPLE 19 | CREATE TABLE customers( 20 | cid INTEGER PRIMARY KEY AUTO_INCREMENT, 21 | name VARCHAR(255) NOT NULL, 22 | email VARCHAR(200) NOT NULL UNIQUE 23 | ); 24 | CREATE TABLE orders( 25 | order_id INTEGER PRIMARY KEY, 26 | cid INTEGER NOT NULL, 27 | order_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, 28 | 29 | CONSTRAINT orders_fk FOREIGN KEY (cid) REFERENCES customers(cid) 30 | ); 31 | 32 | -- ALTER 33 | ALTER TABLE customers ADD COLUMN surname VARCHAR(255) NOT NULL AFTER name; 34 | ALTER TABLE customers 35 | ADD COLUMN pan_num VARCHAR(255) AFTER surname, 36 | ADD COLUMN joining_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; 37 | 38 | ALTER TABLE customers DROP COLUMN pan_num; 39 | ALTER TABLE customers 40 | DROP COLUMN surname, 41 | DROP COLUMN joining_date; 42 | 43 | ALTER TABLE customers MODIFY COLUMN name INTEGER NOT NULL; -------------------------------------------------------------------------------- /DDL Commands/readme.md: -------------------------------------------------------------------------------- 1 | # DDL Commands 2 | 3 | `DDL Commands for Database` 4 | 1. CREATE 5 | ```sql 6 | CREATE DATABASE IF NOT EXISTS campusx; 7 | ``` 8 | 2. DROP 9 | ```sql 10 | DROP DATABASE IF EXISTS campusx; 11 | ``` 12 | 13 | `DDL Commands for Tables` 14 | 1. CREATE 15 | ```sql 16 | CREATE TABLE users( 17 | user_id INTEGER, 18 | name VARCHAR(255), 19 | email VARCHAR(255), 20 | password VARCHAR(255) 21 | ); 22 | ``` 23 | 2. TRUNCATE 24 | ```sql 25 | TRUNCATE TABLE users; 26 | ``` 27 | 3. DROP 28 | ```sql 29 | DROP TABLE IF EXISTS users; 30 | ``` 31 | 3. ALTER 32 | ```sql 33 | ALTER TABLE customers ADD COLUMN surname VARCHAR(255) NOT NULL AFTER name; 34 | -- Adding multiple columns 35 | ALTER TABLE customers 36 | ADD COLUMN pan_num VARCHAR(255) AFTER surname, 37 | ADD COLUMN joining_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; 38 | ``` 39 | ```sql 40 | ALTER TABLE customers DROP COLUMN pan_num; 41 | -- Deleting multiple column 42 | ALTER TABLE customers 43 | DROP COLUMN surname, 44 | DROP COLUMN joining_date; 45 | ``` 46 | ```sql 47 | ALTER TABLE customers MODIFY COLUMN name INTEGER NOT NULL; 48 | ``` 49 | 50 | - Alter for constraints 51 | ```sql 52 | ALTER TABLE customers ADD CONSTRAINT customer_age_check CHECK (age > 18); 53 | ALTER TABLE customers DROP CONSTRAINT customer_age_check; 54 | ``` 55 | 56 | ### CONSTRAINTS 57 | 58 | `NOT NULL` `UNIQUE` `PRIMARY KEY` `AUTO INCREMENT` `CHECK` `DEFAULT` `FORIGN KEY` 59 | ```sql 60 | CREATE TABLE example_table ( 61 | id INTEGER AUTO_INCREMENT PRIMARY KEY, 62 | name VARCHAR(50) NOT NULL, 63 | age INTEGER, 64 | email VARCHAR(100) UNIQUE, 65 | created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 66 | 67 | CONSTRAINT chk_age CHECK (age >= 18 AND age <= 100) 68 | ); 69 | ``` 70 | 71 | `Another way of adding constraints` 72 | - To add Unique constraint for combination of name and email 73 | - We can delete added constraint whenever we want 74 | ```sql 75 | CREATE TABLE users( 76 | user_id INTEGER, 77 | name VARCHAR(255), 78 | email VARCHAR(255), 79 | password VARCHAR(255), 80 | 81 | CONSTRAINT users_password_unique UNIQUE(password), 82 | CONSTRAINT users_name_email_unique UNIQUE(name, email) 83 | ); 84 | ``` 85 | 86 | `Foreign key example` 87 | ```sql 88 | CREATE TABLE customers( 89 | cid INTEGER PRIMARY KEY AUTO_INCREMENT, 90 | name VARCHAR(255) NOT NULL, 91 | email VARCHAR(200) NOT NULL UNIQUE 92 | ); 93 | CREATE TABLE orders( 94 | order_id INTEGER PRIMARY KEY, 95 | cid INTEGER NOT NULL, 96 | order_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, 97 | 98 | CONSTRAINT orders_fk FOREIGN KEY (cid) REFERENCES customers(cid) 99 | ); 100 | ``` 101 | We cant delete or update customers becouse of foreign key.\ 102 | Cannot delete or update a parent row: A foreign key constraints fails.. 103 | 104 | 105 | **REFERENTIAL ACTIONS** 106 | 107 | If two tables are related via a foreign key. what happens to a record when you delete or update a related record. 108 | 109 | - Changing Referential acitions 110 | ```sql 111 | CREATE TABLE orders( 112 | order_id INTEGER PRIMARY KEY, 113 | cid INTEGER NOT NULL, 114 | order_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, 115 | 116 | CONSTRAINT orders_fk FOREIGN KEY (cid) REFERENCES customers(cid) 117 | ON DELETE CASCADE 118 | ON DELETE CASCADE 119 | ); 120 | ``` 121 | 122 | 1. `RESTRICT` : (default) An error is returned and no rows are deleted 123 | 2. `CASCADE` : 124 | The delete operation is propagated to the dependents of p in D 125 | 3. `SET NULL` : 126 | Each nullable column of the foreign key of each dependent of p in D is set to null 127 | 4. `SET DEFAULT` : Each column of the foreign key of each dependent of p in D is set to its default value -------------------------------------------------------------------------------- /DML Commands/dml.sql: -------------------------------------------------------------------------------- 1 | DROP DATABASE IF EXISTS campusx; 2 | CREATE DATABASE IF NOT EXISTS campusx; 3 | USE campusx; 4 | 5 | CREATE TABLE users( 6 | user_id INTEGER PRIMARY KEY AUTO_INCREMENT, 7 | name VARCHAR(255) NOT NULL, 8 | email VARCHAR(255) NOT NULL UNIQUE, 9 | f1 INTEGER, 10 | f2 INTEGER, 11 | password VARCHAR(255) NOT NULL 12 | ); 13 | 14 | -- INSERT 15 | 16 | INSERT INTO users (user_id, name, email, f1, f2, password) VALUES (NULL, ' nitish', 'nitish@gmail.com', 10, 20, '1234'); 17 | INSERT INTO users VALUES (NULL, ' ankit', 'ankit@gmail.com', 11, 22, '1234'); 18 | INSERT INTO users (name, email, password) VALUES ('amit', 'amit@gmail.com', '4567'); 19 | -- Adding multiple rows 20 | INSERT INTO users VALUES 21 | (NULL, 'rishab', 'rishab@gmail.com', 12, 22, '2467'), 22 | (NULL, 'rahul', 'rahul@gmail.com', 13, 23, '8538'); 23 | 24 | -- SELECT 25 | 26 | SELECT * FROM users WHERE 1; 27 | 28 | -- Filtering cols 29 | SELECT name, email FROM users; 30 | 31 | -- Aliasing (Renaming cols) 32 | SELECT f1 AS 'Feature 1', f2 AS 'Feature 2' FROM users; 33 | 34 | -- Create expression using cols 35 | SELECT f1 * f2 AS 'New Feature' FROM users; 36 | 37 | -- Constants 38 | SELECT "smartpones"; 39 | 40 | -- Distict (unique) 41 | SELECT DISTINCT name FROM users; 42 | -- Distict combo 43 | SELECT DISTINCT name, email FROM users; 44 | 45 | -- WHERE (filtering rows) 46 | SELECT * FROM users WHERE email = 'ankit@gmail.com'; 47 | SELECT * FROM users WHERE f1 > 10; 48 | SELECT * FROM users WHERE f1 BETWEEN 11 AND 12; 49 | SELECT * FROM users WHERE f1 > 11 AND f2 > 22; 50 | 51 | -- IN, NOT IN 52 | SELECT * FROM users 53 | WHERE email IN ('nitish@gmail.com', 'ankit@gmail.com'); 54 | 55 | 56 | -- UPDATE 57 | UPDATE users 58 | SET f1 = 14 59 | WHERE email = "nitish@gmail.com"; 60 | 61 | 62 | -- DELETE 63 | DELETE FROM users 64 | WHERE f1 > 100; 65 | 66 | 67 | -- AGGRIGATE FUNCTIONS 68 | SELECT MIN(f1) AS "min" FROM users; 69 | SELECT MAX(f1) AS "max" FROM users; 70 | SELECT AVG(f1) AS "avg" FROM users; 71 | SELECT SUM(f1) AS "sum" FROM users; 72 | SELECT COUNT(f1) AS "count" FROM users; 73 | SELECT COUNT(DISTINCT(f1)) FROM users; 74 | SELECT STD(f1) AS "std" FROM users; 75 | SELECT VARIANCE(f1) AS "var" FROM users; 76 | 77 | -- Scalar functions 78 | SELECT ABS(f1) AS 'abs' FROM users; 79 | SELECT SQRT(f1) AS 'sqrt' FROM users; 80 | SELECT ROUND(f1) AS 'round' FROM users; 81 | SELECT CEIL(f1) AS 'ceil' FROM users; 82 | SELECT FLOOR(f1) AS 'floor' FROM users; 83 | SELECT ROUND(f1) AS 'round' FROM users; 84 | SELECT CEIL(f1) AS 'ceil' FROM users; 85 | SELECT FLOOR(f1) AS 'floor' FROM users; -------------------------------------------------------------------------------- /DML Commands/readme.md: -------------------------------------------------------------------------------- 1 | # DML Commands 2 | 3 | ### Insert 4 | ```sql 5 | INSERT INTO users (user_id, name, email, f1, f2, password) VALUES (NULL, ' nitish', 'nitish@gmail.com', 10, 20, '1234'); 6 | INSERT INTO users VALUES (NULL, ' ankit', 'ankit@gmail.com', 11, 22, '1234'); 7 | INSERT INTO users (name, email, password) VALUES ('amit', 'amit@gmail.com', '4567'); 8 | -- Adding multiple rows 9 | INSERT INTO users VALUES 10 | (NULL, 'rishab', 'rishab@gmail.com', 12, 22, '2467'), 11 | (NULL, 'rahul', 'rahul@gmail.com', 13, 23, '8538'); 12 | ``` 13 | 14 | ### Select 15 | ```sql 16 | SELECT * FROM users WHERE 1; 17 | 18 | -- Filtering cols 19 | SELECT name, email FROM users; 20 | 21 | -- Aliasing (Renaming cols) 22 | SELECT f1 AS 'Feature 1', f2 AS 'Feature 2' FROM users; 23 | 24 | -- Create expression using cols 25 | SELECT f1 * f2 AS 'New Feature' FROM users; 26 | 27 | -- Constants 28 | SELECT "smartpones"; 29 | 30 | -- Distict (unique) 31 | SELECT DISTINCT name FROM users; 32 | -- Distict combo 33 | SELECT DISTINCT name, email FROM users; 34 | ``` 35 | 36 | **Where Clause - (filtering rows)** 37 | ```sql 38 | SELECT * FROM users WHERE email = 'ankit@gmail.com'; 39 | SELECT * FROM users WHERE f1 > 10; 40 | SELECT * FROM users WHERE f1 BETWEEN 11 AND 12; 41 | SELECT * FROM users WHERE f1 > 11 AND f2 > 22; 42 | 43 | -- IN, NOT IN 44 | SELECT * FROM users 45 | WHERE email IN ('nitish@gmail.com', 'ankit@gmail.com'); 46 | ``` 47 | 48 | ## Query Execution Order 49 | 50 | ![Query-execution-order-image](https://miro.medium.com/v2/resize:fit:1100/format:webp/1*TS2QIfVGo6q7r6qEeFjiJA.png) 51 | 52 | Checkout [Query execution order blog](https://medium.com/@aakash_7/execution-sequence-of-sql-67b64037b000) 53 | 54 | 55 | ### Update 56 | ```sql 57 | UPDATE users 58 | SET f1 = 14 59 | WHERE email = "nitish@gmail.com"; 60 | ``` 61 | 62 | ### Delete 63 | ```sql 64 | DELETE FROM users 65 | WHERE f1 > 100; 66 | ``` 67 | 68 | --- 69 | 70 | 71 | ## Aggrigate Functions 72 | ```sql 73 | SELECT MIN(f1) AS "min" FROM users; 74 | SELECT MAX(f1) AS "max" FROM users; 75 | SELECT AVG(f1) AS "avg" FROM users; 76 | SELECT SUM(f1) AS "sum" FROM users; 77 | SELECT COUNT(f1) AS "count" FROM users; 78 | SELECT COUNT(DISTINCT(f1)) FROM users; 79 | SELECT STD(f1) AS "std" FROM users; 80 | SELECT VARIANCE(f1) AS "var" FROM users; 81 | ``` 82 | --- 83 | 84 | ## Scalar Functions 85 | ```sql 86 | SELECT ABS(f1) AS 'abs' FROM users; 87 | SELECT ROUND(f1) AS 'round' FROM users; 88 | SELECT CEIL(f1) AS 'ceil' FROM users; 89 | SELECT FLOOR(f1) AS 'floor' FROM users; 90 | ``` -------------------------------------------------------------------------------- /Operators/readme.md: -------------------------------------------------------------------------------- 1 | # Arithmetic Operators 2 | 3 | `1. Addition Operator (+)`: Adds two or more numerical values. 4 | ```sql 5 | SELECT 5+4; 6 | -- The result will be 9. 7 | ``` 8 | `2. Substraction Operator (-)`: Substracts two or more numerical values. 9 | ```sql 10 | SELECT 5-4; 11 | -- The result will be 1. 12 | ``` 13 | `3. Multiplication Operator (*)`: Multiplies two or more numerical values. 14 | ```sql 15 | SELECT 5*4; 16 | -- The result will be 20. 17 | ``` 18 | `4. Division Operator (/)`: Divides two or more numerical values. 19 | ```sql 20 | SELECT 10/2; 21 | -- The result will be 5. 22 | ``` 23 | `5. Modulus Operator (+)`: Returns the remainder of one number divided by other. 24 | ```sql 25 | SELECT 5%4; 26 | -- The result will be 1. 27 | ``` 28 | 29 | --- -------------------------------------------------------------------------------- /SQL Grouping + Sorting/readme.md: -------------------------------------------------------------------------------- 1 | # SQL Grouping + Sorting 2 | 3 | A GROUP BY statement in SQL specifies that a SQL SELECT statement partitions result rows into groups, based on their values in one or several columns. Typically, grouping is used to apply some sort of aggregate function for each group. 4 | 5 | ```sql 6 | -- Returns a list of Department IDs along with the sum of their sales for the date of January 1, 2000. 7 | SELECT DeptID, SUM(SaleAmount) FROM Sales 8 | WHERE SaleDate = '01-Jan-2000' 9 | GROUP BY DeptID; 10 | ``` 11 | 12 | ```sql 13 | SELECT Region, Ship_Date, SUM(Units) AS Sum_of_Units 14 | FROM FlatData 15 | GROUP BY Region, Ship_Date 16 | ``` 17 | 18 | **Using Having clause** 19 | ```sql 20 | SELECT NAME, SUM(sal) FROM Emp 21 | GROUP BY name 22 | HAVING SUM(sal)>3000; 23 | ``` 24 | 25 | **Order by** 26 | 27 | ```sql 28 | SELECT COUNT(CustomerID), Country 29 | FROM Customers 30 | GROUP BY Country 31 | ORDER BY COUNT(CustomerID) DESC; 32 | ``` -------------------------------------------------------------------------------- /SQL Joins/readme.md: -------------------------------------------------------------------------------- 1 | # SQL Joins 2 | 3 | A join clause in the Structured Query Language (SQL) combines columns from one or more tables into a new table. 4 | 5 | ![SQL-joins-image](https://miro.medium.com/v2/resize:fit:1100/format:webp/1*4lPn1y63GGLKsEEpLxS8BQ.png) 6 | 7 | ## Cross Join 8 | CROSS JOIN returns the Cartesian product of rows from tables in the join. In other words, it will produce rows which combine each row from the first table with each row from the second table. 9 | 10 | Example of an explicit cross join: 11 | ```sql 12 | SELECT * 13 | FROM employee CROSS JOIN department; 14 | ``` 15 | Example of an implicit cross join: 16 | ```sql 17 | SELECT * 18 | FROM employee, department; 19 | ``` 20 | The cross join can be replaced with an inner join with an always-true condition: 21 | ```sql 22 | SELECT * 23 | FROM employee INNER JOIN department ON 1=1; 24 | ``` 25 | 26 | ## Inner Join 27 | An inner join (or join) requires each row in the two joined tables to have matching column values 28 | 29 | ```sql 30 | SELECT employee.LastName, employee.DepartmentID, department.DepartmentName 31 | FROM employee 32 | INNER JOIN department ON 33 | employee.DepartmentID = department.DepartmentID; 34 | 35 | SELECT employee.LastName, employee.DepartmentID, department.DepartmentName 36 | FROM employee, department 37 | WHERE employee.DepartmentID = department.DepartmentID; 38 | ``` 39 | 40 | ### Equi-join 41 | An equi-join is a specific type of comparator-based join, that uses only equality comparisons in the join-predicate. Using other comparison operators (such as <) disqualifies a join as an equi-join. 42 | 43 | ```sql 44 | SELECT * 45 | FROM employee JOIN department 46 | ON employee.DepartmentID = department.DepartmentID; 47 | 48 | SELECT * 49 | FROM employee, department 50 | WHERE employee.DepartmentID = department.DepartmentID; 51 | 52 | SELECT * 53 | FROM employee INNER JOIN department USING (DepartmentID); 54 | ``` 55 | 56 | #### Natural Join 57 | The natural join is a special case of equi-join. 58 | ```sql 59 | SELECT * 60 | FROM employee NATURAL JOIN department; 61 | ``` 62 | 63 | ## Outer Join 64 | ### Left Outer Join 65 | ```sql 66 | SELECT * 67 | FROM employee 68 | LEFT OUTER JOIN department ON employee.DepartmentID = department.DepartmentID; 69 | 70 | -- Alternative syntaxes 71 | SELECT * 72 | FROM employee, department 73 | WHERE employee.DepartmentID = department.DepartmentID(+) 74 | ``` 75 | 76 | ### Right Outer Join 77 | ```sql 78 | SELECT * 79 | FROM employee RIGHT OUTER JOIN department 80 | ON employee.DepartmentID = department.DepartmentID; 81 | ``` 82 | 83 | ### Full Outer Join 84 | ```sql 85 | SELECT * 86 | FROM employee FULL OUTER JOIN department 87 | ON employee.DepartmentID = department.DepartmentID; 88 | ``` 89 | 90 | Some database systems do not support the full outer join functionality directly, but they can emulate it through the use of an inner join and UNION ALL selects of the "single table rows" from left and right tables respectively. 91 | 92 | ```sql 93 | SELECT * 94 | FROM Table1 95 | LEFT OUTER JOIN Table2 96 | ON Table1.column_match = Table2.column_match 97 | UNION 98 | SELECT * 99 | FROM Table1 100 | RIGHT OUTER JOIN Table2 101 | ON Table1.column_match = Table2.column_match; 102 | ``` 103 | 104 | ## Self Join 105 | ```sql 106 | SELECT e1.employee_id AS employee_id, e1.manager_id AS manager_id, 107 | e2.employee_id AS manager_employee_id, e2.manager_id AS manager_manager_id 108 | FROM employees e1 109 | JOIN employees e2 ON e1.manager_id = e2.employee_id; 110 | ``` -------------------------------------------------------------------------------- /SQL Subqueries/readme.md: -------------------------------------------------------------------------------- 1 | # SQL Subqueries 2 | 3 | It is a query inside of a query. 4 | 5 | ![SQL-subqueries-image](https://miro.medium.com/v2/resize:fit:1100/format:webp/0*QQs9HwVYiA4LgaKS.png) 6 | 7 | ## Types of subqueries 8 | 9 | ### 1. The result it returns 10 | - `Scalar subquery` 11 | ```sql 12 | SELECT * FROM employees 13 | WHERE salary > (SELECT AVG(salary) FROM employees); 14 | ``` 15 | - `Row subquery` 16 | ```sql 17 | SELECT * FROM t1 WHERE (col1,col2) = (SELECT col3, col4 FROM t2 WHERE id = 10); 18 | ``` 19 | - `Table subquery` 20 | ```sql 21 | WITH top_duos AS ( 22 | SELECT star, director MAX(gross) FROM movies 23 | GROUP BY star, director 24 | ORDER BY SUM(gross) DESC LIMIT 0 1 25 | ) 26 | 27 | SELECT * FROM movies 28 | WHERE (star, director, gross) IN (SELECT * FROM top_duos); 29 | ``` 30 | 31 | ## 2. Based on working 32 | - `Independent subquery` 33 | ```sql 34 | SELECT * FROM Employee 35 | WHERE salary = (SELECT MIN (salary) FROM Employee); 36 | ``` 37 | - `Correlated subquery` 38 | ```sql 39 | SELECT * FROM employees e 40 | WHERE salary > ( 41 | SELECT AVG(salary) 42 | FROM employees 43 | WHERE department_id = e.department_id 44 | ); 45 | ``` 46 | 47 | ## Where can subqueries be used 48 | **Insert** 49 | ```sql 50 | INSERT INTO products_bkp (product_id, product_name, product_price) 51 | SELECT product_id, product_name, product_price FROM products; 52 | 53 | INSERT INTO employees (employee_name, department_id) 54 | VALUES ('John Doe', (SELECT department_id FROM departments WHERE department_name = 'Sales')); 55 | 56 | ``` 57 | 58 | **Select** 59 | - `Where` 60 | ```sql 61 | SELECT team_name FROM team 62 | WHERE team_id IN (SELECT team_id FROM game WHERE points >= 130); 63 | ``` 64 | - `Select` 65 | ```sql 66 | SELECT customer_name, 67 | (SELECT COUNT(*) FROM orders WHERE orders.customer_id = customers.customer_id) AS order_count 68 | FROM customers 69 | ``` 70 | - `From` 71 | ```sql 72 | SELECT * 73 | FROM ( 74 | SELECT customer_id, COUNT(*) AS num_orders 75 | FROM orders 76 | GROUP BY customer_id 77 | ) AS order_counts 78 | JOIN customers ON order_counts.customer_id = customers.customer_id; 79 | ``` 80 | - `Having` 81 | ```sql 82 | SELECT department_id, COUNT(*) AS num_employees 83 | FROM employees 84 | GROUP BY department_id 85 | HAVING COUNT(*) > (SELECT COUNT(*) FROM employees WHERE department_id = 10); 86 | ``` 87 | 88 | **Update** 89 | ```sql 90 | UPDATE loyal_customers t1 91 | SET t1.money = ( 92 | SELECT user_id, SUM(amount)*0.1 AS money FROM orders 93 | GROUP BY use_id 94 | ) t2 95 | WHERE t1.user_id = t2.user_id 96 | ``` 97 | 98 | **Delete** 99 | ```sql 100 | DELETE FROM orders WHERE paid_date IN (SELECT paid_date FROM orders WHERE paid_date < CURRENT DATE); 101 | ``` -------------------------------------------------------------------------------- /Stored Procedures/readme.md: -------------------------------------------------------------------------------- 1 | # Stored Procedures 2 | 3 | A group of SQL statements and logic that are stored in a database. 4 | 5 | ```sql 6 | CREATE PROCEDURE GetEmployeeByID 7 | @EmployeeID INT 8 | AS 9 | BEGIN 10 | SELECT * FROM Employees WHERE EmployeeID = @EmployeeID; 11 | END; 12 | ``` 13 | ```sql 14 | EXEC GetEmployeeByID @EmployeeID = 123; 15 | ``` -------------------------------------------------------------------------------- /Temporal Datatypes/readme.md: -------------------------------------------------------------------------------- 1 | # Temporal Datatypes 2 | 3 | 1. `DATE` - used for storing date values in the format YYYY-MM-DD. 4 | 2. `TIME` - used for storing time values in the format HH:MM:SS. 5 | 3. `DATETIME` - used for storing date and time values in the format YYYY-MM-DD HH:MM:SS. 6 | 4. `TIMESTAMP` - used for storing date and time values in the format YYYY- MM-DD HH:MM:SS. It has a range of 1970-01-01 00:00:01 UTC to 2038-01-19 03:14:07 UTC. 7 | 5. `YEAR` - used for storing year values in 2-digit or 4-digit format (YYYY or YY).If the year is specified with 2 digits, it is assumed to be in the range 1970-2069 (inclusive).\ 8 | 9 | ## DATETIME Functions 10 | 11 | 1. **CURR_DATE()**: Returns the current date from the system clock. 12 | ```sql 13 | SELECT CURR_DATE() AS current_date; 14 | ``` 15 | 16 | 2. **CURR_TIME()**: Retrieve the current time from the system clock 17 | ```sql 18 | SELECT CURR_TIME() AS current_time; 19 | ``` 20 | 21 | 3. **NOW()**: Retrieve the current date and time from the system clock. 22 | ```sql 23 | SELECT NOW() AS current_datetime; 24 | ``` 25 | 26 | ### Extraction Function 27 | 1. **DATE() and TIME()**: `DATE()` function is typically used to extract the date part from a given datetime expression.`TIME()` function is typically used to extract the time part from a datetime expression. 28 | ```sql 29 | SELECT DATE(datetime_column) AS date_only FROM your_table; 30 | SELECT TIME(datetime_column) AS time_only FROM your_table; 31 | ``` 32 | 33 | 2. **YEAR()**: Used to extract the year part from a date or datetime expression. 34 | ```sql 35 | SELECT YEAR(date_column) AS year_only FROM your_table; 36 | ``` 37 | 38 | 3. **DAY() or DAYOFMONTH()()**: `DAY()` and `DAYOFMONTH()` functions are commonly used to extract the day of the month from a date or datetime expression. 39 | ```sql 40 | SELECT DAY(date_column) AS day_only FROM your_table; 41 | SELECT DAYOFMONTH(date_column) AS day_only FROM your_table; 42 | ``` 43 | 44 | 4. **DAYOFWEEK()**: Retrieve the day of the week from a given date. 45 | ```sql 46 | SELECT DAYOFWEEK(date_column) AS day_of_week FROM your_table; 47 | ``` 48 | 49 | 5. **DAYOFYEAR()**: Retrieve the day of the year from a given date. 50 | ```sql 51 | SELECT DAYOFYEAR(date_column) AS day_of_year FROM your_table; 52 | ``` 53 | 54 | 6. **MONTH() and MONTHNAME()**: `MONTH()` and `MONTHNAME()` functions are commonly used to extract and manipulate the month part of a date or datetime expression. 55 | ```sql 56 | SELECT MONTH(date_column) AS month_number FROM your_table; 57 | SELECT MONTHNAME(date_column) AS month_name FROM your_table; 58 | ``` 59 | 60 | 7. **QUARTER()**: Extract the quarter from a given date. 61 | ```sql 62 | SELECT QUARTER(date_column) AS quarter FROM your_table; 63 | ``` 64 | 65 | 8. **WEEK() or WEEKOFYEAR()**: `WEEK()` function returns the week number for a given date. `WEEKOFYEAR()` function returns the week number for a given date, where the week begins on a specific day of the week (e.g., Sunday or Monday) and ends on the following day. 66 | ```sql 67 | SELECT WEEK(date_column) AS week_number FROM your_table; 68 | SELECT WEEKOFYEAR(date_column) AS week_of_year FROM your_table; 69 | ``` 70 | 9. **HOUR() -> MINUTE() -> SECOND()**: `HOUR()`, `MINUTE()`, and `SECOND()` functions are used to extract the hour, minute, and second parts from a given time or datetime expression 71 | ```sql 72 | SELECT HOUR(time_column) AS hour FROM your_table; 73 | SELECT MINUTE(time_column) AS minute FROM your_table; 74 | SELECT SECOND(time_column) AS second FROM your_table; 75 | ``` 76 | 77 | 10. **LAST_DAY()**: Return the last day of the month for a given date or datetime expression 78 | ```sql 79 | SELECT LAST_DAY(date_column) AS last_day_of_month FROM your_table; 80 | ``` 81 | 82 | 83 | ## Datetime Formatting 84 | [Datetime-formatting](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-format) 85 | 86 | 1. **DATE_FORMAT()**: Used to format date and time values according to a specified format string. 87 | ```sql 88 | SELECT DATE_FORMAT(date_column, '%Y-%m-%d') AS formatted_date FROM your_table; 89 | ``` 90 | 91 | 2. **TIME_FORMAT()**: Used to format time values according to a specified format string. 92 | ```sql 93 | SELECT TIME_FORMAT(time_column, '%H:%i:%s') AS formatted_time FROM your_table; 94 | ``` 95 | 96 | ## Type conversion 97 | 98 | 1. **Implicit Type Conversion** 99 | 2. **Explicit Type Conversion -> STR_TO_DATE()**: Used to convert a string representation of a date and/or time into a proper DATE, TIME, or DATETIME value based on a specified format. This function is particularly useful when dealing with date values stored as strings in non-standard formats. 100 | ```sql 101 | SELECT STR_TO_DATE(date_string, '%Y-%m-%d') AS date_value FROM your_table; 102 | ``` 103 | 104 | ## DATETIME Arithmetic 105 | 1. **DATEDIFF()**: Calculates the difference between two dates and returns the result as an integer. 106 | ```sql 107 | SELECT DATEDIFF('2024-02-14', '2024-02-10') AS date_difference; 108 | ``` 109 | 110 | 2. **TIMEDIFF()**: Calculate the difference between two time or datetime values and returns the result as a time interval. 111 | ```sql 112 | SELECT TIMEDIFF('14:30:00', '12:00:00') AS time_difference; 113 | ``` 114 | 115 | 3. **DATE_ADD() and DATE_SUB() INTERVAL**: `DATE_ADD()` and `DATE_SUB()` functions are used to add or subtract intervals from a given date or datetime value. 116 | ```sql 117 | SELECT DATE_ADD('2024-02-14', INTERVAL 3 DAY) AS new_date; 118 | SELECT DATE_SUB('2024-02-14', INTERVAL 1 MONTH) AS new_date; 119 | ``` 120 | 121 | 4. **ADDTIME() and SUBTIME()**: Used to perform datetime arithmetic by adding or subtracting time intervals from given time or datetime values. 122 | ```sql 123 | SELECT ADDTIME('12:00:00', '01:30:00') AS new_time; 124 | SELECT SUBTIME('14:30:00', '00:45:00') AS new_time; 125 | ``` -------------------------------------------------------------------------------- /Views and User Defined Functions/readme.md: -------------------------------------------------------------------------------- 1 | # Views 2 | 3 | A virtual table whose contents are defined by a query. Once a view is created, it can be used in the same way as a table in SQL queries, and any changes made to the underlying tables will be reflected in the view. 4 | 5 | 1. **Read-only views**: As the name suggests, read-only views are views that cannot be updated. 6 | 2. **Updatable views**: Updatable views are views that allow you to modify, insert or delete data in the underlying tables through the view. 7 | 8 | To make a view updatable, certain conditions must be met. For example, the view 9 | must not contain any derived columns, subqueries, or aggregate functions. 10 | Additionally, the view must be based on a single table or a join of tables with a 11 | unique one-to-one relationship. 12 | 13 | ```sql 14 | CREATE VIEW it_employees AS 15 | SELECT id, name, department, salary 16 | FROM employees 17 | WHERE department = 'IT' AND salary > 50000; 18 | 19 | SELECT * FROM it_employees; 20 | ``` 21 | 22 | # User Defined Functions 23 | 24 | A routine that accepts parameters, performs an action, and returns the result as a value. These functions can be used just like built-in functions in SQL and can take parameters as input, perform some 25 | 26 | operations on them, and then return a value. 27 | 28 | ```sql 29 | CREATE FUNCTION CalculateAgeInYears (@dob DATE) 30 | RETURNS INT 31 | AS 32 | BEGIN 33 | DECLARE @age INT 34 | SET @age = DATEDIFF(YEAR, @dob, GETDATE()) 35 | RETURN @age 36 | END 37 | ``` 38 | ```sql 39 | DROP FUNCTION [IF EXISTS] function_name; 40 | ``` -------------------------------------------------------------------------------- /Window Functions in SQL/readme.md: -------------------------------------------------------------------------------- 1 | # Window Functions in SQL 2 | 3 | A window function performs a calculation across a set of table rows that are somehow related to the current row. This is comparable to the type of calculation that can be done with an aggregate function. But unlike regular aggregate functions, use of a window function does not cause rows to become grouped into a single output row — the rows retain their separate identities. Behind the scenes, the window function is able to access more than just the current row of the query result. 4 | 5 | ![SQL-window_functions](https://miro.medium.com/v2/resize:fit:1100/format:webp/1*PyBvYNwMbY75cBcc4TRl7g.jpeg) 6 | 7 | **The most practical example of this is a running total:** 8 | ```sql 9 | SELECT runs, SUM(runs) OVER() FROM cricket_score; 10 | ``` 11 | 12 | **The window function is applied to each partition separately and computation restarts for each partition** 13 | ```sql 14 | SELECT *, SUM(marks) OVER(PARTITION BY branch ORDER BY roll_number) FROM marks; 15 | ``` 16 | 17 | ### RANK() 18 | 19 | Assigns a unique rank to each row within a result set based on the values in one or more columns. Rows with the same values receive the same rank, and the next rank is skipped. 20 | 21 | ```sql 22 | SELECT *, RANK() OVER (ORDER BY exam_score DESC) AS rank 23 | FROM exam_results; 24 | ``` 25 | 26 | ### DENSE_RANK() 27 | 28 | DENSE_RANK() is similar to RANK(), but it assigns ranks without skipping any values, even if multiple rows share the same rank. 29 | 30 | ```sql 31 | SELECT *, DENSE_RANK() OVER (ORDER BY exam_score DESC) AS dense_rank 32 | FROM exam_results; 33 | ``` 34 | 35 | ### ROW_NUMBER() 36 | 37 | It does just what it sounds like—displays the number of a given row. It starts are 1 and numbers the rows according to the ORDER BY part of the window statement. 38 | 39 | ```sql 40 | SELECT *, ROW_NUMBER() OVER (ORDER BY score DESC) AS rank 41 | FROM students; 42 | ``` 43 | 44 | ## Frames 45 | 46 | A frame in a window function is a subset of rows within the partition. 47 | 48 | Common frame specifications include: 49 | 1. `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW` - (Default) This includes all rows from the start of the window (unbounded preceding) up to and including the current row. 50 | 2. `ROWS BETWEEN n PRECEDING AND m FOLLOWING` - This includes a specified number of rows before (preceding) and after (following) the current row. 51 | 3. `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING` - This includes all rows in the window, from the start to the end. 52 | 53 | ### FIRST_VALUE() 54 | Returns the value of a specified column from the first row within the defined window or frame of rows. 55 | ```sql 56 | SELECT *, 57 | FIRST_VALUE(sales_amount) OVER (PARTITION BY region ORDER BY sales_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS first_sale_amount 58 | FROM sales_data; 59 | ``` 60 | 61 | ### LAST_VALUE() 62 | Returns the value of a specified column from the last row within the defined window or frame of rows. 63 | ```sql 64 | SELECT *, 65 | LAST_VALUE(sales_amount) OVER (PARTITION BY region ORDER BY sales_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_sale_amount 66 | FROM sales_data; 67 | ``` 68 | 69 | ### NTH_VALUE() 70 | 71 | Retrieve the value of a specified column from the nth row within a defined window or frame of rows within a result set. 72 | 73 | ```sql 74 | NTH_VALUE(column_name, n) OVER ( 75 | PARTITION BY partition_column 76 | ORDER BY order_column 77 | ROWS BETWEEN unbounded preceding AND unbounded following 78 | ) AS nth_value_result 79 | ``` 80 | 81 | ### LAG() 82 | Retrieves the value of a specified column from the previous row 83 | ```sql 84 | SELECT employee_name, salary, 85 | LAG(salary, 1) OVER (PARTITION BY department ORDER BY hire_date) AS previous_salary 86 | FROM employees; 87 | ``` 88 | 89 | ### LEAD() 90 | Retrieves the value of a specified column from the next row 91 | ```sql 92 | #syntex 93 | LEAD(column_name, n) OVER ( 94 | PARTITION BY partition_column 95 | ORDER BY order_column 96 | ) AS leading_value 97 | ``` -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # SQL Commands 2 | 3 | ### Types of SQL Commands 4 | ![Types of SQL Commands](https://techieshouts.com/wp-content/uploads/2019/08/SQL-Commands.png) --------------------------------------------------------------------------------