├── .gitmodules ├── 0]_SQL ├── 1]_Basic Select │ ├── 01_Revising the Select Query I │ │ └── Revising the Select Query I.mysql │ ├── 02_Revising the Select Query II │ │ └── Revising the Select Query II.mysql │ ├── 03_Select All │ │ └── Select All.mysql │ ├── 04_Select By ID │ │ └── Select By ID.mysql │ ├── 05_Japanese Cities- Attributes │ │ └── Japanese Cities' Attributes.mysql │ ├── 06_Japanese Cities- Names │ │ └── Japanese Cities' Names.mysql │ ├── 07_Weather Observation Station 1 │ │ └── Weather Observation Station 1.mysql │ ├── 08_Weather Observation Station 3 │ │ └── Weather Observation Station 3.mysql │ ├── 09_Weather Observation Station 4 │ │ └── Weather Observation Station 4.mysql │ ├── 10_Weather Observation Station 5 │ │ └── Weather Observation Station 5.mysql │ ├── 11_Weather Observation Station 6 │ │ └── Weather Observation Station 6.mysql │ ├── 12_Weather Observation Station 7 │ │ └── Weather Observation Station 7.mysql │ ├── 13_Weather Observation Station 8 │ │ └── Weather Observation Station 8.mysql │ ├── 14_Weather Observation Station 9 │ │ └── Weather Observation Station 9.mysql │ ├── 15_Weather Observation Station 10 │ │ └── Weather Observation Station 10.mysql │ ├── 16_Weather Observation Station 11 │ │ └── Weather Observation Station 11.mysql │ ├── 17_Weather Observation Station 12 │ │ └── Weather Observation Station 12.mysql │ ├── 18_Higher Than 75 Marks │ │ └── Higher Than 75 Marks.mysql │ ├── 19_Employee Names │ │ └── Employee Names.mysql │ └── 20_Employee Salaries │ │ └── Employee Salaries.mysql ├── 2]_Advanced Select │ ├── 01_Type of Triangle │ │ └── Type of Triangle.mysql │ ├── 02_The PADS │ │ └── The PADS.mysql │ ├── 03_Occupations │ │ └── Occupations.mysql │ ├── 04_Binary Tree Nodes │ │ └── Binary Tree Nodes.mysql │ └── 05_New Companies │ │ └── New Companies.mysql ├── 3]_Aggregation │ ├── 01_Revising Aggregations - The Count Function │ │ └── Revising Aggregations - The Count Function.mysql │ ├── 02_Revising Aggregations - The Sum Function │ │ └── Revising Aggregations - The Sum Function.mysql │ ├── 03_Revising Aggregations - Averages │ │ └── Revising Aggregations - Averages.mysql │ ├── 04_Average Population │ │ └── Average Population.mysql │ ├── 05_Japan Population │ │ └── Japan Population.mysql │ ├── 06_Population Density Difference │ │ └── Population Density Difference.mysql │ ├── 07_The Blunder │ │ └── The blunder.mysql │ ├── 08_Top Earners │ │ └── Top Earners.mysql │ ├── 09_Weather Observation Station 2 │ │ └── Weather Observation Station 2.mysql │ ├── 10_Weather Observation Station 13 │ │ └── Weather Observation Station 13.mysql │ ├── 11_Weather Observation Station 14 │ │ └── Weather Observation Station 14.mysql │ ├── 12_Weather Observation Station 15 │ │ └── Weather Observation Station 15.mysql │ ├── 13_Weather Observation Station 16 │ │ └── Weather Observation Station 16.mysql │ ├── 14_Weather Observation Station 17 │ │ └── Weather Observation Station 17 .mysql │ ├── 15_Weather Observation Station 18 │ │ └── Weather Observation Station 18.mysql │ ├── 16_Weather Observation Station 19 │ │ └── Weather Observation Station 19.mysql │ └── 17_Weather Observation Station 20 │ │ └── Weather Observation Station 20.mysql ├── 4]_Basic Join │ ├── 01_Asian Population │ │ └── Asian Population.mysql │ ├── 02_African Cities │ │ └── African Cities.mysql │ ├── 03_Average Population of Each Continent │ │ └── Average Population of Each Continent.mysql │ ├── 04_The Report │ │ └── The Report.mysql │ ├── 05_Top Competitors │ │ └── Top Competitors.mysql │ ├── 06_Ollivander-s Inventory │ │ └── Ollivander's Inventory.mysql │ ├── 07_Challenges │ │ └── Challenges.mysql │ ├── 08_Contest Leaderboard │ │ └── Contest Leaderboard.mysql │ └── 09_Population Census │ │ └── Population Census.mysql ├── 5]_Advanced Join │ ├── 1_Projects │ │ └── Projects.mysql │ ├── 2_Placements │ │ └── Placements.mysql │ ├── 3_Symmetric Pairs │ │ └── Symmetric Pairs.mysql │ ├── 4_Interviews │ │ └── Interviews.mysql │ └── 5_15 Days of Learning SQL │ │ └── 15 Days of Learning SQL.mysql ├── 6]_Alternate Queries │ ├── 1_Draw the Triangle 1 │ │ └── Draw the Triangle 1.mysql │ ├── 2_Draw the Triangle 2 │ │ └── Draw the Triangle 2.mysql │ └── 3_Print Prime Numbers │ │ └── Print Prime Numbers.mysql └── LeetCodeSQL50.md ├── 1]_SQL_Conventional ├── README.md └── StyleGuide.md ├── A]_PSQL (Postgresql) ├── Problems.sql ├── README.md └── schema_setup.sql ├── B]_PL-SQL (Oracle) ├── Gaut_notes │ └── DBMS │ │ ├── Assignment │ │ ├── Assignment_1 │ │ │ ├── assignment_1(0) │ │ │ │ ├── Maiyani Gautam-312025.doc │ │ │ │ ├── assign0_SQLverysimple.pdf │ │ │ │ └── dp_0.txt │ │ │ ├── assignment_1(a) │ │ │ │ ├── assign1a_SQLsimple.pdf │ │ │ │ └── dbms_1a.txt │ │ │ └── assignment_1(b) │ │ │ │ ├── Maiyani Gautam-312025.docx │ │ │ │ ├── Maiyani-Gautam-312025.doc │ │ │ │ ├── Maiyani_Gautam_312025(1b).docx │ │ │ │ ├── assgn1b_sql.pdf │ │ │ │ ├── dbms-1b(p-2).txt │ │ │ │ ├── dbms1b(p1).txt │ │ │ │ └── dbms_1b(p-1).txt │ │ └── Assignment_2&3 │ │ │ └── Maiyani Gautam-412033(new seat no) ass_2&3.doc │ │ ├── IntroDBMS_ERModelAnjali (1).pptx │ │ ├── Neha DBMS Full n Final.pdf │ │ ├── NormalizationAnjali.pptx │ │ ├── NormalizationAnjali_Part1.pptx │ │ ├── PDF's │ │ └── 1. IntroDBMS_ERModelAnjali.pdf │ │ ├── RelationalModelAnjali (1).pptx │ │ ├── RelationalModelAnjali.pptx │ │ ├── SQLPresentationAnjaliPseudoIndexing.pptx │ │ ├── SQLPresentationAnjaliSubQueries1Feb2022.pptx │ │ ├── SQLPresentationAnjaliSubQueriesdone.pptx │ │ ├── SQLPresentationAnjaliViewsTransactionControl.pptx │ │ ├── SQLPresentationAnjali_Joins_DateManipulationsdone.pptx │ │ ├── SQL_Part1_AnjaliJivani_DDL_DML_Select.pptx │ │ ├── SQL_Part2_AnjaliJivani_GroupBy_SubQuery_StrngFns_DUAL.pptx │ │ ├── SQL_Part3_AnjaliJivani_JoinsDateManipulationPseudoIndexing.pptx │ │ ├── SQL_Part4_AnjaliJivani_SynonymSetOperatorsViewTranControlAdvSQL.pptx │ │ ├── assignment-dbms │ │ ├── DBMSASSIGNMENT3PART2QUE1.docx │ │ ├── DBMSASSIGNMENT3PART2QUE2.docx │ │ ├── DBMSASSIGNMENT3PART2QUE3.docx │ │ ├── DBMSASSIGNMENT3PART2QUE4.docx │ │ └── PLSQL5.pdf │ │ ├── sql-sq.pdf │ │ └── ~$SQLPresentationAnjali_Joins_DateManipulationsdone.pptx ├── Notes.md ├── Oracle Notes │ ├── 1]_Oracle baby │ │ ├── Assignment_12Feb2024.pdf │ │ ├── ORACLE_SETUP_BACKUP.md │ │ ├── Oracle Basics │ │ │ ├── data-definition.sql │ │ │ ├── data-types.sql │ │ │ ├── joining-tables.sql │ │ │ ├── oracle-date-functions.sql │ │ │ ├── oracle-identity-column.sql │ │ │ ├── oracle-insert.sql │ │ │ ├── oracle-string-functions.sql │ │ │ ├── oracle-subquery.sql │ │ │ ├── set-operators.sql │ │ │ └── with-clause.sql │ │ ├── Oracle Database Administration │ │ │ ├── Roles.sql │ │ │ └── users-and-privileges.sql │ │ ├── OracleSQL_AnalyticalFunctions_2024.pdf │ │ ├── README.md │ │ ├── oracle-analytic-functions.sql │ │ ├── oracle-comparison-functions.sql │ │ ├── oracle-db │ │ │ ├── ot_create_user.sql │ │ │ ├── ot_data.sql │ │ │ ├── ot_drop.sql │ │ │ └── ot_schema.sql │ │ ├── oracle-groupings.sql │ │ ├── oracle-index.sql │ │ ├── oracle-merge.sql │ │ ├── oracle-sample-database.sql │ │ ├── oracle-view.sql │ │ ├── synchronized-backup.sql │ │ ├── temporary-tables.sql │ │ ├── transaction-control.sql │ │ ├── truncate.sql │ │ └── virtual-column.sql │ └── 2]_Traner_notes │ │ ├── assignments │ │ ├── 1. Assignment for 31-Jan-2024 │ │ │ ├── 1]_Normalization Prac │ │ │ │ ├── NF.txt │ │ │ │ └── Normalization exercersie.xlsx │ │ │ ├── 2]_DDL & DML │ │ │ │ ├── 162338_nex1_31Jan24.sql │ │ │ │ ├── 162338_nex2_31Jan24.sql │ │ │ │ ├── README.md │ │ │ │ └── school_schema.dbml │ │ │ └── 3]_20 Questions (exercise 1 and 2) │ │ │ │ ├── 162338_hr_31Jan24.sql │ │ │ │ ├── 162338_nex1_practice_31Jan24.sql │ │ │ │ └── 162338_nex2_practice1_31Jan24.sql │ │ ├── 2. Assignment for 02-Feb-2024 │ │ │ ├── 162338_Assignment_001.xlsx │ │ │ ├── 162338_Assignment_002.sql │ │ │ ├── 162338_Assignment_003.sql │ │ │ ├── 162338_Assignment_004.sql │ │ │ ├── 162338_Assignment_005.sql │ │ │ ├── normalization.txt │ │ │ └── touch-assignment.sh │ │ ├── 3. Assignment for 03-Feb-2024 │ │ │ ├── Assignment_006.sql │ │ │ ├── Assignment_007.sql │ │ │ ├── Assignment_008.sql │ │ │ ├── Assignment_009.sql │ │ │ ├── Assignment_010.sql │ │ │ └── OUTPUT.md │ │ ├── 4. Assignment for 10-Feb-2024 │ │ │ ├── 0. Oracle_Northwind_CreateUser.sql │ │ │ ├── 1. Oracle_Northwind_CreateObjects.sql │ │ │ ├── 2. Oracle_Northwind_InsertData.sql │ │ │ ├── 3. Oracle_Northwind_DropTables.sql │ │ │ ├── 4. DQL_Analysis.sql │ │ │ ├── 4. Oracle_Northwind_DQL.sql │ │ │ ├── Assignment_Northwind Database_v_1_0.pdf │ │ │ └── README.md │ │ ├── 5. Assignment for 12-Feb-2024 │ │ │ ├── Assignment_12Feb2024.pdf │ │ │ └── Oracle_Northwind_DQL.sql │ │ ├── 6. Assignment for 14-Feb-2024 │ │ │ ├── 06.Assignment_14Feb2024.pdf │ │ │ ├── OUTPUT.md │ │ │ └── Oracle_Northwind_DQL.sql │ │ ├── 7. Assignment for 21-Feb-2024 │ │ │ ├── 07.Assignment_21Feb2024.pdf │ │ │ └── Assignment_21Feb24_162338.doc .sql │ │ └── README.md │ │ ├── day's.sql │ │ ├── notes-from-trainer │ │ ├── DAY2_25jan24.sql │ │ ├── DAY3_29jan24.sql │ │ ├── DAY4_30jan24.sql │ │ ├── DAY4_30jan24_createuser.sql │ │ └── Day2_NormalizationtoDDL_25JAN24.sql │ │ └── work_with_shree.sql ├── PL-SQL │ ├── README.md │ ├── SQL Developer │ │ └── PlayGroundSQL.sql │ ├── plsql-collections.sql │ ├── plsql-cursor.sql │ ├── plsql-exception.sql │ ├── plsql-functions-&-procedure.SQL │ ├── plsql-package.sql │ ├── plsql-trigger.sql │ ├── plsql-tutorial-plsql-record.sql │ └── tuts.sql ├── PLSQL-Revision.txt ├── PROJECT │ └── README.md ├── README.md ├── SETUP.md ├── SQL-Revision.txt └── social_media.sql ├── LICENSE ├── README.md ├── Res ├── HackerRankSql.jpg └── LeetCodeSql.jpg ├── common-notes.sql └── tuts.sql /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "B]_PL-SQL (Oracle)/PROJECT/Online-Bookstore-Management-System"] 2 | path = B]_PL-SQL (Oracle)/PROJECT/Online-Bookstore-Management-System 3 | url = https://github.com/Ayon-SSP/Online-Bookstore-Management-System/ 4 | -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/01_Revising the Select Query I/Revising the Select Query I.mysql: -------------------------------------------------------------------------------- 1 | select * from city 2 | where countrycode='USA' and population>100000; -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/02_Revising the Select Query II/Revising the Select Query II.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select name from city 9 | where population > 120000 and countrycode='USA'; -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/03_Select All/Select All.mysql: -------------------------------------------------------------------------------- 1 | select * from city; -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/04_Select By ID/Select By ID.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select * from city 9 | where id=1661; -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/05_Japanese Cities- Attributes/Japanese Cities' Attributes.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | 9 | select * from city 10 | where countrycode='JPN'; -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/06_Japanese Cities- Names/Japanese Cities' Names.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select name from city 9 | where COUNTRYCODE ='JPN'; -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/07_Weather Observation Station 1/Weather Observation Station 1.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | 9 | select city,state from station; -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/08_Weather Observation Station 3/Weather Observation Station 3.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Enter your query here and follow these instructions: 3 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 4 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 5 | 3. Type your code immediately after comment. Don't leave any blank line. 6 | */ 7 | 8 | select distinct city from station 9 | where MOD(ID,2)=0 10 | ORDER BY city; -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/09_Weather Observation Station 4/Weather Observation Station 4.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select count(city) - count(distinct city) from station; -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/10_Weather Observation Station 5/Weather Observation Station 5.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | 9 | select city,length(city) 10 | from station 11 | order by length(city),city limit 1; 12 | 13 | select city,length(city) 14 | from station 15 | order by length(city) desc,city limit 1; -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/11_Weather Observation Station 6/Weather Observation Station 6.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select distinct city from station 9 | where left(city,1) IN ('A','E','I','O','U'); -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/12_Weather Observation Station 7/Weather Observation Station 7.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select distinct city from station 9 | where right(city,1) IN ('a','e','i','o','u'); -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/13_Weather Observation Station 8/Weather Observation Station 8.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select distinct city from station 9 | where lower(right(city,1)) IN ('a','e','i','o','u') and lower(left(city,1)) in ('a','e','i','o','u'); -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/14_Weather Observation Station 9/Weather Observation Station 9.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select distinct city from station 9 | where lower(left(city,1)) not in ('a','e','i','o','u'); 10 | 11 | -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/15_Weather Observation Station 10/Weather Observation Station 10.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select distinct city from station 9 | where lower(right(city,1)) not in ('a','e','i','o','u'); -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/16_Weather Observation Station 11/Weather Observation Station 11.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Enter your query here and follow these instructions: 3 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 4 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 5 | 3. Type your code immediately after comment. Don't leave any blank line. 6 | */ 7 | select distinct city from station 8 | where lower(right(city,1)) not in ('a','e','i','o','u') or lower(left(city,1)) not in ('a','e','i','o','u'); 9 | 10 | -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/17_Weather Observation Station 12/Weather Observation Station 12.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Enter your query here and follow these instructions: 3 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 4 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 5 | 3. Type your code immediately after comment. Don't leave any blank line. 6 | */ 7 | select distinct city from station 8 | where lower(right(city,1)) not in ('a','e','i','o','u') and lower(left(city,1)) not in ('a','e','i','o','u'); -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/18_Higher Than 75 Marks/Higher Than 75 Marks.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | 9 | select name from students 10 | where marks > 75 11 | order by right(name,3),id asc; -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/19_Employee Names/Employee Names.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select name from employee 9 | order by name; -------------------------------------------------------------------------------- /0]_SQL/1]_Basic Select/20_Employee Salaries/Employee Salaries.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select name from employee 9 | where salary > 2000 and months < 10 10 | order by employee_id asc; 11 | -------------------------------------------------------------------------------- /0]_SQL/2]_Advanced Select/01_Type of Triangle/Type of Triangle.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | 9 | 10 | select case 11 | when A + B <= C OR A + C <= B OR B + C <= A then 'Not A Triangle' 12 | when A = B and B = C then 'Equilateral' 13 | when A = B or B = C or A = C then 'Isosceles' 14 | else 'Scalene' 15 | end 16 | from TRIANGLES; -------------------------------------------------------------------------------- /0]_SQL/2]_Advanced Select/02_The PADS/The PADS.mysql: -------------------------------------------------------------------------------- 1 | select concat(NAME,'(',substr(OCCUPATION,1,1),')') as N 2 | from OCCUPATIONS 3 | order by N; 4 | select concat('There are a total of ',count(OCCUPATION),' ',lower(OCCUPATION),'s.') 5 | from OCCUPATIONS 6 | group by OCCUPATION 7 | order by count(OCCUPATION), OCCUPATION; 8 | -------------------------------------------------------------------------------- /0]_SQL/2]_Advanced Select/03_Occupations/Occupations.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- MySQL 3 | */ 4 | SET @r1=0, @r2=0, @r3=0, @r4=0; 5 | SELECT MIN(DOCTOR), MIN(PROFESSOR), MIN(SINGER), MIN(ACTOR) 6 | FROM( 7 | SELECT CASE WHEN OCCUPATION = 'Doctor' THEN (@r1:=@r1+1) 8 | WHEN OCCUPATION = 'Professor' THEN (@r2:=@r2+1) 9 | WHEN OCCUPATION = 'Singer' THEN (@r3:=@r3+1) 10 | WHEN OCCUPATION = 'Actor' THEN (@r4:=@r4+1) END AS RowNumber, 11 | CASE WHEN OCCUPATION = 'Doctor' THEN Name END AS Doctor, 12 | CASE WHEN OCCUPATION = 'Professor' THEN Name END AS Professor, 13 | CASE WHEN OCCUPATION = 'Singer' THEN Name END AS Singer, 14 | CASE WHEN OCCUPATION = 'Actor' THEN Name END AS Actor 15 | FROM OCCUPATIONS 16 | ORDER BY NAME 17 | ) Temp 18 | GROUP BY RowNumber; 19 | -------------------------------------------------------------------------------- /0]_SQL/2]_Advanced Select/04_Binary Tree Nodes/Binary Tree Nodes.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working platform:- DB2, MySQL, Oracle, MS SQL Server 3 | */ 4 | SELECT N, CASE WHEN P IS NULL THEN 'Root' 5 | WHEN(SELECT COUNT(*) FROM BST WHERE P = A.N) > 0 THEN 'Inner' 6 | ELSE 'Leaf' 7 | END 8 | FROM BST A 9 | ORDER BY N; 10 | -------------------------------------------------------------------------------- /0]_SQL/2]_Advanced Select/05_New Companies/New Companies.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working platform:- DB2, MySQL, Oracle, MS SQL Server 3 | */ 4 | SELECT COMPANY_CODE, FOUNDER, 5 | (SELECT COUNT(DISTINCT LEAD_MANAGER_CODE) FROM LEAD_MANAGER WHERE COMPANY_CODE = C.COMPANY_CODE), 6 | (SELECT COUNT(DISTINCT SENIOR_MANAGER_CODE) FROM SENIOR_MANAGER WHERE COMPANY_CODE = C.COMPANY_CODE), 7 | (SELECT COUNT(DISTINCT MANAGER_CODE) FROM MANAGER WHERE COMPANY_CODE = C.COMPANY_CODE), 8 | (SELECT COUNT(DISTINCT EMPLOYEE_CODE) FROM EMPLOYEE WHERE COMPANY_CODE = C.COMPANY_CODE) 9 | FROM COMPANY C 10 | ORDER BY COMPANY_CODE; 11 | -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/01_Revising Aggregations - The Count Function/Revising Aggregations - The Count Function.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select count(*) 9 | from city 10 | where population > 100000; -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/02_Revising Aggregations - The Sum Function/Revising Aggregations - The Sum Function.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | 9 | select sum(population) from city 10 | where district='California'; -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/03_Revising Aggregations - Averages/Revising Aggregations - Averages.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select avg(population) from city 9 | where district='California'; -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/04_Average Population/Average Population.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select floor(avg(population)) from city; -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/05_Japan Population/Japan Population.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select sum(population) from city where countrycode = 'JPN'; -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/06_Population Density Difference/Population Density Difference.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select max(population)- min(population) from city; -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/07_The Blunder/The blunder.mysql: -------------------------------------------------------------------------------- 1 | select ceiling(avg(salary)-avg(replace(salary,'0',''))) from employees; -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/08_Top Earners/Top Earners.mysql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Enter your query here and follow these instructions: 4 | 1. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. 5 | 2. The AS keyword causes errors, so follow this convention: "Select t.Field From table1 t" instead of "select t.Field From table1 AS t" 6 | 3. Type your code immediately after comment. Don't leave any blank line. 7 | */ 8 | select max(months*salary), count(*) 9 | from employee 10 | where (months*salary) = (select max(months*salary) from employee); -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/09_Weather Observation Station 2/Weather Observation Station 2.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- Oracle, MySQL 3 | */ 4 | select round(sum(LAT_N),2), round(sum(LONG_W),2) 5 | from station; -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/10_Weather Observation Station 13/Weather Observation Station 13.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Enter your query here. 3 | */ 4 | 5 | select round(sum(LAT_N),4) 6 | from STATION 7 | where LAT_N > 38.7880 and LAT_N < 137.2345; -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/11_Weather Observation Station 14/Weather Observation Station 14.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- MySQL, Oracle 3 | */ 4 | SELECT ROUND(MAX(LAT_N),4) 5 | FROM STATION 6 | WHERE LAT_N < 137.2345; 7 | -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/12_Weather Observation Station 15/Weather Observation Station 15.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Enter your query here. 3 | */ 4 | select round(LONG_W,4) 5 | from STATION 6 | where LAT_N = (select max(LAT_N) from STATION where LAT_N < 137.2345); -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/13_Weather Observation Station 16/Weather Observation Station 16.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Enter your query here. 3 | */ 4 | 5 | select round(min(LAT_N),4) 6 | from STATION 7 | where LAT_N > 38.7780; 8 | -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/14_Weather Observation Station 17/Weather Observation Station 17 .mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- MySQL, Oracle 3 | */ 4 | SELECT ROUND(LONG_W,4) 5 | FROM STATION 6 | WHERE LAT_N = ( 7 | SELECT MIN(LAT_N) 8 | FROM STATION 9 | WHERE LAT_N > 38.7780 10 | ); 11 | -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/15_Weather Observation Station 18/Weather Observation Station 18.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- MySQL, Oracle 3 | */ 4 | -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/16_Weather Observation Station 19/Weather Observation Station 19.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Enter your query here. 3 | */ 4 | select round(sqrt(power(min(LAT_N)-max(LAT_N),2)+power(min(LONG_W)-max(LONG_W),2)),4) 5 | from STATION; 6 | -------------------------------------------------------------------------------- /0]_SQL/3]_Aggregation/17_Weather Observation Station 20/Weather Observation Station 20.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- MySQL, Oracle 3 | */ 4 | SELECT ROUND(S.LAT_N, 4) FROM STATION S 5 | WHERE 6 | (SELECT COUNT(LAT_N) FROM STATION WHERE LAT_N > S.LAT_N) 7 | = (SELECT COUNT(LAT_N) FROM STATION WHERE LAT_N < S.LAT_N); 8 | -------------------------------------------------------------------------------- /0]_SQL/4]_Basic Join/01_Asian Population/Asian Population.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- MySQL, Oracle, MS SQL Server 3 | */ 4 | SELECT SUM(CITY.POPULATION) 5 | FROM CITY 6 | INNER JOIN COUNTRY 7 | ON CITY.COUNTRYCODE = COUNTRY.CODE 8 | WHERE COUNTRY.CONTINENT = 'Asia'; 9 | -------------------------------------------------------------------------------- /0]_SQL/4]_Basic Join/02_African Cities/African Cities.mysql: -------------------------------------------------------------------------------- 1 | select CITY.NAME 2 | from CITY 3 | inner join COUNTRY 4 | on CITY.COUNTRYCODE = COUNTRY.CODE 5 | where COUNTRY.CONTINENT = 'Africa'; 6 | -------------------------------------------------------------------------------- /0]_SQL/4]_Basic Join/03_Average Population of Each Continent/Average Population of Each Continent.mysql: -------------------------------------------------------------------------------- 1 | select country.continent, floor(avg(city.population)) 2 | from city 3 | inner join country 4 | on city.countrycode = country.code 5 | group by country.continent; -------------------------------------------------------------------------------- /0]_SQL/4]_Basic Join/04_The Report/The Report.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working platform:- MySQL 3 | */ 4 | SELECT IF(GRADES.GRADE>=8, STUDENTS.NAME, NULL),GRADES.GRADE, STUDENTS.MARKS 5 | FROM GRADES, STUDENTS 6 | WHERE STUDENTS.MARKS BETWEEN GRADES.MIN_MARK AND GRADES.MAX_MARK 7 | ORDER BY GRADES.GRADE DESC, STUDENTS.NAME; 8 | -------------------------------------------------------------------------------- /0]_SQL/4]_Basic Join/05_Top Competitors/Top Competitors.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working platform:- MySQL 3 | */ 4 | SELECT H.HACKER_ID, H.NAME 5 | FROM HACKERS H 6 | INNER JOIN SUBMISSIONS S 7 | ON H.HACKER_ID = S.HACKER_ID 8 | INNER JOIN CHALLENGES C 9 | ON S.CHALLENGE_ID = C.CHALLENGE_ID 10 | INNER JOIN DIFFICULTY D 11 | ON C.DIFFICULTY_LEVEL = D.DIFFICULTY_LEVEL 12 | WHERE S.SCORE = D.SCORE AND C.DIFFICULTY_LEVEL = D.DIFFICULTY_LEVEL 13 | GROUP BY H.HACKER_ID, H.NAME 14 | HAVING COUNT(S.HACKER_ID) > 1 15 | ORDER BY COUNT(S.HACKER_ID) DESC, S.HACKER_ID ASC; 16 | -------------------------------------------------------------------------------- /0]_SQL/4]_Basic Join/06_Ollivander-s Inventory/Ollivander's Inventory.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- DB2, MySQL, MS SQL Server 3 | */ 4 | SELECT W.ID, P.AGE, W.COINS_NEEDED, W.POWER 5 | FROM WANDS AS W 6 | JOIN WANDS_PROPERTY AS P 7 | ON (W.CODE = P.CODE) 8 | WHERE P.IS_EVIL = 0 AND W.COINS_NEEDED = (SELECT MIN(COINS_NEEDED) 9 | FROM WANDS AS X 10 | JOIN WANDS_PROPERTY AS Y 11 | ON (X.CODE = Y.CODE) 12 | WHERE X.POWER = W.POWER AND Y.AGE = P.AGE) 13 | ORDER BY W.POWER DESC, P.AGE DESC; 14 | -------------------------------------------------------------------------------- /0]_SQL/4]_Basic Join/07_Challenges/Challenges.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working platform:- MySQL 3 | */ 4 | SELECT H.HACKER_ID, 5 | H.NAME, 6 | COUNT(C.CHALLENGE_ID) AS C_COUNT 7 | FROM HACKERS H 8 | JOIN CHALLENGES C ON C.HACKER_ID = H.HACKER_ID 9 | GROUP BY H.HACKER_ID, H.NAME 10 | HAVING C_COUNT = 11 | (SELECT COUNT(C2.CHALLENGE_ID) AS C_MAX 12 | FROM CHALLENGES AS C2 13 | GROUP BY C2.HACKER_ID 14 | ORDER BY C_MAX DESC LIMIT 1) 15 | OR C_COUNT IN 16 | (SELECT DISTINCT C_COMPARE AS C_UNIQUE 17 | FROM (SELECT H2.HACKER_ID, 18 | H2.NAME, 19 | COUNT(CHALLENGE_ID) AS C_COMPARE 20 | FROM HACKERS H2 21 | JOIN CHALLENGES C ON C.HACKER_ID = H2.HACKER_ID 22 | GROUP BY H2.HACKER_ID, H2.NAME) COUNTS 23 | GROUP BY C_COMPARE 24 | HAVING COUNT(C_COMPARE) = 1) 25 | ORDER BY C_COUNT DESC, H.HACKER_ID; 26 | -------------------------------------------------------------------------------- /0]_SQL/4]_Basic Join/08_Contest Leaderboard/Contest Leaderboard.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- MySQL 3 | */ 4 | SELECT X.hacker_id, 5 | (SELECT H.NAME FROM HACKERS H 6 | WHERE H.HACKER_ID = X.HACKER_ID) NAME, 7 | SUM(X.SCORE) TOTAL_SCORE FROM 8 | (SELECT HACKER_ID, MAX(SCORE) SCORE FROM SUBMISSIONS S 9 | GROUP BY 1, S.CHALLENGE_ID) X 10 | GROUP BY 1 11 | HAVING TOTAL_SCORE > 0 12 | ORDER BY TOTAL_SCORE DESC, HACKER_ID; 13 | -------------------------------------------------------------------------------- /0]_SQL/4]_Basic Join/09_Population Census/Population Census.mysql: -------------------------------------------------------------------------------- 1 | select sum(city.population) 2 | from CITY 3 | inner join COUNTRY 4 | on CITY.CountryCode = COUNTRY.Code 5 | where COUNTRY.CONTINENT = 'Asia'; -------------------------------------------------------------------------------- /0]_SQL/5]_Advanced Join/1_Projects/Projects.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- MySQL 3 | */ 4 | SELECT START_DATE, X FROM ( 5 | SELECT A.START_DATE, MIN(B.END_DATE) AS X 6 | FROM 7 | (SELECT START_DATE FROM PROJECTS WHERE START_DATE NOT IN (SELECT END_DATE FROM PROJECTS)) A, 8 | (SELECT END_DATE FROM PROJECTS WHERE END_DATE NOT IN (SELECT START_DATE FROM PROJECTS)) B 9 | WHERE START_DATE < END_DATE 10 | GROUP BY A.START_DATE 11 | ) P 12 | ORDER BY DATEDIFF(X, START_DATE), START_DATE; 13 | -------------------------------------------------------------------------------- /0]_SQL/5]_Advanced Join/2_Placements/Placements.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- DB2, MySQL, Oracle, MS SQL Server 3 | */ 4 | Select S.NAME 5 | FROM STUDENTS S 6 | JOIN FRIENDS F ON S.ID = F.ID 7 | JOIN PACKAGES P1 ON S.ID = P1.ID 8 | JOIN PACKAGES P2 ON F.FRIEND_ID = P2.ID 9 | WHERE P2.SALARY > P1.SALARY 10 | ORDER BY P2.SALARY; 11 | -------------------------------------------------------------------------------- /0]_SQL/5]_Advanced Join/3_Symmetric Pairs/Symmetric Pairs.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- DB2, MySQL, Oracle, MS SQL Server 3 | */ 4 | SELECT X, Y FROM FUNCTIONS F1 5 | WHERE EXISTS(SELECT * FROM FUNCTIONS F2 WHERE F2.Y = F1.X 6 | AND F2.X = F1.Y AND F2.X > F1.X) AND (X != Y) 7 | UNION 8 | SELECT X,Y FROM FUNCTIONS F1 WHERE X = Y AND 9 | ((SELECT COUNT(*) FROM FUNCTIONS WHERE X = F1.X AND Y = F1.X) > 1) 10 | ORDER BY X; 11 | -------------------------------------------------------------------------------- /0]_SQL/5]_Advanced Join/4_Interviews/Interviews.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- MySQL 3 | */ 4 | SELECT A.CONTEST_ID, A.HACKER_ID, A.NAME, 5 | SUM(TOTAL_SUBMISSIONS) AS TOTAL_SUBMISSIONS, 6 | SUM(TOTAL_ACCEPTED_SUBMISSIONS) AS TOTAL_ACCEPTED_SUBMISSIONS, 7 | SUM(TOTAL_VIEWS) AS TOTAL_VIEWS, 8 | SUM(TOTAL_UNIQUE_VIEWS) AS TOTAL_UNIQUE_VIEWS 9 | FROM CONTESTS AS A 10 | LEFT JOIN COLLEGES AS B 11 | ON A.CONTEST_ID = B.CONTEST_ID 12 | LEFT JOIN CHALLENGES AS C 13 | ON B.COLLEGE_ID = C.COLLEGE_ID 14 | LEFT JOIN (SELECT CHALLENGE_ID, SUM(TOTAL_VIEWS) AS TOTAL_VIEWS, 15 | SUM(TOTAL_UNIQUE_VIEWS) AS TOTAL_UNIQUE_VIEWS 16 | FROM VIEW_STATS 17 | GROUP BY CHALLENGE_ID) AS D 18 | ON C.CHALLENGE_ID = D.CHALLENGE_ID 19 | LEFT JOIN (SELECT CHALLENGE_ID, SUM(TOTAL_SUBMISSIONS) AS TOTAL_SUBMISSIONS, 20 | SUM(TOTAL_ACCEPTED_SUBMISSIONS) AS TOTAL_ACCEPTED_SUBMISSIONS 21 | FROM SUBMISSION_STATS 22 | GROUP BY CHALLENGE_ID) AS E 23 | ON C.CHALLENGE_ID = E.CHALLENGE_ID 24 | GROUP BY A.CONTEST_ID, A.HACKER_ID, A.NAME 25 | HAVING (TOTAL_SUBMISSIONS + TOTAL_ACCEPTED_SUBMISSIONS + TOTAL_VIEWS + TOTAL_UNIQUE_VIEWS) > 0 26 | ORDER BY A.CONTEST_ID; 27 | -------------------------------------------------------------------------------- /0]_SQL/5]_Advanced Join/5_15 Days of Learning SQL/15 Days of Learning SQL.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- MySQL 3 | */ 4 | SELECT SUBMISSION_DATE, 5 | (SELECT COUNT(DISTINCT HACKER_ID) 6 | FROM SUBMISSIONS S2 7 | WHERE S2.SUBMISSION_DATE = S1.SUBMISSION_DATE AND 8 | (SELECT COUNT(DISTINCT S3.SUBMISSION_DATE) 9 | FROM SUBMISSIONS S3 WHERE S3.HACKER_ID = S2.HACKER_ID AND S3.SUBMISSION_DATE < S1.SUBMISSION_DATE) = DATEDIFF(S1.SUBMISSION_DATE , '2016-03-01')), 10 | (SELECT HACKER_ID FROM SUBMISSIONS S2 WHERE S2.SUBMISSION_DATE = S1.SUBMISSION_DATE 11 | GROUP BY HACKER_ID ORDER BY COUNT(SUBMISSION_ID) DESC, HACKER_ID LIMIT 1) AS TMP, 12 | (SELECT NAME FROM HACKERS WHERE HACKER_ID = TMP) 13 | FROM 14 | (SELECT DISTINCT SUBMISSION_DATE FROM SUBMISSIONS) S1 15 | GROUP BY SUBMISSION_DATE; 16 | -------------------------------------------------------------------------------- /0]_SQL/6]_Alternate Queries/1_Draw the Triangle 1/Draw the Triangle 1.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Enter your query here. 3 | */ 4 | set @TEMP:=21; 5 | select REPEAT('* ', @TEMP:= @TEMP - 1) 6 | from INFORMATION_SCHEMA.TABLES; -------------------------------------------------------------------------------- /0]_SQL/6]_Alternate Queries/2_Draw the Triangle 2/Draw the Triangle 2.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- MySQL 3 | */ 4 | SET @TEMP:=0; 5 | SELECT REPEAT('* ', @TEMP:= @TEMP + 1) 6 | FROM INFORMATION_SCHEMA.TABLES 7 | WHERE @TEMP < 20; 8 | -------------------------------------------------------------------------------- /0]_SQL/6]_Alternate Queries/3_Print Prime Numbers/Print Prime Numbers.mysql: -------------------------------------------------------------------------------- 1 | /* 2 | Working Platform:- Oracle 3 | */ 4 | SET SERVEROUTPUT ON; 5 | DECLARE 6 | COUNTER NUMBER; 7 | K NUMBER; 8 | RESULT CLOB; 9 | BEGIN 10 | RESULT := ''; 11 | FOR N IN 2..1000 LOOP 12 | COUNTER := 0; 13 | K := FLOOR(N/2); 14 | FOR i IN 2..K LOOP 15 | IF(MOD(N,i)=0) THEN 16 | COUNTER :=1; 17 | END IF; 18 | END LOOP; 19 | IF (COUNTER = 0) THEN 20 | RESULT := RESULT||N||'&'; 21 | END IF; 22 | END LOOP; 23 | DBMS_OUTPUT.PUT_LINE(SUBSTR(RESULT,0,length(RESULT)-1)); 24 | END; 25 | -------------------------------------------------------------------------------- /0]_SQL/LeetCodeSQL50.md: -------------------------------------------------------------------------------- 1 | ## Select 2 | ### 1757. Recyclable and Low Fat Products 3 | ```sql 4 | SELECT product_id 5 | FROM Products 6 | WHERE low_fats='Y' AND recyclable='Y'; 7 | ``` 8 | ### 584. Find Customer Referee 9 | ```sql 10 | SELECT name 11 | FROM Customer 12 | WHERE referee_id != 2 OR referee_id IS NULL; 13 | ``` 14 | ### 595. Big Countries 15 | ```sql 16 | SELECT name, population, area 17 | FROM World 18 | WHERE area >= 3000000 OR population >= 25000000; 19 | ``` 20 | ### 1148. Article Views I 21 | ```sql 22 | SELECT DISTINCT author_id AS id 23 | FROM views 24 | WHERE author_id = viewer_id 25 | ORDER BY id; 26 | ``` 27 | ### 1683. Invalid Tweets 28 | ```sql 29 | SELECT tweet_id 30 | FROM Tweets 31 | WHERE LENGTH(content) > 15; 32 | ``` 33 | 34 | ## Basic Joins 35 | ### 1378. Replace Employee ID With The Unique Identifier 36 | ```sql 37 | SELECT EmployeeUNI.unique_id, Employees.name 38 | FROM Employees 39 | LEFT JOIN EmployeeUNI 40 | ON Employees.id = EmployeeUNI.id 41 | ``` 42 | ### 1068. Product Sales Analysis I 43 | ```sql 44 | SELECT Product.product_name, Sales.year, Sales.price 45 | FROM Sales 46 | INNER JOIN Product 47 | ON Sales.product_id = Product.product_id 48 | ``` 49 | ### 1581. Customer Who Visited but Did Not Make Any Transactions 50 | ```sql 51 | SELECT Visits.customer_id, COUNT(Visits.customer_id) as count_no_trans 52 | FROM Visits 53 | LEFT JOIN Transactions 54 | ON Visits.visit_id = Transactions.visit_id 55 | WHERE Transactions.amount IS NULL 56 | GROUP BY Visits.customer_id; 57 | ``` 58 | ### 197. Rising Temperature 59 | ```sql 60 | SELECT w1.id 61 | FROM Weather as w1 62 | CROSS JOIN Weather as w2 63 | WHERE DATEDIFF(w1.recordDate, w2.recordDate) = 1 64 | AND w1.temperature > w2.temperature; 65 | ``` 66 | ### 67 | ```sql 68 | ``` 69 | ### 70 | ```sql 71 | ``` 72 | ### 73 | ```sql 74 | ``` 75 | ### 76 | ```sql 77 | ``` 78 | ### 79 | ```sql 80 | ``` 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | ## Basic Aggregate Functions 95 | ## Sorting and Grouping 96 | ## Advanced Select and Joins 97 | ## Subqueries 98 | ## Advanced String Functions / Regex / Clause -------------------------------------------------------------------------------- /1]_SQL_Conventional/README.md: -------------------------------------------------------------------------------- 1 | ### 💥 Examples of SQL Conventional [Link](https://github.com/Ayon-SSP/SQL/blob/main/B%5D_PL-SQL%20(Oracle)/Oracle%20Notes/1%5D_Oracle%20baby/README.md) 2 | 3 | > 1. **Consistency**: Use consistent formatting and naming conventions throughout your code. 4 | > 2. **Readability**: Write clear and concise code that is easy to understand. 5 | > 3. **Maintainability**: Make your code easy to modify and extend. 6 | > 4. **Performance**: Consider performance implications when writing queries. [🔑 Key Points](https://gemini.google.com/app/88fb0a8eb06acc68) 7 | 8 | ### 24 Rules to the SQL Formatting Standard [Link](https://learnsql.com/blog/24-rules-sql-code-formatting-standard/) 9 | - **Avoid** table/column in the plural ✅ `employee` instead of ❌`employees` 10 | - **CamelCase style || using '_' || paka more than one word**: eg: employee_city, employee_name 11 | - Check that the name is not already used as a keyword in SQL 12 | - For the primary key column avoid the name id. A good idea is to combine id with the name of a table, for example: id_employee. 13 | 14 | ### SQL Style Guide [Link](https://handbook.gitlab.com/handbook/business-technology/data-team/platform/sql-style-guide/) 15 | 16 | ### Trigger naming convention 17 | 18 | Certainly! Here are some more naming conventions for triggers in Oracle databases: 19 | ```sql 20 | TRG__: Naming convention where refers to the table associated with the trigger and represents the database event that triggers the action, such as INSERT, UPDATE, or DELETE. For example, TRG_EMPLOYEE_INSERT or TRG_ORDER_UPDATE. 21 | 22 | __TRG: Naming convention where represents the action that triggers the event, such as BEFORE or AFTER, and refers to the associated table. For example, BEFORE_EMPLOYEE_UPDATE_TRG or AFTER_ORDER_INSERT_TRG. 23 | 24 | _TRG_: Naming convention where represents the database event and refers to the table associated with the trigger. For example, INSERT_TRG_EMPLOYEE or UPDATE_TRG_ORDER. 25 | 26 | __TRIGGER: Naming convention where refers to the associated table, and represents the action that triggers the event. For example, EMPLOYEE_BEFORE_INSERT_TRIGGER or ORDER_AFTER_UPDATE_TRIGGER. 27 | 28 | _: Customized naming convention where is a descriptive prefix indicating the type of trigger (e.g., BEF for BEFORE triggers, AFT for AFTER triggers), and provides a brief description of the trigger's purpose. For example, BEF_EMPLOYEE_INSERT_CHECK or AFT_ORDER_UPDATE_AUDIT. 29 | 30 | ``` 31 | -------------------------------------------------------------------------------- /1]_SQL_Conventional/StyleGuide.md: -------------------------------------------------------------------------------- 1 | ```sql 2 | WITH my_data AS ( 3 | 4 | SELECT my_data.* 5 | FROM prod.my_data_with_a_long_table_name AS my_data 6 | INNER JOIN prod.other_thing 7 | WHERE my_data.filter = 'my_filter' 8 | 9 | ), 10 | 11 | some_cte AS ( 12 | 13 | SELECT DISTINCT 14 | id AS other_id, 15 | other_field_1, 16 | other_field_2, 17 | date_field_at, 18 | data_by_row, 19 | field_4, 20 | field_5, 21 | LAG( 22 | other_field_2 23 | ) OVER (PARTITION BY other_id, other_field_1 ORDER BY 5) AS previous_other_field_2 24 | FROM prod.my_other_data 25 | 26 | ), 27 | /* 28 | This is a very long comment: It is good practice to leave comments in code to 29 | explain complex logic in CTEs or business logic which may not be intuitive to 30 | someone who does not have intimate knowledge of the data source. This can help 31 | new users familiarize themselves with the code quickly. 32 | */ 33 | 34 | final AS ( 35 | 36 | SELECT 37 | -- This is a singel line comment 38 | my_data.field_1 AS detailed_field_1, 39 | my_data.field_2 AS detailed_field_2, 40 | my_data.detailed_field_3, 41 | DATE_TRUNC('month', some_cte.date_field_at) AS date_field_month, 42 | some_cte.data_by_row['id']::NUMBER AS id_field, 43 | IFF(my_data.detailed_field_3 > my_data.field_2, TRUE, FALSE) AS is_boolean, 44 | CASE 45 | WHEN my_data.cancellation_date IS NULL 46 | AND my_data.expiration_date IS NOT NULL 47 | THEN my_data.expiration_date 48 | WHEN my_data.cancellation_date IS NULL 49 | THEN my_data.start_date + 7 -- There is a reason for this number 50 | ELSE my_data.cancellation_date 51 | END AS adjusted_cancellation_date, 52 | COUNT(*) AS number_of_records, 53 | SUM(some_cte.field_4) AS field_4_sum, 54 | MAX(some_cte.field_5) AS field_5_max 55 | FROM my_data 56 | LEFT JOIN some_cte 57 | ON my_data.id = some_cte.id 58 | WHERE my_data.field_1 = 'abc' 59 | AND (my_data.field_2 = 'def' OR my_data.field_2 = 'ghi') 60 | GROUP BY 1, 2, 3, 4, 5, 6 61 | HAVING COUNT(*) > 1 62 | ORDER BY 8 DESC 63 | ) 64 | 65 | SELECT * 66 | FROM final 67 | ``` -------------------------------------------------------------------------------- /A]_PSQL (Postgresql)/Problems.sql: -------------------------------------------------------------------------------- 1 | -- /1393. Capital Gain/Loss 2 | -- https://leetcode.com/problems/capital-gainloss/?envType=study-plan&id=sql-i 3 | 4 | -- select stock_name, sum(if(operation = 'Buy',price, 0)) as total_buy, sum(if(operation = 'Sell', price , 0)) as total_sell 5 | -- from stocks 6 | -- group by stock_name; 7 | 8 | select stock_name, sum(if(operation = 'Sell', price , 0)) - sum(if(operation = 'Buy',price, 0)) as capital_gain_loss 9 | from stocks 10 | group by stock_name; 11 | 12 | 13 | 14 | 15 | 16 | -- /1407. Top Travellers 17 | # select user_id, sum(distance) as travelled_distance from rides 18 | # group by user_id 19 | # order by travelled_distance desc; 20 | 21 | select u.name, if(sum(r.distance) is null ,0,sum(r.distance)) as travelled_distance 22 | from users as u 23 | left join rides as r 24 | on u.id = r.user_id 25 | group by r.user_id 26 | order by travelled_distance desc, name; 27 | 28 | 29 | -- /1158. Market Analysis I 30 | select u.user_id as buyer_id, join_date, sum(case when year(order_date) = 2019 then 1 ELSE 0 END) as orders_in_2019 31 | from Users u left join Orders o 32 | on u.user_id = o.buyer_id 33 | group by u.user_id 34 | order by u.user_id 35 | 36 | 37 | 38 | 39 | 40 | 41 | CREATE table employee ( 42 | id serial primary key, 43 | name varchar(255) not null, 44 | department varchar(255) not null, 45 | salary int not null, 46 | phone int not null, 47 | UNIQUE (name,department), 48 | CHECK (salary > 10000), 49 | CHECK (phone > 1000000000) 50 | ); 51 | 52 | select * from employee; 53 | 54 | 55 | create table products ( 56 | prodID int primary key, 57 | ProdName varchar(225) Not null, 58 | Qty int, 59 | description varchar(225), 60 | check (Qty>0) 61 | ); 62 | 63 | create table orders( 64 | prodID int, 65 | OrderId serial primary key, 66 | Qty_sold int, 67 | check (Qty_sold > 0), 68 | constraint fk foreign key (prodID) references custm(prodID) 69 | ); 70 | 71 | 72 | 73 | 74 | create table products ( 75 | prodID int primary key, 76 | ProdName varchar(225) Not null, 77 | Qty int, 78 | description varchar(225), 79 | check (Qty>0) 80 | ); 81 | 82 | create table Orders ( 83 | prodID int, 84 | OrderId int primary key, 85 | Qty_sold int, 86 | check (Qty_sold > 0), 87 | price int, 88 | Order_date date, 89 | constraint fk foreign key (prodID) references products(prodID) 90 | 91 | ); -------------------------------------------------------------------------------- /A]_PSQL (Postgresql)/README.md: -------------------------------------------------------------------------------- 1 | # 🛢️ Postgresql 2 | 3 | ## 📚 Resources 4 | 5 | - [Pepcoding-sql](https://www.youtube.com/playlist?list=PL-Jc9J83PIiFRR58Ezyy2z3gYhPA0lKmt) 6 | - [Postgresql Docs](https://www.postgresql.org/docs/) 7 | - [Postgresql Tutorial](https://www.postgresqltutorial.com/) 8 | - [Postgresql Tutorial](https://www.postgresqltutorial.com/postgresql-cheat-sheet/) 9 | 10 | 11 | ## 👷‍♂️ Code used in my projects 12 | 📁 Repo: [Store-Monitoring `run.sql`](https://github.com/Ayon-SSP/Store-Monitoring/blob/master/src/run.sql) 13 | 14 | 15 | 16 | ## 📝 Notes 17 | 18 | ```bash 19 | user, password = ayonssp, zboy@1x1 20 | psql jwt_auth_system ayonssp 21 | ``` 22 | ```bash 23 | sudo service postgresql status 24 | sudo service postgresql start 25 | sudo service postgresql stop 26 | sudo service postgresql restart 27 | sudo service postgresql reload 28 | psql --version 29 | sudo passwd postgres 30 | 31 | ``` 32 | ```bash 33 | psql -U postgres # for linux root 34 | ``` 35 | ```bash 36 | sudo passwd postgres 37 | sudo -u postgres psql 38 | psql store_monitoring postgres 39 | ``` 40 | ```psql 41 | \l 42 | \du 43 | \dt - this shows all tables in the current schema 44 | \password postgres 45 | \q 46 | SELECT * FROM pg_catalog.pg_tables; - list all tables 47 | \c 48 | \! clear 49 | \d+ tablename - show table structure 50 | ``` 51 | > psql: [terminal-based](https://www.postgresql.org/docs/current/app-psql.html) 52 | [lisk to wsl connection](https://chloesun.medium.com/set-up-postgresql-on-wsl2-and-connect-to-postgresql-with-pgadmin-on-windows-ca7f0b7f38ab) 53 | 54 | [initilising Pgadmin](https://itslinuxfoss.com/fix-psql-peer-authentication-failed-for-user/#:~:text=To%20fix%20%E2%80%9Cpsql%20Peer%20authentication,are%20explained%20with%20their%20applications.) 55 | 56 | - Need to update pg_hba.conf file to allow local connections 57 | 58 | you just have to change the line in pg_hba.conf file from peer to trust. 59 | 60 | ![image](https://user-images.githubusercontent.com/80549753/230084621-ef75600e-bdfc-4dc4-b266-53da31cc36f7.png) 61 | 62 | ```bash 63 | cd /etc/postgresql/12/main 64 | vi pg_hba.conf 65 | esc :wq! 66 | sudo su postgres 67 | service postgresql restart 68 | psql store_monitoring postgres 69 | ``` 70 | ![image](https://user-images.githubusercontent.com/80549753/230105990-2b5ef2db-8d8b-4291-806a-ca0c1a3a1548.png) 71 | 72 | 73 | The error message suggests that there might be another instance of PostgreSQL already running on the port 5432. You can try the following steps to resolve this issue: 74 | 75 | Verify if there is another instance of PostgreSQL already running by running the command: 76 | sudo lsof -i :5432 77 | 78 | If this command returns any output, it means that some process is already listening on port 5432. You can then stop the process using the command sudo kill , where is the ID of the process returned by the previous command. 79 | 80 | If there is no other instance of PostgreSQL running, then you can try to restart the PostgreSQL service by running the following command: 81 | sudo systemctl restart postgresql 82 | 83 | If the service still does not start, you can try to start the PostgreSQL server manually by running the following command: 84 | sudo su postgres -c '/usr/lib/postgresql/12/bin/pg_ctl -D /var/lib/postgresql/12/main -l /var/log/postgresql/postgresql-12-main.log start' 85 | 86 | This command starts the PostgreSQL server with the data directory /var/lib/postgresql/12/main and logs output to /var/log/postgresql/postgresql-12-main.log. If there are any errors, they should be visible in the log file. You can check the log file by running the command: 87 | sudo tail -f /var/log/postgresql/postgresql-12-main.log 88 | 89 | I hope this helps! 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /A]_PSQL (Postgresql)/schema_setup.sql: -------------------------------------------------------------------------------- 1 | 2 | 3 | CREATE table employee ( 4 | id serial primary key, 5 | name varchar(255) not null, 6 | department varchar(255) not null, 7 | salary int not null, 8 | phone int not null, 9 | UNIQUE (name,department), 10 | CHECK (salary > 10000), 11 | CHECK (phone > 1000000000) 12 | ); 13 | 14 | select * from employee; 15 | 16 | 17 | 18 | -- schema 19 | create table products ( 20 | prodID serial primary key, 21 | ProdName varchar(225) Not null, 22 | Qty int, 23 | description varchar(225), 24 | check (Qty>0) 25 | ); 26 | 27 | create table Orders ( 28 | prodID int, 29 | OrderId int primary key, 30 | Qty_sold int, 31 | check (Qty_sold > 0), 32 | price int, 33 | Order_date date, 34 | constraint fk foreign key (prodID) references products(prodID) 35 | 36 | ); 37 | 38 | 39 | alter table Orders 40 | add column product_name varchar(225); 41 | 42 | -- alter the table orders and add a column product_revue with a default value of 0 and check constraint of 0 to 10 43 | alter table Orders 44 | add column product_revue int default 0 check (product_revue >= 0 and product_revue <= 10); 45 | 46 | 47 | 48 | 49 | -- change the constrans fo the product_revue to 0 to 10 50 | alter table Orders 51 | alter column product_revue int; 52 | 53 | 54 | 55 | 56 | drop table Orders; 57 | drop table products; 58 | 59 | 60 | 61 | select * from orders; 62 | truncate table orders; 63 | 64 | select * from products; 65 | truncate table products; 66 | 67 | 68 | 69 | 70 | 71 | 72 | -- insert data in products table 73 | insert into products (prodName, Qty, description) values ('laptop', 10, 'HP'); 74 | 75 | insert into orders (prodID, OrderId, Qty_sold, price, Order_date) values (1, 1, 5, 1000, '2020-01-01'); 76 | 77 | -- insert data in orders table 78 | insert into orders (prodID, OrderId, Qty_sold, price, Order_date, product_revue, product_name) values (1, 1, 5, 1000, '2020-01-01', 5, 'laptop'); 79 | 80 | 81 | 82 | -- insert data in orders table 83 | update orders 84 | set product_name = 'laptop' 85 | where prodID = 1; 86 | 87 | -- update the product_revue to 5 and product_name to laptop 88 | update orders 89 | set product_revue = 5, product_name = 'laptop' 90 | where prodID = 1; -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(0)/Maiyani Gautam-312025.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(0)/Maiyani Gautam-312025.doc -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(0)/assign0_SQLverysimple.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(0)/assign0_SQLverysimple.pdf -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(0)/dp_0.txt: -------------------------------------------------------------------------------- 1 | create table SUPPLIER( 2 | 3 | sid int primary key, 4 | sname varchar(20) not null, 5 | city varchar(20) constraint nn_city not null 6 | ); 7 | 8 | create table PART( 9 | 10 | pid int primary key, 11 | pname varchar(20) not null, 12 | color varchar(20) not null 13 | 14 | ); 15 | 16 | create table CATALOG( 17 | 18 | sid int not null, 19 | pid int not null, 20 | cost int not null, 21 | constraint fk_sid primary key(sid,pid), 22 | foreign key(sid) references Supplier(sid), 23 | foreign key(pid) references Part(pid) 24 | ); 25 | 26 | insert into SUPPLIER(sid,sname,city) values(1,'riya','Mumbai'); 27 | insert into SUPPLIER(sid,sname,city) values(2,'Patel','Bangalore'); 28 | insert into SUPPLIER(sid,sname,city) values(3,'rinkal','Chennai'); 29 | insert into SUPPLIER(sid,sname,city) values(4,'krishna','Delhi'); 30 | 31 | select * from SUPPLIER; 32 | 33 | 34 | insert into PART(pid,pname,color) values(111,'wood','green'); 35 | insert into PART(pid,pname,color) values(222,'screw','red'); 36 | insert into PART(pid,pname,color) values(333,'Timber','blue'); 37 | insert into PART(pid,pname,color) values(444,'bolt','yellow'); 38 | select * from PART; 39 | 40 | 41 | insert into CATALOG(sid,pid,cost) values(1,111,95); 42 | insert into CATALOG(sid,pid,cost) values(2,222,5000); 43 | insert into CATALOG(sid,pid,cost) values(3,333,2000); 44 | insert into CATALOG(sid,pid,cost) values(4,444,250); 45 | 46 | select * from CATALOG; 47 | 48 | 49 | 50 | alter table PART add WEIGHT varchar(30); 51 | select * from PART; 52 | 53 | 54 | alter table SUPPLIER add constraint ck_city check(city in('Mumbai','Bangalore','Delhi','Kolkata','Chennai')); 55 | 56 | 57 | update PART set color='grey' where pid=111; 58 | select * from PART; 59 | 60 | 61 | update SUPPLIER set city='Mumbai' where sname='Patel'; 62 | select * from SUPPLIER; 63 | 64 | 65 | delete from CATALOG where cost>100 and cost<500; 66 | select * from CATALOG; 67 | 68 | 69 | alter table SUPPLIER add Country varchar(30); 70 | select * from SUPPLIER; 71 | 72 | 73 | update SUPPLIER set Country='India'; 74 | select * from SUPPLIER; 75 | 76 | 77 | alter table PART modify Color(40); 78 | alter table PART modify pname(5); 79 | desc PART; 80 | 81 | select * from SUPPLIER where city='Chennai'; 82 | 83 | 84 | select sid,pid from CATALOG where cost between 1000 and 5000; 85 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(a)/assign1a_SQLsimple.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(a)/assign1a_SQLsimple.pdf -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(a)/dbms_1a.txt: -------------------------------------------------------------------------------- 1 | create table supplier( 2 | 3 | sid int primary key not null, 4 | sname varchar(15) not null, 5 | city varchar(15) not null 6 | ); 7 | 8 | desc supplier 9 | 10 | create table part( 11 | pid int primary key, 12 | pname varchar(20) not null, 13 | color varchar(20) not null 14 | ); 15 | desc part 16 | 17 | create table catalog( 18 | 19 | sid int not null, 20 | pid int not null, 21 | cost int not null, 22 | constraint fk_sid primary key(sid,pid), 23 | foreign key(sid) references Supplier(sid), 24 | foreign key(pid) references Part(pid) 25 | ); 26 | desc catalog 27 | 28 | insert into supplier(sid,sname,city) values(1,'Raj','Mumbai'); 29 | insert into supplier(sid,sname,city) values(2,'Joy','Delhi'); 30 | insert into supplier(sid,sname,city) values(3,'Rajdeep','Mumbai'); 31 | insert into supplier(sid,sname,city) values(4,'Andrew','Up'); 32 | insert into supplier(sid,sname,city) values(5,'Jason','Kolkata'); 33 | insert into supplier(sid,sname,city) values(6,'Root','Surat'); 34 | 35 | select * from supplier; 36 | 37 | 38 | insert into part(pid,pname,color) values(10,'p-1','Red'); 39 | insert into part(pid,pname,color) values(20,'p-2','Blue'); 40 | insert into part(pid,pname,color) values(30,'p-3','Red'); 41 | insert into part(pid,pname,color) values(40,'p-4','Green'); 42 | insert into part(pid,pname,color) values(50,'p-5','Yellow'); 43 | 44 | select * from part; 45 | 46 | insert into catalog(sid,pid,cost) values(1,10,200); 47 | insert into catalog(sid,pid,cost) values(2,10,350); 48 | insert into catalog(sid,pid,cost) values(1,20,100); 49 | insert into catalog(sid,pid,cost) values(3,30,1000); 50 | insert into catalog(sid,pid,cost) values(3,10,200); 51 | insert into catalog(sid,pid,cost) values(4,50,20); 52 | insert into catalog(sid,pid,cost) values(2,50,600); 53 | insert into catalog(sid,pid,cost) values(5,40,400); 54 | insert into catalog(sid,pid,cost) values(5,20,2000); 55 | insert into catalog(sid,pid,cost) values(1,30,500); 56 | insert into catalog(sid,pid,cost) values(1,40,70); 57 | insert into catalog(sid,pid,cost) values(2,20,170); 58 | insert into catalog(sid,pid,cost) values(2,30,300); 59 | 60 | select * from catalog; 61 | 62 | 63 | 64 | 65 | 66 | select * from supplier 67 | 68 | where sid in(select distinct(sid) from catalog where pid in (select pid from part where color='Red')); 69 | 70 | 71 | select pid,count(*) 72 | from catalog 73 | group by pid; 74 | 75 | select * from supplier 76 | where upper(city)='MUMBAI' and upper(sname) like '__J%'; 77 | 78 | 79 | alter table supplier add scontact number(10)constraint ck_count check(scontact like '0%'); 80 | 81 | select * from supplier; 82 | 83 | create index idx on supplier (sname,city); 84 | 85 | select sid from catalog group by sid having count(*)>3; 86 | 87 | select * from supplier where sid not in(select distinct(sid)from catalog); 88 | 89 | select avg(cost) from catalog where pid in(select pid from part where upper(color)='GREEN'); 90 | 91 | 92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(b)/Maiyani Gautam-312025.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(b)/Maiyani Gautam-312025.docx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(b)/Maiyani-Gautam-312025.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(b)/Maiyani-Gautam-312025.doc -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(b)/Maiyani_Gautam_312025(1b).docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(b)/Maiyani_Gautam_312025(1b).docx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(b)/assgn1b_sql.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(b)/assgn1b_sql.pdf -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(b)/dbms-1b(p-2).txt: -------------------------------------------------------------------------------- 1 | create table Candidate( 2 | 3 | cid number(10) constraint pk_cid primary key, 4 | cname varchar2(20), 5 | caddress varchar2(50), 6 | cbirth_dt date 7 | ); 8 | 9 | create table Test( 10 | 11 | tid number(10) constraint pk_tid primary key, 12 | tname varchar2(20), 13 | tot_marks number(20), 14 | pass_marks number(20) 15 | ); 16 | 17 | create table Test_Centre( 18 | 19 | tcid number(10) constraint pk_tcid primary key, 20 | location varchar2(50), 21 | mgr varchar2(20), 22 | capacity number(20) 23 | ); 24 | 25 | create table Test_Taken( 26 | cid number(10), 27 | tid number(10), 28 | tcid number(10), 29 | Test_dt date, 30 | score number(20), 31 | constraint pk_cidtidtcid primary key(cid,tid,tcid), 32 | constraint fk_cid foreign key(cid) references Candidate(cid) on delete cascade, 33 | constraint fk_tid foreign key(tid) references Test(tid) on delete cascade, 34 | constraint fk_tcid foreign key(tcid) references Test_Centre(tcid) on delete cascade 35 | 36 | ); 37 | 38 | insert into Candidate values(1,'Gautam Maiyani','Kirti Stambh','14-Nov-2002'); 39 | insert into Candidate values(2,'Raval Krish ','Akota','07-JUN-2001'); 40 | insert into Candidate values(3,'Roy Makwana','Alkapuri','07-FEB-2003'); 41 | insert into Candidate values(4,'Mayank Trivedi','Gotri','12-JAN-2001'); 42 | insert into Candidate values(5,'Tirth Shah','Akota','24-JAN-2001'); 43 | insert into Candidate values(6,'Raj Patel','Karelibaugh','01-JUN-2002'); 44 | 45 | select * from Candidate; 46 | 47 | 48 | 49 | insert into test values(1,'JEE Mains',360,100) ; 50 | insert into test values(2,'JEE Advanced',480,120) ; 51 | insert into test values(3,'NEET UG',720,360) ; 52 | insert into test values(4,'GUJCET',120,40) ; 53 | SELECT* from test; 54 | 55 | insert into Test_Centre values(1,'Gotri','Raj Shah',200) ; 56 | insert into Test_Centre values(2,'Alkapuri','Nilesh Patel',100) ; 57 | insert into Test_Centre values(3,'Manjalpur','Nikita Parmar',150) ; 58 | insert into Test_Centre values(4,'Karelibaugh','Henil Shah',230) ; 59 | insert into Test_Centre values(5,'Akota','Mayur Desai',270) ; 60 | insert into Test_Centre values(6,'GIDC','Amit Shah',110) ; 61 | SELECT* from Test_Centre; 62 | 63 | 64 | insert into Test_Taken values(1,1,4,'15-JUNE-2020',220); 65 | insert into Test_Taken values(1,2,4,'20-MAY-2020',155); 66 | insert into Test_Taken values(1,4,1,'20-APR-2020',118); 67 | insert into Test_Taken values(2,3,2,'25-JUNE-2020',580); 68 | insert into Test_Taken values(3,3,2,'20-MAY-2020',490); 69 | insert into Test_Taken values(4,1,1,'20-APR-2020',120); 70 | insert into Test_Taken values(4,2,4,'15-MAY-2020',25); 71 | insert into Test_Taken values(4,4,3,'25-APR-2020',99); 72 | insert into Test_Taken values(5,1,2,'20-APR-2020',100); 73 | insert into Test_Taken values(5,4,2,'25-APR-2020',70); 74 | insert into Test_Taken values(6,1,1,'20-APR-2020',200); 75 | insert into Test_Taken values(6,2,3,'15-MAY-2020',180); 76 | SELECT* from Test_Taken; 77 | 78 | select tt.tid, tname, tt.tcid, location, count(*) as No_Of_Candidates from Test_Taken tt , Test t,Test_Centre tc where tt.tid = t.tid and tt.tcid = tc.tcid group by(tt.tid,tt.tcid,tname,location) order by(tid); 79 | 80 | select c.* from Candidate c ,Test_Centre tc, Test_Taken tt where c.cid = tt.cid and tc.tcid = tt.tcid and upper(location) = 'MANJALPUR' and score in (select score from test_taken tt1 ,Candidate c1 where tt1.cid = c.cid and upper(cname) = 'GAUTAM MAIYANI'); 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 10th quries.... 90 | create view v as select t1.cid,c.cname,t1.tid,t2.tname ,t1.score from test_taken t1 join test t2 on 91 | t1.tid=t2.tid join candidate c on c.cid=t1.cid with read only; 92 | select * from v; 93 | 94 | 95 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(b)/dbms1b(p1).txt: -------------------------------------------------------------------------------- 1 | create table Team_Master( 2 | 3 | team_id number(5) constraint pk_team_id primary key , 4 | team_name varchar2(20) 5 | ); desc Team_Master 6 | 7 | create table Player( 8 | 9 | team_id number(5), 10 | pid number(5), 11 | pname varchar2(30), 12 | pbirthdate date, 13 | constraint fk_team_id foreign key(team_id) references Team_Master(team_id) on delete cascade , 14 | constraint pk_team_id_pid primary key(team_id,pid) 15 | ); desc Player 16 | 17 | create table Score( 18 | 19 | team_id number(5), 20 | pid number(5), 21 | runs_made number(5), 22 | out_type varchar2(20), 23 | bid number(5), 24 | bteam_id number(5), 25 | constraint fk1_team_id_pid foreign key(team_id,pid) references Player(team_id,pid) , 26 | constraint fk2_bteam_id_bid foreign key(bteam_id,bid) references Player(team_id,pid) , 27 | constraint pkS_team_id_pid primary key(team_id,pid) 28 | ); desc Score 29 | 30 | create table Balling( 31 | 32 | team_id number(5), 33 | bid number(5), 34 | overs number(10), 35 | maiden number(5), 36 | runs_given number(5), 37 | wickets_taken number(10), 38 | constraint fk_team_id_bid foreign key(team_id,bid) references Player(team_id,pid), 39 | constraint pk_team_id_bid primary key(team_id,bid) 40 | ); desc Balling 41 | 42 | insert into Team_Master values(101,'India'); 43 | insert into Team_Master values(102,'Australia'); 44 | insert into Team_Master values(103,'England'); 45 | insert into Team_Master values(104,'SouthAfrica'); 46 | insert into Team_Master values(105,'WestIndies'); 47 | 48 | Select * from Team_Master; 49 | 50 | insert into Player values(101,1,'MS Dhoni',to_date('07-07-1981','dd-mm-yyyy')) ; 51 | insert into Player values(101,2,'Virat Kohli',to_date('05-11-1988','dd-mm-yyyy')) ; 52 | insert into Player values(101,3,'Ravindra Jadeja',to_date('06-12-1988','dd-mm-yyyy')) ; 53 | insert into Player values(102,1,'Steve Smith',to_date('01-11-1988','dd-mm-yyyy')) ; 54 | insert into Player values(102,2,'David Warner',to_date('08-12-1984','dd-mm-yyyy')) ; 55 | insert into Player values(102,3,'Glen Johnsen',to_date('21-09-1995','dd-mm-yyyy')) ; 56 | insert into Player values(103,1,'Eion Morgan',to_date('17-04-1982','dd-mm-yyyy')) ; 57 | insert into Player values(103,2,'Ben Stokes',to_date('20-02-1989','dd-mm-yyyy')) ; 58 | insert into Player values(103,3,'Moin Ali',to_date('18-06-1987','dd-mm-yyyy')) ; 59 | insert into Player values(104,1,'Michel Starks',to_date('22-06-1983','dd-mm-yyyy')) ; 60 | insert into Player values(104,2,'AB de Villiers',to_date('15-02-1987','dd-mm-yyyy')) ; 61 | insert into Player values(105,1,'Bravo',to_date('10-07-1988','dd-mm-yyyy')) ; 62 | insert into Player values(105,2,'Chris Gayle',to_date('10-01-1979','dd-mm-yyyy')) ; 63 | select * from Player; 64 | 65 | insert into Score values(101,1,101,'Bowled',2,103) ; 66 | insert into Score values(101,2,79,'Caught',1,105) ; 67 | insert into Score values(101,3,34,'Caught',2,103) ; 68 | insert into Score values(102,1,36,'Stumped',3,103) ; 69 | insert into Score values(102,2,5,'LBW',2,105) ; 70 | insert into Score values(103,1,44,'Caught',1,105) ; 71 | insert into Score values(104,1,68,'Stumped',1,105) ; 72 | insert into Score values(104,2,23,'Caught',2,103) ; 73 | Select *from Score; 74 | 75 | 76 | insert into Balling values(103,2,4,0,28,2); 77 | insert into Balling values(105,1,4,0,22,2); 78 | insert into Balling values(103,3,3,0,36,0); 79 | insert into Balling values(105,2,4,1,45,1); 80 | insert into Balling values(102,3,2,0,22,0); 81 | insert into Balling values(101,3,4,1,21,4); 82 | Select *from Balling; 83 | 84 | select * from Balling where wickets_taken = (select max(wickets_taken) from Balling); 85 | 86 | 87 | select * from Player where pid in (select pid from Score where runs_made > 25) and (to_char(pbirthdate,'Mon') = 'Feb') ; 88 | 89 | select p.team_id,pid,pname as Name,overs,maiden,runs_given as Run,wickets_taken as Wickets from Player p , Balling b where p.pid = b.bid and p.team_id = b.team_id and maiden <= 3 ; 90 | 91 | select p.team_id,bid,pname as Name,runs_given as Runs from Player p , Balling b where p.pid = b.bid and p.team_id = b.team_id ; 92 | 93 | 94 | select team_id,out_type,count(*) as count from Score group by (team_id,out_type) order by team_id ; 95 | 96 | select * from Player where round(sysdate-pbirthdate) > 40*365 ; 97 | 98 | select p.team_id, p.pid, pname as "ALL ROUNDER" from Player p ,Score s , Balling b where s.pid=b.bid and s.team_id=b.team_id and p.pid=s.pid and p.team_id=s.team_id ; 99 | 100 | 101 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_1/assignment_1(b)/dbms_1b(p-1).txt: -------------------------------------------------------------------------------- 1 | create table TEAM_MASTER( 2 | 3 | team_id int primary key not null, 4 | team_name varchar(10) not null 5 | ); 6 | desc TEAM_MASTER 7 | 8 | create table PLAYER( 9 | 10 | team_id int not null, 11 | pid int not null, 12 | pname varchar(20) not null, 13 | pbirthdate date not null, 14 | constraint pk_sid primary key(team_id,pid), 15 | foreign key(team_id) references TEAM_MASTER(team_id) 16 | ); 17 | desc PLAYER 18 | 19 | create table SCORE( 20 | 21 | team_id int not null, 22 | pid int not null, 23 | run_made_out int not null, 24 | b_id int not null, 25 | bteam_id int not null, 26 | constraint sk_sid primary key(team_id,pid) 27 | ); 28 | desc SCORE 29 | 30 | create table BALLING( 31 | 32 | team_id int not null, 33 | b_id int not null, 34 | overs int not null, 35 | maiden int not null, 36 | runs_given int not null, 37 | wickets_taken int not null, 38 | constraint bk_sid primary key(team_id,b_id) 39 | ); 40 | desc BALLING 41 | 42 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_2&3/Maiyani Gautam-412033(new seat no) ass_2&3.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Assignment/Assignment_2&3/Maiyani Gautam-412033(new seat no) ass_2&3.doc -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/IntroDBMS_ERModelAnjali (1).pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/IntroDBMS_ERModelAnjali (1).pptx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Neha DBMS Full n Final.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/Neha DBMS Full n Final.pdf -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/NormalizationAnjali.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/NormalizationAnjali.pptx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/NormalizationAnjali_Part1.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/NormalizationAnjali_Part1.pptx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/PDF's/1. IntroDBMS_ERModelAnjali.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/PDF's/1. IntroDBMS_ERModelAnjali.pdf -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/RelationalModelAnjali (1).pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/RelationalModelAnjali (1).pptx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/RelationalModelAnjali.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/RelationalModelAnjali.pptx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQLPresentationAnjaliPseudoIndexing.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQLPresentationAnjaliPseudoIndexing.pptx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQLPresentationAnjaliSubQueries1Feb2022.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQLPresentationAnjaliSubQueries1Feb2022.pptx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQLPresentationAnjaliSubQueriesdone.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQLPresentationAnjaliSubQueriesdone.pptx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQLPresentationAnjaliViewsTransactionControl.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQLPresentationAnjaliViewsTransactionControl.pptx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQLPresentationAnjali_Joins_DateManipulationsdone.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQLPresentationAnjali_Joins_DateManipulationsdone.pptx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQL_Part1_AnjaliJivani_DDL_DML_Select.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQL_Part1_AnjaliJivani_DDL_DML_Select.pptx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQL_Part2_AnjaliJivani_GroupBy_SubQuery_StrngFns_DUAL.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQL_Part2_AnjaliJivani_GroupBy_SubQuery_StrngFns_DUAL.pptx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQL_Part3_AnjaliJivani_JoinsDateManipulationPseudoIndexing.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQL_Part3_AnjaliJivani_JoinsDateManipulationPseudoIndexing.pptx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQL_Part4_AnjaliJivani_SynonymSetOperatorsViewTranControlAdvSQL.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/SQL_Part4_AnjaliJivani_SynonymSetOperatorsViewTranControlAdvSQL.pptx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/assignment-dbms/DBMSASSIGNMENT3PART2QUE1.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/assignment-dbms/DBMSASSIGNMENT3PART2QUE1.docx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/assignment-dbms/DBMSASSIGNMENT3PART2QUE2.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/assignment-dbms/DBMSASSIGNMENT3PART2QUE2.docx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/assignment-dbms/DBMSASSIGNMENT3PART2QUE3.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/assignment-dbms/DBMSASSIGNMENT3PART2QUE3.docx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/assignment-dbms/DBMSASSIGNMENT3PART2QUE4.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/assignment-dbms/DBMSASSIGNMENT3PART2QUE4.docx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/assignment-dbms/PLSQL5.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/assignment-dbms/PLSQL5.pdf -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/sql-sq.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Gaut_notes/DBMS/sql-sq.pdf -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Gaut_notes/DBMS/~$SQLPresentationAnjali_Joins_DateManipulationsdone.pptx: -------------------------------------------------------------------------------- 1 | GAUTAM GAUTAM -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Notes.md: -------------------------------------------------------------------------------- 1 | 2 | - all the high privileged users like SYS, SYSTEM were placed inside the container databaswe and other schemas like HR, OE, SH were placed inside the pluggable database. 3 | - - In Oracle Database, a pluggable database (PDB) is a self-contained database unit within a larger container database (CDB) 4 | - 5 | - 6 | - A **schema** is a collection of database objects. A **schema is owned by a database user** and has the **same name** as that user. Schema objects are logical structures created by users. **Objects such as tables or indexes hold data**, or can consist of a definition only, such as a view or synonym. 7 | 8 | - **SQL*Plus** is a command-line interface provided by Oracle for interacting with the Oracle Database. **PL/SQL** is a language used within SQL*Plus to write procedural code and interact with the database 9 | - **Dual :** DUAL is a table automatically created by Oracle Database along with the data dictionary. DUAL is in the schema of the user SYS but is accessible by the name DUAL to all users. It has one column, DUMMY , defined to be VARCHAR2(1) , and contains one row with a value X . 10 | #### **SYS & SYSTEM :** [sys-and-system-accounts-in-oracle-database](https://medium.com/@ykods/sys-and-system-accounts-in-oracle-database-6113c3a29765) 11 | 1. **SYS:** `superuser` (system administrator account) && `highest level of privileges` 12 | 2. both created automatically during the database installation, AND account is used for performing critical administrative tasks and managing the Oracle Database instance itself. 13 | 3. privileges: creating and modifying database structures managing, memory and storage, and creating and managing other database users. 14 | 4. **SYSTEM**: `another administrative account` && `fewer privileges` compared to SYS. 15 | 5. privileges: system-related tasks 16 | 6. used for day-to-day management activities and is typically used for managing database schema objects, security, and application-related tasks 17 | 18 | 19 | 20 | 21 | 22 | - [data dictionary objects](https://chat.openai.com/c/5b7fc911-9988-4722-9648-2329b670400e): ALL_TABLES, ALL_TAB_COLUMNS, ALL_VIEWS, ALL_INDEXES, ALL_CONS_COLUMNS, ALL_CONSTRAINTS, ALL_TAB_PRIVS, ALL_SYNONYMS, DBA_OBJECTS, DBA_USERS. 23 | - [plsql-exception-propagation-example-3](https://www.oracletutorial.com/wp-content/uploads/2019/08/plsql-exception-propagation-example-3.png) 24 | 25 | 26 | 27 | 28 | ## interviewbit.com 29 | - tables: object of type table that are modeled as db tables 30 | - WHERE CURRENT: we use this clause while referencing the current row from an explicit cursor. This clause allows applying updates and deletion of the row currently under consideration without explicitly referencing the row ID. 31 | - EXCEPTION_INIT: assigns a name to an Oracle error so that you can reference it in your exception-handling routine. -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/Assignment_12Feb2024.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/Assignment_12Feb2024.pdf -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/ORACLE_SETUP_BACKUP.md: -------------------------------------------------------------------------------- 1 | # Remove Oracle database [Link](https://youtube.com/playlist?list=PLL_LQvNX4xKzN_nhJWT8pPzOwSjKFd_uD&si=_elkgkkl5OHOMHYL) 2 | - remove the home pathe from the environment variable system path's 'C:\app\user\product\12.2.0\dbhome_1\bin' 3 | 4 | ### Deleting all the records from the registry 5 | - win + r 'regedit' -> HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\ -> remove the home path && 6 | - HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ -> DELETE FOLDER'S name start with 'Oracle' 7 | 8 | ### Delete oracle home users and groupes 9 | - win + r 'lusrmgr.msc' -> Users -> remove the user 'Oracle_HomeUser' && 10 | 11 | 12 | 13 | 14 | 15 | # How to find out the SID and DB Home 16 | - open registory editor win + r 'regedit' -> HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\ -> ORACLE_HOME_NAME -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/Oracle Basics/data-definition.sql: -------------------------------------------------------------------------------- 1 | -- . Create Table 2 | -- . Constraint 3 | -- . Create Table As 4 | -- . Alter Table 5 | -- . Drop Table 6 | -- . Global Temp Tables 7 | -- . Local Temp Tables 8 | -- . Create Sequence & Synonym, Grant Option 9 | 10 | 11 | 12 | -- Create Table As 13 | CREATE TABLE new_table_name AS 14 | SELECT column1, column2, ... 15 | FROM existing_table_name 16 | WHERE condition; 17 | 18 | -- Global Temp Tables 19 | CREATE GLOBAL/PRIVATE TEMPORARY TABLE temp_table_name 20 | (column1 datatype, column2 datatype, ...); 21 | 22 | -- Local Temp Tables 23 | CREATE TEMPORARY TABLE temp_table_name 24 | (column1 datatype, column2 datatype, ...); 25 | 26 | -- Create Sequence & Synonym, Grant Option 27 | CREATE SEQUENCE sequence_name 28 | MINVALUE 1 29 | START WITH 1 30 | INCREMENT BY 1 31 | CACHE 10; 32 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/Oracle Basics/data-types.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Character Data Types: 3 | CHAR(n): Fixed-length character string with a maximum length of n characters. 4 | VARCHAR2(n): Variable-length character string with a maximum length of n characters. 5 | NCHAR(n): Fixed-length Unicode character string with a maximum length of n characters. 6 | NVARCHAR2(n): Variable-length Unicode character string with a maximum length of n characters. 7 | CLOB: Character large object for storing large amounts of character data. 8 | 9 | Numeric Data Types: 10 | NUMBER(precision, scale): Fixed-point or floating-point number with specified precision and scale. 11 | INTEGER: Whole numbers within the range of -2,147,483,648 to 2,147,483,647. 12 | FLOAT: Floating-point number with binary precision p. 13 | DOUBLE PRECISION: Double-precision floating-point number. 14 | 15 | Date and Time Data Types: 16 | DATE: Date and time data in the format 'YYYY-MM-DD HH:MI:SS'. 17 | TIMESTAMP: Date and time data with fractional seconds precision. 18 | INTERVAL: Represents a period of time. 19 | 20 | Binary Data Types: 21 | BLOB: Binary large object for storing large amounts of binary data. 22 | RAW(n): Fixed-length binary data with a maximum length of n bytes. 23 | LONG RAW: Variable-length binary data. 24 | 25 | Large Object Data Types: 26 | BFILE: Binary file data stored outside the database. 27 | NCLOB: Unicode character large object. 28 | 29 | Row Identifier Data Types: 30 | ROWID: Binary representation of a row's address. 31 | UROWID: Universal row identifier, encoded as base 64. 32 | 33 | */ 34 | 35 | 36 | -- CHAR(size) 37 | /* 38 | * DEFAULT 1 39 | * CHARACERS ARE FIXED LENGTH 40 | * IF YOU INSERT LESS THAN THE SIZE IT WILL BE FILLED WITH SPACE 41 | * CHARACTERS RANGE FROM 1 TO 2000 bytes 42 | */ 43 | 44 | 45 | CREATE TABLE Temp_1 (col1 CHAR(5)); 46 | INSERT INTO Temp_1 VALUES ('AYON'); 47 | INSERT INTO Temp_1 VALUES ('KAYON'); 48 | INSERT INTO Temp_1 VALUES ('abc'); 49 | 50 | SELECT * FROM Temp_1; 51 | -- HOW TO CALCULATE THE SPACE OF col1 FOR ORACLE 52 | SELECT SUM(VSIZE(col1)) FROM Temp_1; -- 15 CAUSE 5*3 TAKING WHOLE SPACE 53 | DROP TABLE Temp_1; 54 | 55 | -- VARCHAR2(size) 56 | /* 57 | * DEFAULT 1 58 | * CHARACERS ARE VARIABLE LENGTH 59 | * IF YOU INSERT LESS THAN THE SIZE IT WILL BE Take the size of the string 60 | * CHARACTERS RANGE FROM 1 TO 4000 bytes 61 | */ 62 | 63 | 64 | CREATE TABLE Temp_2 (col1 VARCHAR2(5)); 65 | INSERT INTO Temp_2 VALUES ('AYON'); 66 | INSERT INTO Temp_2 VALUES ('SSP'); 67 | 68 | SELECT * FROM Temp_2; 69 | SELECT col1, VSIZE(col1) FROM Temp_2; -- 8 CAUSE 5+3 TAKING WHOLE SPACE 70 | 71 | 72 | 73 | 74 | CREATE TABLE t ( 75 | x CHAR(10), 76 | y VARCHAR2(10) 77 | ); 78 | INSERT INTO t(x, y ) 79 | VALUES('Oracle', 'Oracle'); 80 | SELECT 81 | x, DUMP(x), 82 | y, DUMP(y) 83 | FROM t; 84 | 85 | -- X, DUMP(X), Y, DUMP(Y) 86 | -- Oracle ,Typ=96 Len=10: 79,114,97,99,108,101,32,32,32,32,Oracle,Typ=1 Len=6: 79,114,97,99,108,101 87 | 88 | 89 | SELECT 90 | LENGTHB(x), 91 | LENGTHB(y) 92 | FROM 93 | t; 94 | 95 | -- LENGTHB(X),LENGTHB(Y) 96 | -- 10, 6 97 | 98 | -- to compare the strings with different data types use 99 | select * from t where rtrim(x) = :v; 100 | 101 | 102 | 103 | 104 | CREATE TABLE Temp_number_demo ( 105 | number_value NUMERIC(6, 2) 106 | ); 107 | 108 | INSERT INTO Temp_number_demo 109 | VALUES(9999.99); 110 | 111 | INSERT INTO Temp_number_demo 112 | VALUES(-9999.99); 113 | 114 | INSERT INTO Temp_number_demo 115 | VALUES(9999.999); -- ERROR 116 | 117 | SELECT * FROM Temp_number_demo; 118 | 119 | DELETE FROM Temp_number_demo; 120 | 121 | ALTER TABLE Temp_number_demo 122 | MODIFY number_value NUMERIC(6, 0); 123 | 124 | INSERT INTO Temp_number_demo VALUES (9999.99); 125 | INSERT INTO Temp_number_demo VALUES (-9999.99); 126 | INSERT INTO Temp_number_demo VALUES (-9999.999); 127 | INSERT INTO Temp_number_demo VALUES (976354.978); 128 | INSERT INTO Temp_number_demo VALUES (976364.978); 129 | INSERT INTO Temp_number_demo VALUES (976314.978); 130 | INSERT INTO Temp_number_demo VALUES (976314.978); 131 | INSERT INTO Temp_number_demo VALUES (976314.578); 132 | INSERT INTO Temp_number_demo VALUES (976314.478); 133 | 134 | SELECT * FROM Temp_number_demo; 135 | 136 | -- DATEDIFF() 137 | 138 | 139 | -- THIS IS VERY CONFUSION 140 | CREATE TABLE number_demo ( 141 | number_value NUMERIC(6, 2) 142 | ); 143 | 144 | 145 | INSERT INTO number_demo 146 | VALUES(100.99); 147 | 148 | INSERT INTO number_demo 149 | VALUES(90.551); 150 | 151 | INSERT INTO number_demo 152 | VALUES(8.556014527); 153 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/Oracle Basics/oracle-date-functions.sql: -------------------------------------------------------------------------------- 1 | -- Oracle Date Functions 2 | 3 | Function Example Result Description 4 | ADD_MONTHS ADD_MONTHS( DATE '2016-02-29', 1 ) 31-MAR-16 Add a number of months (n) to a date and return the same day which is n of months away. 5 | LAST_DAY LAST_DAY( DATE '2016-02-29' ) 29-FEB-16 Return the last day of the month for a date. 6 | TO_CHAR TO_CHAR( DATE'2017-01-01', 'DL' ) Sunday, January 01, 2017 Convert a DATE or an INTERVAL value to a character string in a specified format. 7 | TO_DATE TO_DATE( '01 Jan 2017', 'DD MON YYYY' ) 01-JAN-17 Convert a date which is in the character string to a DATE value. 8 | NEXT_DAY NEXT_DAY( DATE '2017-01-01', 'MONDAY' ) 02-JAN-17 Return the date of the next specified day of the week that comes after a date. 9 | TRUNC TRUNC(DATE '2017-07-16', 'MM') 01-JUL-17 Return a date truncated to a specific unit of measure. 10 | CURRENT_DATE RETURN the current data format '06-AUG-2017 19:43:44' 11 | CURRENT_TIMESTAMP -> '06-AUG-17 08.26.52.742000000 PM -07:00' 12 | DBTIMEZONE -> -07:00 13 | EXTRACT EXTRACT(YEAR FROM SYSDATE) -> 2017; EXTRACT ( year/month/date/DOW FROM SYSDATE) 14 | MONTHS_BETWEEN MONTHS_BETWEEN( DATE '2017-07-01', DATE '2017-01-01' ) -> 6 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | SELECT ADD_MONTHS(SYSDATE, 1) AS project_due_date FROM dual; 23 | SELECT ADD_MONTHS(DATE '2016-02-20', 1) AS project_due_date FROM dual; 24 | 25 | 26 | -- TO_CHAR 27 | /* 28 | DD for day of month. 29 | MM for month. 30 | YYYY for year. 31 | HH for hour. 32 | MI for minute. 33 | SS for second. 34 | 35 | TO_CHAR(123.456, '$0,0.00') 36 | TO_CHAR(SYSDATE, 'DD-MON-YYYY') 37 | RTRIM(TO_CHAR(l_date, 'Day')) = 'Sunday' 38 | */ 39 | 40 | 41 | 42 | CREATE TABLE audits ( 43 | audit_id NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 44 | table_name VARCHAR2(255), 45 | transaction_name VARCHAR2(10), 46 | by_user VARCHAR2(30), 47 | transaction_date DATE 48 | ); 49 | 50 | CREATE OR REPLACE TRIGGER customers_audit_trg 51 | AFTER 52 | UPDATE OR DELETE ON customers 53 | FOR EACH ROW 54 | DECLARE 55 | l_transaction VARCHAR2(10); 56 | BEGIN 57 | -- determine the transaction type 58 | l_transaction := CASE 59 | WHEN UPDATING THEN 'UPDATE' 60 | WHEN DELETING THEN 'DELETE' 61 | END; 62 | 63 | -- insert a row into the audit table 64 | INSERT INTO audits (table_name, transaction_name, by_user, transaction_date) 65 | VALUES('CUSTOMERS', l_transaction, USER, SYSDATE); 66 | END; 67 | / 68 | 69 | -- Oracle Row-level Triggers 70 | CREATE OR REPLACE TRIGGER trigger_name 71 | BEFORE | AFTER 72 | INSERT OR DELETE OR UPDATE OF column1, column2, … 73 | ON table_name 74 | FOR EACH ROW 75 | REFERENCING OLD AS old_name 76 | NEW AS new_name 77 | WHEN (condition) 78 | DECLARE 79 | … 80 | BEGIN 81 | … 82 | EXCEPTION 83 | … 84 | END; 85 | / 86 | 87 | -- sudo record: :NEW OR :OLD 88 | 89 | /* 90 | BEFORE 91 | insert :NEW 92 | update :NEW, :OLD 93 | delete :OLD 94 | 95 | */ 96 | 97 | -- need to pratice: https://youtu.be/i5fw-67P3XY?si=c8gDkdOw-Ml5CWpe -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/Oracle Basics/oracle-identity-column.sql: -------------------------------------------------------------------------------- 1 | -- * Oracle Identity Column 2 | id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY START WITH 10 INCREMENT BY 10, 3 | 4 | -- update 5 | update table_name 6 | set column_name = new_value; 7 | 8 | 9 | update table_name 10 | set 11 | column_name = new_value, 12 | equation(cnt = cnt + 1), 13 | column_name = (sub_query), 14 | gross_margin AS ((list_price - cost) / cost), 15 | column_name = column1 || ' ' || column2; 16 | case 17 | where condition then value1 18 | where condition then value2 19 | end default_value 20 | end 21 | where condition 22 | order by column_name desc 23 | limit 5; 24 | 25 | 26 | 27 | id number generate by default on (identity/ on null) 28 | start with 100 increment by 100 29 | no catch 30 | no cycle; -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/Oracle Basics/oracle-insert.sql: -------------------------------------------------------------------------------- 1 | 2 | -- Modifying data 3 | 4 | -- INSERT – learn how to insert a row into a table. 5 | INSERT INTO table_name (column_list) 6 | VALUES( value_list); 7 | 8 | INSERT INTO discounts(discount_name, amount, start_date, expired_date) 9 | VALUES('Summer Promotion', 9.5, DATE '2017-05-01', DATE '2017-08-31'); 10 | 11 | 12 | -- INSERT INTO SELECT – insert data into a table from the result of a query. 13 | INSERT INTO target_table [(col1, col2, col3)] 14 | SELECT 15 | col1, 16 | col2, 17 | col3 18 | FROM source_table 19 | WHERE condition; 20 | 21 | -- INSERT ALL – discuss multitable insert statement to insert multiple rows into a table or multiple tables. 22 | INSERT ALL 23 | INTO table_name(col1,col2,col3) VALUES(val1,val2, val3) 24 | INTO table_name(col1,col2,col3) VALUES(val4,val5, val6) 25 | INTO table_name(col1,col2,col3) VALUES(val7,val8, val9) 26 | Subquery; -- SELECT * FROM dual; 27 | 28 | CREATE TABLE medium_orders AS 29 | SELECT * 30 | FROM small_orders; 31 | 32 | 33 | -- ALL: In this example, if both condition1 and condition2 are true for a row in the source_table, INSERT ALL will insert that row into both table_1 and table_2. 34 | INSERT ALL 35 | WHEN condition1 THEN 36 | INTO table_1 (column_list) VALUES (value_list) 37 | WHEN condition2 THEN 38 | INTO table_2 (column_list) VALUES (value_list) 39 | ELSE 40 | INTO table_3 (column_list) VALUES (value_list) 41 | SELECT * FROM source_table; 42 | 43 | -- FIRST: In this example, if both condition1 and condition2 are true for a row in the source_table, only the INSERT INTO clause corresponding to condition1 will be executed, and the row will be inserted into table_1. 44 | INSERT FIRST 45 | WHEN condition1 THEN 46 | INTO table_1 (column_list) VALUES (value_list) 47 | WHEN condition2 THEN 48 | INTO table_2 (column_list) VALUES (value_list) 49 | ELSE 50 | INTO table_3 (column_list) VALUES (value_list) 51 | SELECT * FROM source_table; 52 | 53 | INSERT ALL 54 | WHEN amount < 10000 THEN 55 | INTO small_orders 56 | WHEN amount >= 10000 AND amount <= 30000 THEN 57 | INTO medium_orders 58 | WHEN amount > 30000 THEN 59 | INTO big_orders 60 | 61 | SELECT 62 | order_id, 63 | customer_id, 64 | (quantity * unit_price) amount 65 | FROM orders 66 | INNER JOIN order_items USING(order_id); 67 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/Oracle Basics/oracle-string-functions.sql: -------------------------------------------------------------------------------- 1 | -- Oracle String Functions 2 | -- ASCII: Returns the ASCII code value of the leftmost character of a string. 3 | ASCII( 'ABC' ) -> 65 4 | -- CHR: Returns the character having the binary equivalent to n as a VARCHAR2 value. 5 | CHR( 65 ) -> A 6 | -- CONCAT: Concatenate two strings and return the combined string. 7 | CONCAT( 'ABC', 'DEF' ) -> ABCDEF 8 | -- CONVERT: Convert a string from one character set to another. 9 | CONVERT( 'ABC', 'UTF8', 'WE8MSWIN1252' ) -> ABC 10 | -- DUMP: Returns a VARCHAR2 value that includes the datatype code, length in bytes, and internal representation of a raw or character string. 11 | DUMP( 'ABC', 1016 ) -> Typ=96 Len=3: 65,66,67 12 | -- INITCAP: Converts the first character in each word in a specified string to uppercase and the rest to lowercase. 13 | INITCAP( 'abc def' ) -> Abc Def 14 | -- INSTR: Returns the position of a substring in a string. 15 | INSTR( 'ABCDEF', 'C' ) -> 3 16 | 17 | SELECT 18 | INSTR( 'This is a playlist', 'is', 1, 1 ) third_occurrence, -- 16 19 | INSTR( 'This is a playlist', 'is', -1, 1 ) second_occurrence, -- 6 (-1 means search from the end of the string)) 20 | INSTR( 'This is a playlist is', 'is', 1, 4 ) third_occurrence, -- 20 21 | INSTR( 'This is a playlist is', 'is', 1, 5 ) third_occurrence, -- 0 if not foutnd 22 | INSTR( 'This is a playlist', 'is',-1 ) substring_location -- -1 means search from the end of the string 23 | FROM dual; 24 | -- LENGTH 25 | LENGTH( 'ABC' ) -> 3 26 | -- LOWER: Converts all letters in the specified string to lowercase. 27 | LOWER( 'ABC' ) -> abc 28 | -- UPPER: Converts all letters in the specified string to uppercase. 29 | UPPER( 'abc' ) -> ABC 30 | -- LPAD: Left-pads a string to the specified length with the specified characters. 31 | LPAD( 'ABC', 5, 'X' ) -> XXABC 32 | -- SUBSTR: Returns a substring from a string, using a specified starting position and length. 33 | SUBSTR( 'ABCDEF', 2, 3 ) -> BCD 34 | -- TRIM: Removes all specified characters from the beginning and end of a string. 35 | TRIM( 'ABC', 'A' ) -> BC 36 | -- LTRIM: Removes all occurrences of a specified set of characters from the left end of a string. 37 | LTRIM(' ABC ') -> 'ABC ' 38 | RTRIM(' ABC ') -> ' ABC' 39 | -- REGEXP_COUNT: Returns the number of times a pattern occurs in a string. 40 | REGEXP_COUNT( 'This is a playlist', 'is' ) -> 2 41 | -- REGEXP_INSTR: Returns the position of the first occurrence of a regular expression in a string. 42 | REGEXP_INSTR( 'This is a playlist', 'is' ) -> 3 43 | -- REGEXP_REPLACE: REGEXP_REPLACE( string, pattern, replace_with, position, occurrence, match_param ) 44 | REGEXP_REPLACE( 'This is a playlist', 'is', 'IS' ) -> ThIS IS a playlist 45 | -- REGEXP_SUBSTR: Returns the first occurrence of a regular expression in a string. 46 | REGEXP_SUBSTR( 'This is a playlist', 'is' ) -> is 47 | -- ...THERE ARE MANY READ FORM DOCS: https://www.oracletutorial.com/oracle-string-functions/ 48 | REPLACE( 'This is a test', 'is', 'IS' ) -> ThIS IS a test 49 | 50 | TRANSLATE("12345", "143", "bx") | 1 -> b, 4 -> x, 3 -> ''; | -> 'b2x5' 51 | 52 | REPLACE('JACK AND JOND','J','BL'); -> BLACK AND BLOND 53 | 54 | -- LISTAGG: Concatenates the values of a column into a single string. 55 | -- LISTAGG(expression [ WITHIN GROUP ( ORDER BY expression [, expression] ... ) [, DISTINCT ] [ , delimiter ] ) 56 | SELECT 57 | customer_id, 58 | LISTAGG(order_id, ', ') 59 | WITHIN GROUP (ORDER BY order_date DESC) AS order_list 60 | FROM orders 61 | GROUP BY customer_id 62 | FILTER (WHERE proficiency_level > 2) 63 | ORDER BY customer_id; 64 | 65 | SELECT level, department_id, LISTAGG(employee_name, ', ') AS dept_employees 66 | FROM employees 67 | START WITH manager_id IS NULL 68 | CONNECT BY PRIOR employee_id = manager_id 69 | ORDER BY level, department_id; 70 | 71 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/Oracle Basics/oracle-subquery.sql: -------------------------------------------------------------------------------- 1 | -- Oracle SQL Subqueries 2 | -- 1. Scalar Subqueries: 3 | SELECT * 4 | FROM employees 5 | WHERE salary > (SELECT AVG(salary) FROM employees); 6 | 7 | -- 2. Correlated Subqueries: 8 | SELECT manager_id, name 9 | FROM managers m 10 | WHERE (SELECT COUNT(*) FROM employees WHERE manager_id = m.manager_id) > 11 | (SELECT AVG(COUNT(*)) FROM employees GROUP BY department_id); 12 | 13 | -- 3. Subqueries in SELECT Clause 14 | SELECT e.employee_id, e.name, d.name AS department_name 15 | FROM employees e 16 | INNER JOIN departments d ON e.department_id = d.department_id 17 | WHERE e.salary > (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id); 18 | 19 | -- 4. Subqueries in FROM Clause 20 | SELECT * 21 | FROM orders o 22 | WHERE order_date < (SELECT AVG(order_date) FROM orders); 23 | 24 | -- 5. Subqueries in WHERE Clause 25 | SELECT * 26 | FROM customers 27 | WHERE customer_id IN (SELECT customer_id FROM orders WHERE order_date < TO_DATE('01-JAN-2023', 'DD-MON-YYYY')); 28 | 29 | 30 | 31 | 32 | -- Oracle Subquery 33 | -- A) Oracle subquery in the SELECT clause example 34 | SELECT 35 | *, 36 | (subquery) AS avg_list_price 37 | FROM 38 | inline_view; 39 | 40 | -- B) Oracle subquery in the FROM clause example 41 | SELECT * FROM (subquery) [AS] inline_view; 42 | 43 | -- C) Oracle subquery with comparison operators example 44 | SELECT * 45 | FROM 46 | products 47 | WHERE 48 | list_price > (subquery); 49 | 50 | -- D) Oracle subquery with IN and NOT IN operators 51 | SELECT * 52 | FROM 53 | employees 54 | WHERE 55 | employee_id IN(subquery) 56 | -- 57 | employee_id IN(subquery) 58 | -- 59 | (EMPLOYEE_ID, SALARY) INw(SELECT EMPLOYEE_ID, SALARY FROM EMPLOYEES WHERE SALARY > 10000) 60 | ORDER BY attrubutes; 61 | 62 | -- E) Oracle subquery with the EXISTS operator 63 | SELECT * 64 | FROM 65 | employees 66 | WHERE 67 | EXISTS(subquery); 68 | 69 | -- F) Oracle subquery with the ALL operator 70 | SELECT * 71 | FROM 72 | products 73 | WHERE 74 | list_price > ALL(subquery); 75 | 76 | 77 | -- `ROWNUM` <= 3" not supported in subqueries(ROWNUM works in main SELECT statements) -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/Oracle Basics/set-operators.sql: -------------------------------------------------------------------------------- 1 | -- data types should be same 2 | -- UNION - removes duplicates 3 | -- UNION ALL - does not remove duplicates 4 | -- INTERSECT - returns common rows 5 | -- MINUS - returns rows from first query that are not in second query 6 | 7 | 8 | 9 | -- Creating sample tables 10 | CREATE TABLE table1 ( 11 | id NUMBER, 12 | name VARCHAR2(50) 13 | ); 14 | 15 | CREATE TABLE table2 ( 16 | id NUMBER, 17 | name VARCHAR2(50) 18 | ); 19 | 20 | -- Inserting sample data 21 | INSERT INTO table1 (id, name) VALUES (1, 'John'); 22 | INSERT INTO table1 (id, name) VALUES (2, 'Alice'); 23 | INSERT INTO table1 (id, name) VALUES (3, 'Bob'); 24 | 25 | INSERT INTO table2 (id, name) VALUES (3, 'Bob'); 26 | INSERT INTO table2 (id, name) VALUES (4, 'Charlie'); 27 | 28 | 29 | -- Query using UNION 30 | SELECT id, name FROM table1 31 | UNION 32 | SELECT id, name FROM table2; 33 | /* 34 | ID NAME 35 | ---- ------- 36 | 1 John 37 | 2 Alice 38 | 3 Bob 39 | 4 Charlie 40 | 41 | */ 42 | 43 | 44 | 45 | -- Query using UNION ALL 46 | SELECT id, name FROM table1 47 | UNION ALL 48 | SELECT id, name FROM table2; 49 | 50 | /* 51 | ID NAME 52 | ---- ------- 53 | 1 John 54 | 2 Alice 55 | 3 Bob 56 | 3 Bob 57 | 4 Charlie 58 | */ 59 | 60 | -- Intersect 61 | /* 62 | 1 John 63 | 2 Alice 64 | 3 Bob 65 | 66 | 3 Bob 67 | 4 Charlie 68 | */ 69 | 70 | SELECT id, name FROM table1 71 | INTERSECT 72 | SELECT id, name FROM table2; 73 | 74 | /* 75 | ID NAME 76 | ---- ------- 77 | 3 Bob 78 | */ 79 | 80 | -- Minus 81 | SELECT id, name FROM table1 82 | MINUS 83 | SELECT id, name FROM table2; 84 | 85 | /* 86 | ID NAME 87 | ---- ------- 88 | 1 John 89 | 2 Alice 90 | */ 91 | 92 | 93 | select 1234 from dual 94 | UNION ALL 95 | select 1234 from dual 96 | union 97 | select 1234 from dual 98 | union 99 | select 1234 from dual 100 | INTERSECT 101 | select 1234 from dual 102 | union 103 | select 1234 from dual; -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/Oracle Basics/with-clause.sql: -------------------------------------------------------------------------------- 1 | drop table emp purge; 2 | drop table dept purge; 3 | 4 | create table dept ( 5 | deptno number(2) constraint pk_dept primary key, 6 | dname varchar2(14), 7 | loc varchar2(13) 8 | ) ; 9 | 10 | create table emp ( 11 | empno number(4) constraint pk_emp primary key, 12 | ename varchar2(10), 13 | job varchar2(9), 14 | mgr number(4), 15 | hiredate date, 16 | sal number(7,2), 17 | comm number(7,2), 18 | deptno number(2) constraint fk_deptno references dept 19 | ); 20 | 21 | insert into dept values (10,'ACCOUNTING','NEW YORK'); 22 | insert into dept values (20,'RESEARCH','DALLAS'); 23 | insert into dept values (30,'SALES','CHICAGO'); 24 | insert into dept values (40,'OPERATIONS','BOSTON'); 25 | 26 | insert into emp values (7369,'SMITH','CLERK',7902,to_date('17-12-1980','dd-mm-yyyy'),800,null,20); 27 | insert into emp values (7499,'ALLEN','SALESMAN',7698,to_date('20-2-1981','dd-mm-yyyy'),1600,300,30); 28 | insert into emp values (7521,'WARD','SALESMAN',7698,to_date('22-2-1981','dd-mm-yyyy'),1250,500,30); 29 | insert into emp values (7566,'JONES','MANAGER',7839,to_date('2-4-1981','dd-mm-yyyy'),2975,null,20); 30 | insert into emp values (7654,'MARTIN','SALESMAN',7698,to_date('28-9-1981','dd-mm-yyyy'),1250,1400,30); 31 | insert into emp values (7698,'BLAKE','MANAGER',7839,to_date('1-5-1981','dd-mm-yyyy'),2850,null,30); 32 | insert into emp values (7782,'CLARK','MANAGER',7839,to_date('9-6-1981','dd-mm-yyyy'),2450,null,10); 33 | insert into emp values (7788,'SCOTT','ANALYST',7566,to_date('13-JUL-87','dd-mm-rr')-85,3000,null,20); 34 | insert into emp values (7839,'KING','PRESIDENT',null,to_date('17-11-1981','dd-mm-yyyy'),5000,null,10); 35 | insert into emp values (7844,'TURNER','SALESMAN',7698,to_date('8-9-1981','dd-mm-yyyy'),1500,0,30); 36 | insert into emp values (7876,'ADAMS','CLERK',7788,to_date('13-JUL-87', 'dd-mm-rr')-51,1100,null,20); 37 | insert into emp values (7900,'JAMES','CLERK',7698,to_date('3-12-1981','dd-mm-yyyy'),950,null,30); 38 | insert into emp values (7902,'FORD','ANALYST',7566,to_date('3-12-1981','dd-mm-yyyy'),3000,null,20); 39 | insert into emp values (7934,'MILLER','CLERK',7782,to_date('23-1-1982','dd-mm-yyyy'),1300,null,10); 40 | commit; 41 | 42 | 43 | 44 | -- Non-ANSI Syntax 45 | select e.ename as employee_name, 46 | dc.dept_count as emp_dept_count 47 | from emp e, 48 | (select deptno, count(*) as dept_count 49 | from emp 50 | group by deptno) dc 51 | where e.deptno = dc.deptno; 52 | 53 | -- ANSI Syntax 54 | select e.ename as employee_name, 55 | dc.dept_count as emp_dept_count 56 | from emp e 57 | join (select deptno, count(*) as dept_count 58 | from emp 59 | group by deptno) dc 60 | on e.deptno = dc.deptno; 61 | 62 | 63 | 64 | -- Non-ANSI Syntax 65 | with dept_count as ( 66 | select deptno, count(*) as dept_count 67 | from emp 68 | group by deptno 69 | ) 70 | select e.ename as employee_name, 71 | dc.dept_count as emp_dept_count 72 | from emp e, 73 | dept_count dc 74 | where e.deptno = dc.deptno; 75 | 76 | -- ANSI Syntax 77 | with dept_count as ( 78 | select deptno, count(*) as dept_count 79 | from emp 80 | group by deptno 81 | ) 82 | select e.ename as employee_name, 83 | dc.dept_count as emp_dept_count 84 | from emp e 85 | join dept_count dc on e.deptno = dc.deptno; 86 | 87 | 88 | -- Non-ANSI Syntax 89 | select e.ename as employee_name, 90 | dc1.dept_count as emp_dept_count, 91 | m.ename as manager_name, 92 | dc2.dept_count as mgr_dept_count 93 | from emp e, 94 | (select deptno, count(*) as dept_count 95 | from emp 96 | group by deptno) dc1, 97 | emp m, 98 | (x(*) as dept_count 99 | from emp 100 | group by deptno) dc2 101 | where e.deptno = dc1.deptno 102 | and e.mgr = m.empno 103 | and m.deptno = dc2.deptno; 104 | 105 | -- ANSI Syntax 106 | select e.ename as employee_name, 107 | dc1.dept_count as emp_dept_count, 108 | m.ename as manager_name, 109 | dc2.dept_count as mgr_dept_count 110 | from emp e 111 | join (select deptno, count(*) as dept_count 112 | from emp 113 | group by deptno) dc1 114 | on e.deptno = dc1.deptno 115 | join emp m on e.mgr = m.empno 116 | join (select deptno, count(*) as dept_count 117 | from emp 118 | group by deptno) dc2 119 | on m.deptno = dc2.deptno; 120 | 121 | 122 | -- Non-ANSI Syntax 123 | with dept_count as ( 124 | select deptno, count(*) as dept_count 125 | from emp 126 | group by deptno 127 | ) 128 | select e.ename as employee_name, 129 | dc1.dept_count as emp_dept_count, 130 | m.ename as manager_name, 131 | dc2.dept_count as mgr_dept_count 132 | from emp e, 133 | dept_count dc1, 134 | emp m, 135 | dept_count dc2 136 | where e.deptno = dc1.deptno 137 | and e.mgr = m.empno 138 | and m.deptno = dc2.deptno; 139 | 140 | -- ANSI Syntax 141 | with dept_count as ( 142 | select deptno, count(*) as dept_count 143 | from emp 144 | group by deptno 145 | ) 146 | select e.ename as employee_name, 147 | dc1.dept_count as emp_dept_count, 148 | m.ename as manager_name, 149 | dc2.dept_count as mgr_dept_count 150 | from emp e 151 | join dept_count dc1 on e.deptno = dc1.deptno 152 | join emp m on e.mgr = m.empno 153 | join dept_count dc2 on m.deptno = dc2.deptno; -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/Oracle Database Administration/Roles.sql: -------------------------------------------------------------------------------- 1 | -- Section 5. Roles 2 | -- CREATE ROLE – show you how to group object or system privileges into a role and grant the role to users. 3 | -- SET ROLE – enable and disable roles for your current session. 4 | -- ALTER ROLE – modify the authorization needed to enable a role. 5 | -- DROP ROLE – learn how to remove a role from the database. 6 | 7 | 8 | 9 | 10 | -- 1) Using Oracle CREATE ROLE without a password example 11 | 12 | CREATE ROLES mdm; 13 | 14 | GRANT SELECT, INSERT, UPDATE, DELETE 15 | ON customers 16 | TO mdm; 17 | 18 | GRANT SELECT, INSERT, UPDATE, DELETE 19 | ON contacts 20 | TO mdm; 21 | 22 | GRANT SELECT, INSERT, UPDATE, DELETE 23 | ON products 24 | TO mdm; 25 | 26 | GRANT SELECT, INSERT, UPDATE, DELETE 27 | ON product_categories 28 | TO mdm; 29 | 30 | GRANT SELECT, INSERT, UPDATE, DELETE 31 | ON warehouses 32 | TO mdm; 33 | 34 | GRANT SELECT, INSERT, UPDATE, DELETE 35 | ON locations 36 | TO mdm; 37 | 38 | GRANT SELECT, INSERT, UPDATE, DELETE 39 | ON employees 40 | TO mdm; 41 | 42 | 43 | CREATE USER alice IDENTIFIED BY abcd1234; 44 | 45 | GRANT CREATE SESSION TO alice; 46 | 47 | 48 | -- Fourth, log in to the database as alice: 49 | 50 | -- Enter user-name: alice@pdborcl 51 | -- Enter password: 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | -- 2) Using Oracle CREATE ROLE to create a role with IDENTIFIED BY password example 79 | CREATE ROLE order_entry IDENTIFIED BY xyz123; 80 | GRANT SELECT, INSERT, UPDATE, DELETE 81 | ON orders 82 | TO order_entry; 83 | 84 | GRANT SELECT, INSERT, UPDATE, DELETE 85 | ON order_items 86 | TO order_entry; 87 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/OracleSQL_AnalyticalFunctions_2024.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/OracleSQL_AnalyticalFunctions_2024.pdf -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/oracle-comparison-functions.sql: -------------------------------------------------------------------------------- 1 | -- *Oracle Comparison Functions 2 | -- * COALESCE – function to return the first non-null arguments in a list. 3 | -- * DECODE – learn how to add if-then-else logic to a SQL query. 4 | -- * NVL – return the first argument if it is not null, otherwise, returns the second argument. 5 | -- * NVL2 – show you how to substitute a null value with various options.(1,2,3) 6 | -- * NULLIF – return a null if the first argument equals the second one, otherwise, returns the first argument. 7 | 8 | 9 | -- coalesce: return the first non-null value in a list 10 | SELECT COALESCE(NULL, NULL, NULL, 'A', 'B', 'C') FROM dual; -- A 11 | SELECT COALESCE(NULL, NULL, NULL, NULL, NULL, NULL) FROM dual; -- null 12 | 13 | -- nvl(a, b): 14 | -- If a is not null, then nvl(a, b) returns a. 15 | -- nvl(a, b) returns b. 16 | 17 | SELECT NVL(100,200) 18 | FROM dual; -- 100 19 | 20 | SELECT NVL(NULL, 'a is null && i"m b') 21 | FROM dual; 22 | 23 | 24 | SELECT 25 | order_id, 26 | NVL(first_name, 'Not Assigned') 27 | FROM 28 | orders 29 | LEFT JOIN employees 30 | ON 31 | employee_id = salesman_id 32 | WHERE 33 | EXTRACT(YEAR FROM order_date) = 2016 34 | ORDER BY 35 | order_date; 36 | 37 | 38 | SELECT 39 | order_id, 40 | CASE 41 | WHEN first_name IS NOT NULL 42 | THEN first_name 43 | ELSE 'Not Assigned' 44 | END 45 | FROM 46 | orders 47 | LEFT JOIN employees 48 | ON employee_id = salesman_id 49 | WHERE 50 | EXTRACT(YEAR FROM order_date) = 2016 51 | ORDER BY 52 | order_date; 53 | 54 | -- nvl2(a, b, c) - ternary operator but not experession: 55 | SELECT NVL2(condition if true 1 else 2, 1, 2) FROM dual; --1 56 | SELECT NVL2('not null', 1, 2) FROM dual; --1 57 | SELECT NVL2(NULL, 1, 2) FROM dual; --2 58 | 59 | 60 | -- nullif(a, b): return a if not equal else null: 61 | SELECT NULLIF(10,'20') 62 | FROM dual; 63 | 64 | SELECT NULLIF(100,100) -- null 65 | FROM dual; 66 | 67 | SELECT NULLIF(100,200) -- 0 68 | FROM dual; 69 | 70 | -- decode(a, b, c): if a = b then c else a 71 | SELECT DECODE(1, 1, 'One') 72 | FROM dual; -- One 73 | SELECT DECODE(2, 1, 'One', 2, 'Two') 74 | FROM dual; -- Two 75 | 76 | DECODE(NULL,NULL,'Equal','Not equal') 77 | 78 | DECODE(country_id, 79 | 'US','United States', 80 | 'UK', 'United Kingdom', 81 | 'JP','Japan', 82 | 'CA', 'Canada', 83 | 'CH','Switzerland', 84 | 'IT', 'Italy', country_id) AS country 85 | 86 | SELECT customer_id, 87 | DECODE(credit_rating, 88 | 'A', 'Excellent', 89 | 'B', 'Good', 90 | 'C', 'Fair', 91 | 'D', 'Needs Improvement', 92 | 'Other', 'Unknown') AS credit_status 93 | FROM customers; 94 | 95 | 96 | DECLARE 97 | my_constant CONSTANT NUMBER := NULL; 98 | BEGIN 99 | -- Attempting to change the value of the constant will result in a compilation error 100 | -- my_constant := 10; 101 | DBMS_OUTPUT.PUT_LINE('The value of my_constant is ' || my_constant); 102 | END; -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/oracle-db/ot_create_user.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/oracle-db/ot_create_user.sql -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/oracle-db/ot_data.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/oracle-db/ot_data.sql -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/oracle-db/ot_drop.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/oracle-db/ot_drop.sql -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/oracle-db/ot_schema.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/oracle-db/ot_schema.sql -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/oracle-index.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE members( 2 | member_id INT GENERATED BY DEFAULT AS IDENTITY, 3 | first_name VARCHAR2(100) NOT NULL, 4 | last_name VARCHAR2(100) NOT NULL, 5 | gender CHAR(1) NOT NULL, 6 | dob DATE NOT NULL, 7 | email VARCHAR2(255) NOT NULL, 8 | PRIMARY KEY(member_id) 9 | ); 10 | 11 | -- https://www.oracletutorial.com/wp-content/uploads/2019/01/load_member_data.txt 12 | 13 | SELECT 14 | index_name, 15 | index_type, 16 | visibility, 17 | status 18 | FROM 19 | all_indexes 20 | WHERE 21 | table_name = 'MEMBERS'; 22 | 23 | 24 | CREATE INDEX members_last_name_i 25 | ON members(last_name); 26 | 27 | SELECT * FROM members 28 | WHERE last_name = 'Harse'; 29 | 30 | CREATE UNIQUE INDEX index_name ON 31 | table_name(column1[,column2,...]); 32 | 33 | DROP INDEX [schema_name.]index_name; 34 | 35 | -- https://www.oracletutorial.com/oracle-index/ 36 | - effective tools for boost the query performance. 37 | However, in order to use it effectively, you must understand it correctly. This section helps you understand and use Oracle indexes to speed up your queries. 38 | 39 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/oracle-merge.sql: -------------------------------------------------------------------------------- 1 | -- Merge data from source_table to target_table 2 | CREATE TABLE target_table ( 3 | id NUMBER PRIMARY KEY, 4 | name VARCHAR2(50), 5 | age NUMBER 6 | ); 7 | 8 | CREATE TABLE source_table ( 9 | id NUMBER, 10 | name VARCHAR2(50), 11 | age NUMBER 12 | ); 13 | 14 | INSERT INTO target_table VALUES (1, 'John', 30); 15 | INSERT INTO target_table VALUES (2, 'Alice', 25); 16 | 17 | INSERT INTO source_table VALUES (1, 'John', 31); 18 | INSERT INTO source_table VALUES (3, 'Bob', 28); 19 | 20 | SELECT * FROM target_table; 21 | SELECT * FROM source_table; 22 | 23 | MERGE INTO target_table tgt 24 | USING source_table src 25 | ON (tgt.id = src.id) 26 | WHEN MATCHED THEN 27 | UPDATE SET tgt.name = src.name, tgt.age = src.age 28 | WHEN NOT MATCHED THEN 29 | INSERT (id, name, age) 30 | VALUES (src.id, src.name, src.age); 31 | 32 | SELECT * FROM target_table; 33 | /* 34 | ID | NAME | AGE 35 | ------------------ 36 | 1 | John | 31 37 | 2 | Alice | 25 38 | 3 | Bob | 28 39 | */ -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/oracle-view.sql: -------------------------------------------------------------------------------- 1 | /* 2 | * refere gaurav's notes romee 3 | * view's are also called as virtual tables. 4 | * (Virtual/logical table) or 5 | * (database object) 6 | * (virtual entity) 7 | * (no space is taken, extract data from table) 8 | * (slow results because it renders the info from the exst table) 9 | * dependent logical object 10 | * may or may not allow DML 11 | * only the definition of a view is stored in the data dictionary, it doew not actually exist as a separate tables 12 | * Oracle allows the creation of an object called view 13 | * Types of Views 14 | * Simple View: contains only one table, no group by, no aggregate functions, no subqueries 15 | * Complex View: contains more than one table, group by, aggregate functions, subqueries 16 | * Read Only View(Non-updatable view): (only allows SELECT)does not allow DML operations 17 | * Updatable View: allows DML operations 18 | * (INSERT, UPDATE, DELETE are actually happening on the table on which it is created), 19 | * (thease view contains pk and all not null columns of the base table) 20 | * syntzx: WITH CHECK OPTION; 21 | * Inline View: a subquery in the FROM clause of a SELECT statement 22 | * Materialized View: stores the result of a query in a table, stores the definition and data, if changed then replaced 23 | * oracle uses materialized view it creates a snapshorts in prior. 24 | create materialized view mview as select ...; 25 | 26 | * Views can be updated under followings: If the view consists of the primary key of the table based on which the view has been created. If the view is defined based on one and only one table. 27 | * "WITH CHECK OPTION" ensures that any data modification made through a view meets the criteria specified by the view's query. It prevents inserting, updating, or deleting rows that do not satisfy the view's filtering conditions. 28 | */ 29 | CREATE VIEW employee_yos AS 30 | SELECT first_name || ' ' || last_name AS employee_name, CURRENT_DATE 31 | FROM customers_S2; 32 | 33 | 34 | CREATE OR REPLACE VIEW employee_yos (employee_name, toDay) AS 35 | SELECT first_name || ' ' || last_name AS employee_name, CURRENT_DATE 36 | FROM customers_S2 37 | ORDER BY employee_name; 38 | 39 | DROP VIEW employee_yos; 40 | 41 | 42 | SELECT * FROM employee_yos; 43 | 44 | CREATE OR REPLACE VIEW backlogs AS 45 | SELECT 46 | product_name, 47 | EXTRACT( YEAR from order_date) YEAR, 48 | SUM(quantity * unit_price) amount 49 | FROM orders 50 | INNER JOIN order_items USING(order_id) 51 | INNER JOIN products USING(product_id) 52 | WHERE status = 'Pending' 53 | GROUP BY EXTRACT(YEAR FROM order_data), product_name; 54 | 55 | 56 | -- update or delete 57 | UPDATE or DELETE employee_yos 58 | [same as tables]; 59 | 60 | 61 | -- create a materialized view emp 62 | CREATE MATERIALIZED VIEW MempView AS 63 | SELECT * FROM emp; -- base tables and stored on the disk 64 | 65 | -- faster in execution 66 | 67 | 68 | 69 | -- Inline View in Oracle 70 | -- a subquery in the FROM clause of a SELECT statement 71 | 72 | 73 | 74 | 75 | 76 | 77 | DROP TABLE cars; 78 | DROP TABLE brands; 79 | 80 | 81 | SELECT * FROM CARS; 82 | SELECT * FROM BRANDS; 83 | 84 | CREATE TABLE brands( 85 | brand_id NUMBER GENERATED BY DEFAULT AS IDENTITY, 86 | brand_name VARCHAR2(50) NOT NULL, 87 | PRIMARY KEY(brand_id) 88 | ); 89 | 90 | CREATE TABLE cars ( 91 | car_id NUMBER GENERATED BY DEFAULT AS IDENTITY, 92 | car_name VARCHAR2(255) NOT NULL, 93 | brand_id NUMBER NOT NULL, 94 | PRIMARY KEY(car_id), 95 | FOREIGN KEY(brand_id) 96 | REFERENCES brands(brand_id) ON DELETE CASCADE 97 | ); 98 | 99 | INSERT INTO brands(brand_name) 100 | VALUES('Audi'); 101 | 102 | INSERT INTO brands(brand_name) 103 | VALUES('BMW'); 104 | 105 | INSERT INTO brands(brand_name) 106 | VALUES('Ford'); 107 | 108 | INSERT INTO brands(brand_name) 109 | VALUES('Honda'); 110 | 111 | INSERT INTO brands(brand_name) 112 | VALUES('Toyota'); 113 | 114 | INSERT INTO cars (car_name,brand_id) 115 | VALUES('Audi R8 Coupe',1); 116 | 117 | INSERT INTO cars (car_name,brand_id) 118 | VALUES('Audi Q2', 1); 119 | 120 | INSERT INTO cars (car_name,brand_id) 121 | VALUES('Audi S1', 1); 122 | 123 | INSERT INTO cars (car_name,brand_id) 124 | VALUES('BMW 2-serie Cabrio',2); 125 | 126 | INSERT INTO cars (car_name,brand_id) 127 | VALUES('BMW i8', 2); 128 | 129 | INSERT INTO cars (car_name,brand_id) 130 | VALUES('Ford Edge',3); 131 | 132 | INSERT INTO cars (car_name,brand_id) 133 | VALUES('Ford Mustang Fastback', 3); 134 | 135 | INSERT INTO cars (car_name,brand_id) 136 | VALUES('Honda S2000', 4); 137 | 138 | INSERT INTO cars (car_name,brand_id) 139 | VALUES('Honda Legend', 4); 140 | 141 | INSERT INTO cars (car_name,brand_id) 142 | VALUES('Toyota GT86', 5); 143 | 144 | INSERT INTO cars (car_name,brand_id) 145 | VALUES('Toyota C-HR', 5); 146 | 147 | 148 | CREATE OR REPLACE VIEW cars_master AS 149 | SELECT 150 | car_id, 151 | car_name 152 | FROM 153 | cars; 154 | 155 | SELECT * FROM cars_master; 156 | 157 | DELETE 158 | FROM 159 | cars_master 160 | WHERE 161 | car_id = 2; 162 | 163 | SELECT * FROM cars_master; -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/synchronized-backup.sql: -------------------------------------------------------------------------------- 1 | -- synchronized backup copy of a table using DML Trigger 2 | /* 3 | Table 1 (Main Table) 4 | Table 2 (Backup Table) 5 | 6 | 7 | */ 8 | 9 | create table main_table( 10 | id int 11 | ); 12 | 13 | Insert into main_table values(1); 14 | Insert into main_table values(2); 15 | 16 | create table main_table_backup AS 17 | select * from main_table where 1=2; 18 | 19 | 20 | select * from main_table; 21 | select * from main_table_backup; 22 | 23 | 24 | CREATE OR REPLACE TRIGGER main_table_backup_trigger 25 | BEFORE INSERT OR DELETE OR UPDATE ON main_table 26 | FOR EACH ROW 27 | BEGIN 28 | IF INSERTING THEN 29 | INSERT INTO main_table_backup VALUES(:new.id); 30 | ELSIF DELETING THEN 31 | DELETE FROM main_table_backup WHERE id = :old.id; 32 | ELSIF UPDATING THEN 33 | UPDATE main_table_backup SET id = :new.id WHERE id = :old.id; 34 | END IF; 35 | END; 36 | / 37 | 38 | Insert into main_table values(10); 39 | Insert into main_table values(11); 40 | 41 | select * from main_table; 42 | select * from main_table_backup; 43 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/temporary-tables.sql: -------------------------------------------------------------------------------- 1 | -- Temporary Tables 2 | /* 3 | Oracle Global Temporary Table: 4 | - structure of the table accessible to all users but not the data, every user has their own data 5 | 6 | */ 7 | 8 | -- Create a Global Temporary Table 9 | CREATE GLOBAL TEMPORARY TABLE temp_orders ( 10 | order_id NUMBER, 11 | product_name VARCHAR2(100), 12 | quantity NUMBER 13 | ) ON COMMIT DELETE ROWS; 14 | 15 | -- Insert data into the temporary table 16 | INSERT INTO temp_orders (order_id, product_name, quantity) 17 | VALUES (1, 'Product A', 10); 18 | 19 | -- Select data from the temporary table 20 | SELECT * FROM temp_orders; 21 | 22 | -- Output: 23 | -- ORDER_ID PRODUCT_NAME QUANTITY 24 | -- 1 Product A 10 25 | 26 | -- Data in the temporary table will be automatically deleted at the end of the session or when explicitly deleted. 27 | 28 | 29 | -- Oracle Private Temporary Table 30 | CREATE PRIVATE TEMPORARY TABLE table_name( 31 | column_definition, 32 | ... 33 | ) ON COMMIT [DROP DEFINITION | PRESERVE DEFINITION]; 34 | -- ON COMMIT DROP DEFINITION/ON COMMIT PRESERVE DEFINITION 35 | 36 | 37 | 38 | -- In Oracle Database, global temporary tables are permanent objects whose data are stored on disk and automatically deleted at the end of a session or transaction. In addition, global temporary tables are visible to all sessions currently connected to the database. 39 | 40 | 41 | -- 0. Global Temporary Tables: 42 | 43 | 44 | CREATE GLOBAL TEMPORARY TABLE temp1( 45 | id INT, 46 | description VARCHAR2(100) 47 | ) ON COMMIT DELETE ROWS; 48 | 49 | -- Transaction specific global temporary table 50 | BEGIN 51 | INSERT INTO temp1(id,description) 52 | VALUES(1,'Transaction specific global temp table'); 53 | 54 | SELECT id, description 55 | FROM temp1; 56 | END; 57 | 58 | COMMENT; 59 | 60 | 61 | -- 1.Inline Temporary Tables (WITH clause): 62 | -- Define an inline temporary table using the WITH clause 63 | WITH temp_orders AS ( 64 | SELECT order_id, order_date, total_amount 65 | FROM orders 66 | WHERE order_date >= DATE '2024-01-01' AND order_date < DATE '2024-02-01' 67 | ) 68 | -- Query the inline temporary table 69 | SELECT * FROM temp_orders; 70 | 71 | 72 | SELECT user_id, COUNT(*) 73 | FROM MovieRating 74 | -- // Remove the unnecessary GROUP BY clause 75 | -- // GROUP BY user_id 76 | FETCH FIRST 1 ROWS ONLY; -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/transaction-control.sql: -------------------------------------------------------------------------------- 1 | -- Transaction Control 2 | /* 3 | - a transaction is a sequence of operations performed as a single logical unit of work 4 | - a transaction usually means that the data in the database has changed. 5 | - a transaction has only two results: success or failure 6 | 7 | Commands: 8 | - COMMIT: Saves changes made during the transaction to the database. 9 | - ROLLBACK: Discards changes made during the transaction and restores the database to its state before the transaction began. 10 | - SAVEPOINT: Sets a point within the transaction to which you can later rollback. SAVEPOINT sp1; 11 | - SET TRANSACTION: change transaction options like isolation level and what kind of lock to use 12 | - Rollback is possible of dml commands only 13 | ROLLBACK TO SAVEPOINT sp1; 14 | - AUTOCOMMIT: Automatically commits each SQL statement as a separate transaction. Turned on by default in some systems. 15 | SET AUTOCOMMIT OFF; 16 | - RELEASE SAVEPOINT: Removes a savepoint from the transaction. 17 | RELEASE SAVEPOINT sp1; 18 | 19 | */ 20 | 21 | -- Begin the transaction 22 | BEGIN TRANSACTION; 23 | 24 | -- Withdraw money from account A 25 | UPDATE accounts SET balance = balance - 100 WHERE account_id = 'A'; 26 | 27 | -- Deposit money into account B 28 | UPDATE accounts SET balance = balance + 100 WHERE account_id = 'B'; 29 | 30 | -- Commit the transaction if both updates succeed 31 | COMMIT; 32 | -- Rollback the transaction if any update fails 33 | ROLLBACK; 34 | 35 | 36 | 37 | -- EG. 38 | 39 | -- Begin the transaction 40 | BEGIN TRANSACTION; 41 | 42 | -- Set the isolation level to Serializable for consistency 43 | SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; 44 | 45 | -- Savepoint before deducting items from inventory 46 | SAVEPOINT before_deduct_inventory; 47 | 48 | -- Deduct items from inventory for the ordered products 49 | UPDATE inventory 50 | SET quantity = quantity - 1 51 | WHERE product_id = 'XYZ' AND quantity >= 1; 52 | 53 | -- Check if the update affected any rows, if not, rollback to the savepoint 54 | IF SQL%ROWCOUNT = 0 THEN 55 | ROLLBACK TO SAVEPOINT before_deduct_inventory; 56 | RAISE_APPLICATION_ERROR(-20001, 'Insufficient inventory'); 57 | END IF; 58 | 59 | -- Savepoint before updating the order status 60 | SAVEPOINT before_update_order_status; 61 | 62 | -- Update the order status to 'Shipped' 63 | UPDATE orders 64 | SET status = 'Shipped' 65 | WHERE order_id = '123' AND status = 'Pending'; 66 | 67 | -- Check if the update affected any rows, if not, rollback to the savepoint 68 | IF SQL%ROWCOUNT = 0 THEN 69 | ROLLBACK TO SAVEPOINT before_update_order_status; 70 | RAISE_APPLICATION_ERROR(-20002, 'Failed to update order status'); 71 | END IF; 72 | 73 | -- Commit the transaction if all updates succeed 74 | COMMIT; 75 | -- Rollback the transaction if any update fails 76 | ROLLBACK; 77 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/truncate.sql: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | TRUNCATE TABLE schema_name.table_name 5 | [CASCADE] 6 | [[ PRESERVE | PURGE] MATERIALIZED VIEW LOG ]] 7 | [[ DROP | REUSE]] STORAGE ] 8 | 9 | PURGE: 10 | In simple terms, using PURGE in the SQL statement means you want to completely get rid of the record of changes (log) that is associated with the table you're truncating. It's like saying, "Not only do I want to remove the data from the table, but I also want to erase any history or log of changes related to it." 11 | PRESERVE: 12 | In easy terms, using PRESERVE in the SQL statement means you want to keep and maintain the record of changes (log) associated with the table even after truncating it. Its like saying, "Remove the data from the table, but please keep a record of any changes made to it in the past." 13 | 14 | 15 | TRUNCATE TABLE schema_name.table_name: Removes all rows from the specified table while preserving the table structure. 16 | 17 | [CASCADE]: Optional keyword indicating that dependent objects (e.g., foreign keys) should also be truncated. 18 | 19 | [[ PRESERVE | PURGE] MATERIALIZED VIEW LOG ]: Optional clause for preserving or purging materialized view logs associated with the table. 20 | 21 | [[ DROP | REUSE]] STORAGE ]: Optional clause for dropping or reusing storage space. -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/1]_Oracle baby/virtual-column.sql: -------------------------------------------------------------------------------- 1 | 2 | -- virtual column(full_name, gross_margin) : https://www.oracletutorial.com/oracle-basics/oracle-virtual-column/ 3 | -- Advantages and disadvantages of virtual columns 4 | -- Virtual column limitations ... more 5 | 6 | 7 | -- Virtual columns ensure the values are always in sync with the source columns. For example, if you have a date column as the normal column and have the month, quarter, and year columns as the virtual columns. The values in the month, quarter, and year are always in sync with the date column 8 | -- Reduce query performance because their values are calculated at run-time. 9 | 10 | 11 | CREATE TABLE accounts ( 12 | account_id NUMBER GENERATED BY DEFAULT AS IDENTITY, 13 | first_name VARCHAR2(25) NOT NULL, 14 | last_name VARCHAR2(25) NOT NULL, 15 | email VARCHAR2(100), 16 | phone VARCHAR2(12) , 17 | full_name VARCHAR2(51) GENERATED ALWAYS AS( 18 | first_name || ' ' || last_name 19 | ), 20 | gross_margin AS ((list_price - cost) / cost), 21 | PRIMARY KEY(account_id) 22 | ); 23 | 24 | 25 | CREATE TABLE parts( 26 | part_id INT GENERATED ALWAYS AS IDENTITY, 27 | part_name VARCHAR2(50) NOT NULL, 28 | capacity INT NOT NULL, 29 | cost DEC(15,2) NOT NULL, 30 | list_price DEC(15,2) NOT NULL, 31 | gross_margin AS ROUND((list_price - cost) / cost), 32 | PRIMARY KEY(part_id) 33 | ); 34 | 35 | INSERT INTO parts(part_name, capacity, cost, list_price) 36 | VALUES('G.SKILL TridentZ RGB Series 16GB (2 x 8GB)', 16, 95,105); 37 | 38 | INSERT INTO parts(part_name, capacity, cost, list_price) 39 | VALUES('G.SKILL TridentZ RGB Series 32GB (4x8GB)', 32, 205,220); 40 | 41 | INSERT INTO parts(part_name, capacity, cost, list_price) 42 | VALUES('G.SKILL TridentZ RGB Series 16GB (1 x 8GB)', 8, 50,70); 43 | 44 | 45 | SELECT * from parts; 46 | 47 | 48 | ALTER TABLE parts 49 | ADD ( 50 | capacity_description AS ( 51 | CASE 52 | WHEN capacity <= 8 THEN 'Small' 53 | WHEN capacity > 8 AND capacity <= 16 THEN 'Medium' 54 | WHEN capacity > 16 THEN 'Large' 55 | END) 56 | ) 57 | 58 | 59 | drop TABLE parts; -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/1. Assignment for 31-Jan-2024/1]_Normalization Prac/NF.txt: -------------------------------------------------------------------------------- 1 | Full Link: https://docs.google.com/spreadsheets/d/1M6h4vWZqQlwjWZuumF1ALPxosW3HSSa412oUlKgM2Wk/edit?usp=sharing 2 | 3 | DID -> Department ID 4 | Dname -> Department Name 5 | EID -> Employee ID 6 | Ename -> Employee Name 7 | Btime -> Budgeted Time 8 | PID -> Project ID 9 | Pname -> Project Name 10 | 11 | 12 | DID -> Department ID 13 | Dname -> Department Name 14 | EID -> Employee ID 15 | Ename -> Employee Name 16 | Btime -> Budgeted Time 17 | PID -> Project ID 18 | Pname -> Project Name 19 | 20 | DID -> Dname 21 | EID -> Ename 22 | EID and PID ->Btime 23 | EID -> DID 24 | PID -> Pname 25 | 26 | CK: (EID, PID) -> (EID, PID, DID, Btime, Ename, Dname, Pname) 27 | EID -> (EID, DID, Ename, Dname) 28 | PID -> (PID, Pname) 29 | 30 | DID -> Dname 31 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/1. Assignment for 31-Jan-2024/1]_Normalization Prac/Normalization exercersie.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/1. Assignment for 31-Jan-2024/1]_Normalization Prac/Normalization exercersie.xlsx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/1. Assignment for 31-Jan-2024/2]_DDL & DML/162338_nex1_31Jan24.sql: -------------------------------------------------------------------------------- 1 | -- DDL/DML for the following ER diagram 2 | 3 | -- student 4 | -- student_id(pk) student_name 5 | -- 1 Adams 6 | -- 2 Jones 7 | -- 3 Smith 8 | -- 4 Baker 9 | 10 | -- faculty 11 | -- faculty_id(pk) faculty_name faculty_phone 12 | -- 1 Howser 60192 13 | -- 2 Langley 45869 14 | 15 | -- course 16 | -- course_id(pk) faculty_id* course_name 17 | -- IS318 1 Database 18 | -- IS301 2 EC 19 | 20 | -- students_grade 21 | -- (student_id* course_id*)pk student_grade 22 | -- 1 IS318 A 23 | -- 1 IS301 B 24 | -- 2 IS318 A 25 | -- 3 IS318 B 26 | -- 4 IS301 A 27 | -- 4 IS318 B 28 | 29 | 30 | -- Create student table 31 | CREATE TABLE student ( 32 | student_id NUMBER GENERATED BY DEFAULT AS IDENTITY 33 | START WITH 1 PRIMARY KEY, 34 | student_name VARCHAR2( 50 ) NOT NULL 35 | ); 36 | 37 | -- Create faculty table 38 | CREATE TABLE faculty ( 39 | faculty_id NUMBER GENERATED BY DEFAULT AS IDENTITY 40 | START WITH 1 PRIMARY KEY, 41 | faculty_name VARCHAR2( 50 ) NOT NULL, 42 | faculty_phone VARCHAR2( 20 ) NOT NULL 43 | ); 44 | 45 | -- Create course table 46 | CREATE TABLE course ( 47 | course_id VARCHAR2( 5 ) PRIMARY KEY, 48 | faculty_id NUMBER NOT NULL, -- fk 49 | course_name VARCHAR2( 50 ) NOT NULL, 50 | CONSTRAINT fk_course_faculty 51 | FOREIGN KEY( faculty_id ) 52 | REFERENCES faculty( faculty_id ) 53 | ON DELETE SET NULL 54 | ); 55 | 56 | -- Create students_grade table 57 | CREATE TABLE students_grade ( 58 | student_id NUMBER NOT NULL, -- fk 59 | course_id VARCHAR2( 5 ) NOT NULL, -- fk 60 | student_grade VARCHAR2( 2 ) NOT NULL, 61 | CONSTRAINT pk_students_grade 62 | PRIMARY KEY ( student_id, course_id ), 63 | CONSTRAINT fk_students_grade_student_id 64 | FOREIGN KEY( student_id ) 65 | REFERENCES student( student_id ) 66 | ON DELETE CASCADE, 67 | CONSTRAINT fk_students_grade_course_id 68 | FOREIGN KEY( course_id ) 69 | REFERENCES course( course_id ) 70 | ON DELETE CASCADE 71 | ); 72 | 73 | -- Insert data into student table 74 | INSERT INTO student ( student_name ) VALUES ( 'Adams' ); 75 | INSERT INTO student ( student_name ) VALUES ( 'Jones' ); 76 | INSERT INTO student ( student_name ) VALUES ( 'Smith' ); 77 | INSERT INTO student ( student_name ) VALUES ( 'Baker' ); 78 | 79 | -- Insert data into faculty table 80 | INSERT INTO faculty ( faculty_name, faculty_phone ) VALUES ( 'Howser', '60192' ); 81 | INSERT INTO faculty ( faculty_name, faculty_phone ) VALUES ( 'Langley', '45869' ); 82 | 83 | -- Insert data into course table 84 | INSERT INTO course ( course_id, faculty_id, course_name ) VALUES ( 'IS318', 1, 'Database' ); 85 | INSERT INTO course ( course_id, faculty_id, course_name ) VALUES ( 'IS301', 2, 'EC' ); 86 | 87 | -- Insert data into students_grade table 88 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 1, 'IS318', 'A' ); 89 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 1, 'IS301', 'B' ); 90 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 2, 'IS318', 'A' ); 91 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 3, 'IS318', 'B' ); 92 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 4, 'IS301', 'A' ); 93 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 4, 'IS318', 'B' ); 94 | 95 | 96 | -- Select all data from all tables 97 | SELECT * FROM student; 98 | SELECT * FROM faculty; 99 | SELECT * FROM course; 100 | SELECT * FROM students_grade; 101 | 102 | -- Drop the tables 103 | DROP TABLE students_grade; 104 | DROP TABLE course; 105 | DROP TABLE faculty; 106 | DROP TABLE student; -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/1. Assignment for 31-Jan-2024/2]_DDL & DML/162338_nex2_31Jan24.sql: -------------------------------------------------------------------------------- 1 | -- DDL/DML for the following ER diagram 2 | 3 | -- department 4 | -- dept_id dept_name 5 | -- 10 Finance 6 | -- 14 R&D 7 | 8 | -- project 9 | -- proj_id(pk) proj_name 10 | -- 27 alpha 11 | -- 25 beta 12 | -- 22 gamma 13 | -- 26 pail 14 | -- 21 hill 15 | 16 | -- employee 17 | -- empl_id(pk) empl_name dept_id* 18 | -- 1 Huey 10 19 | -- 5 Dewey 10 20 | -- 11 Louie 10 21 | -- 2 Jack 14 22 | -- 4 Jill 14 23 | 24 | -- works_on 25 | -- (empl_id* proj_id*)pk hours 26 | -- 1 27 4.5 27 | -- 5 25 3 28 | -- 11 22 7 29 | -- 2 26 8 30 | -- 4 21 9 31 | 32 | -- Create department table 33 | CREATE TABLE department ( 34 | dept_id NUMBER PRIMARY KEY, 35 | dept_name VARCHAR2( 50 ) NOT NULL 36 | ); 37 | 38 | -- Create project table 39 | CREATE TABLE project ( 40 | proj_id NUMBER PRIMARY KEY, 41 | proj_name VARCHAR2( 50 ) NOT NULL 42 | ); 43 | 44 | -- Create employee table 45 | CREATE TABLE employee ( 46 | empl_id NUMBER PRIMARY KEY, 47 | empl_name VARCHAR2( 50 ) NOT NULL, 48 | dept_id NUMBER NOT NULL, -- fk 49 | CONSTRAINT fk_employee_dept_id 50 | FOREIGN KEY( dept_id ) 51 | REFERENCES department( dept_id ) 52 | ON DELETE SET NULL 53 | ); 54 | 55 | -- Create works_on table 56 | CREATE TABLE works_on ( 57 | empl_id NUMBER NOT NULL, -- fk 58 | proj_id NUMBER NOT NULL, -- fk 59 | hours NUMBER NOT NULL, 60 | CONSTRAINT pk_works_on 61 | PRIMARY KEY ( empl_id, proj_id ), 62 | CONSTRAINT fk_works_on_empl_id 63 | FOREIGN KEY( empl_id ) 64 | REFERENCES employee( empl_id ) 65 | ON DELETE CASCADE, 66 | CONSTRAINT fk_works_on_proj_id 67 | FOREIGN KEY( proj_id ) 68 | REFERENCES project( proj_id ) 69 | ON DELETE CASCADE 70 | ); 71 | 72 | -- Insert data into department table 73 | INSERT INTO department ( dept_id, dept_name ) VALUES ( 10, 'Finance' ); 74 | INSERT INTO department ( dept_id, dept_name ) VALUES ( 14, 'R&D' ); 75 | 76 | -- Insert data into project table 77 | INSERT INTO project ( proj_id, proj_name ) VALUES ( 27, 'alpha' ); 78 | INSERT INTO project ( proj_id, proj_name ) VALUES ( 25, 'beta' ); 79 | INSERT INTO project ( proj_id, proj_name ) VALUES ( 22, 'gamma' ); 80 | INSERT INTO project ( proj_id, proj_name ) VALUES ( 26, 'pail' ); 81 | INSERT INTO project ( proj_id, proj_name ) VALUES ( 21, 'hill' ); 82 | 83 | -- Insert data into employee table 84 | INSERT INTO employee ( empl_id, empl_name, dept_id ) VALUES ( 1, 'Huey', 10 ); 85 | INSERT INTO employee ( empl_id, empl_name, dept_id ) VALUES ( 5, 'Dewey', 10 ); 86 | INSERT INTO employee ( empl_id, empl_name, dept_id ) VALUES ( 11, 'Louie', 10 ); 87 | INSERT INTO employee ( empl_id, empl_name, dept_id ) VALUES ( 2, 'Jack', 14 ); 88 | INSERT INTO employee ( empl_id, empl_name, dept_id ) VALUES ( 4, 'Jill', 14 ); 89 | 90 | -- Insert data into works_on table 91 | INSERT INTO works_on ( empl_id, proj_id, hours ) VALUES ( 1, 27, 4.5 ); 92 | INSERT INTO works_on ( empl_id, proj_id, hours ) VALUES ( 5, 25, 3 ); 93 | INSERT INTO works_on ( empl_id, proj_id, hours ) VALUES ( 11, 22, 7 ); 94 | INSERT INTO works_on ( empl_id, proj_id, hours ) VALUES ( 2, 26, 8 ); 95 | INSERT INTO works_on ( empl_id, proj_id, hours ) VALUES ( 4, 21, 9 ); 96 | 97 | -- Select all data from all tables 98 | SELECT * FROM department; 99 | SELECT * FROM project; 100 | SELECT * FROM employee; 101 | SELECT * FROM works_on; 102 | 103 | -- Drop the tables 104 | DROP TABLE works_on; 105 | DROP TABLE employee; 106 | DROP TABLE project; 107 | DROP TABLE department; -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/1. Assignment for 31-Jan-2024/2]_DDL & DML/school_schema.dbml: -------------------------------------------------------------------------------- 1 | // Use DBML to define your database structure 2 | // Docs: https://dbml.dbdiagram.io/docs 3 | // RUN: https://dbdiagram.io/d/65ba9143ac844320ae28b625 4 | 5 | Table students_grade { 6 | student_id integer [primary key] 7 | course_id varchar2 [primary key] 8 | student_grade varchar2 9 | } 10 | 11 | Table student { 12 | student_id integer [primary key] 13 | student_name varchar2 14 | } 15 | 16 | Table course { 17 | course_id varchar2 [primary key] 18 | faculty_id integer 19 | course_name varchar2 20 | } 21 | 22 | Table faculty { 23 | faculty_id integer [primary key] 24 | faculty_name varchar2 25 | faculty_phone varchar2 26 | } 27 | 28 | Ref: student.student_id < students_grade.student_id // many-to-one 29 | Ref: course.course_id < students_grade.course_id // many-to-one 30 | Ref: faculty.faculty_id < course.faculty_id // one-to-many 31 | ``` 32 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/2. Assignment for 02-Feb-2024/162338_Assignment_001.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/2. Assignment for 02-Feb-2024/162338_Assignment_001.xlsx -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/2. Assignment for 02-Feb-2024/162338_Assignment_002.sql: -------------------------------------------------------------------------------- 1 | /* 2 | QUESTIONS: 3 | Create an user name "assignmentUser" Connect to "assignmentUser". 4 | Create all entities/tables found 3nf of Assignment_001. 5 | While creating the tables ensure to consider all Constraints are used. 6 | */ 7 | 8 | --Assignment_002 2-FEB-24 9 | 10 | -- Create an user name "assignmentUser" 11 | alter session set "_ORACLE_SCRIPT"=true; 12 | CREATE USER assignmentUser IDENTIFIED BY 321654; 13 | 14 | ------------------------------------------------------ 15 | -- DCL: Grant Control 16 | ------------------------------------------------------ 17 | GRANT CREATE SESSION TO assignmentUser; 18 | GRANT CREATE TABLE TO assignmentUser; 19 | GRANT CREATE VIEW TO assignmentUser; 20 | GRANT CREATE ANY TRIGGER TO assignmentUser; 21 | GRANT CREATE ANY PROCEDURE TO assignmentUser; 22 | GRANT CREATE SYNONYM TO assignmentUser; 23 | GRANT ALL PRIVILEGES TO assignmentUser; 24 | GRANT CONNECT TO assignmentUser; 25 | GRANT RESOURCE TO assignmentUser; 26 | 27 | -- Grant all privileges to assignmentUser 28 | GRANT ALL PRIVILEGES TO assignmentUser; 29 | GRANT DBA TO assignmentUser; -- system-level privileges 30 | GRANT SELECT, INSERT, UPDATE, DELETE ON exampleTable TO assignmentUser; -- object-level privileges 31 | -- GRANT SELECT, UPDATE ON TO ; 32 | -- CREATE ROLE WITH SELECT, UPDATE ON ; 33 | -- GRANT TO ; 34 | -- REVOKE SELECT, UPDATE ON FROM ; 35 | -- REVOKE FROM ; 36 | 37 | -- dba_users display 38 | SELECT 39 | username, 40 | default_tablespace, 41 | profile, 42 | authentication_type 43 | FROM 44 | dba_users 45 | WHERE 46 | account_status = 'OPEN' 47 | ORDER BY 48 | username; 49 | 50 | -- drop user 51 | drop user assignmentUser; 52 | 53 | 54 | -- CREATE DB 55 | 56 | -- product_info 57 | CREATE TABLE product_info ( 58 | product_id NUMBER GENERATED BY DEFAULT AS IDENTITY 59 | START WITH 101 PRIMARY KEY, 60 | product_desc VARCHAR2( 50 ) NOT NULL, 61 | product_price NUMBER( 8, 2 ) NOT NULL, 62 | CONSTRAINT product_info_product_price_ck 63 | CHECK ( product_price > 0 ) 64 | ); 65 | 66 | -- customer_info 67 | CREATE TABLE customer_info ( 68 | customer_id NUMBER GENERATED BY DEFAULT AS IDENTITY 69 | START WITH 201 PRIMARY KEY, 70 | customer_name VARCHAR2( 50 ) NOT NULL, 71 | customer_state VARCHAR2( 50 ) NOT NULL 72 | ); 73 | 74 | -- order_info 75 | CREATE TABLE order_info ( 76 | order_id NUMBER GENERATED BY DEFAULT AS IDENTITY 77 | START WITH 301 PRIMARY KEY, 78 | order_date DATE NOT NULL, 79 | customer_id NUMBER NOT NULL, 80 | CONSTRAINT fk_order_info_customer_info 81 | FOREIGN KEY ( customer_id ) 82 | REFERENCES customer_info ( customer_id ) 83 | ON DELETE CASCADE 84 | ); 85 | 86 | -- order_Product 87 | CREATE TABLE order_Product ( 88 | product_id NUMBER NOT NULL, 89 | order_id NUMBER NOT NULL, 90 | quantity NUMBER NOT NULL DEFAULT 1, 91 | CONSTRAINT order_Product_quantity_ck 92 | CHECK ( quantity > 0 ), 93 | CONSTRAINT pk_order_Product 94 | PRIMARY KEY ( product_id, order_id ), 95 | CONSTRAINT fk_order_Product_product_info 96 | FOREIGN KEY ( product_id ) 97 | REFERENCES product_info ( product_id ) 98 | ON DELETE SET NULL, 99 | CONSTRAINT fk_order_Product_order_info 100 | FOREIGN KEY ( order_id ) 101 | REFERENCES order_info ( order_id ) 102 | ON DELETE SET NULL 103 | ); 104 | 105 | -- Select all data from all tables 106 | SELECT * FROM product_info; 107 | SELECT * FROM customer_info; 108 | SELECT * FROM order_info; 109 | SELECT * FROM order_Product; 110 | 111 | -- Drop the tables 112 | DROP TABLE order_Product; 113 | DROP TABLE order_info; 114 | DROP TABLE customer_info; 115 | DROP TABLE product_info; 116 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/2. Assignment for 02-Feb-2024/162338_Assignment_003.sql: -------------------------------------------------------------------------------- 1 | --Assignment_003 2-FEB-24 2 | -- ADD RECORDS: https://www.geeksengine.com/database/problem-solving/northwind-queries-part-2.php 3 | 4 | -- product_info 5 | -- product_id(pk) product_desc product_price 6 | -- 101 Laptop 1200.00 7 | -- 102 Smartphone 700.00 8 | -- 103 Headphones 50.00 9 | -- 104 Tablet 300.00 10 | -- 105 Printer 200.00 11 | 12 | -- Insert data into product_info table 13 | INSERT ALL 14 | INTO product_info (product_desc, product_price) VALUES ('Laptop', 1200.00) 15 | INTO product_info (product_desc, product_price) VALUES ('Smartphone', 700.00) 16 | INTO product_info (product_desc, product_price) VALUES ('Headphones', 50.00) 17 | INTO product_info (product_desc, product_price) VALUES ('Tablet', 300.00) 18 | INTO product_info (product_desc, product_price) VALUES ('Printer', 200.00) 19 | SELECT 1 FROM DUAL; 20 | 21 | -- customer_info 22 | -- customer_id(pk) customer_name customer_state 23 | -- 201 John Smith California 24 | -- 202 Alice Johnson New York 25 | -- 203 Bob Miller Texas 26 | -- 204 Emily Brown Florida 27 | -- 205 Daniel Kim Illinois 28 | 29 | -- Insert data into customer_info table 30 | INSERT ALL 31 | INTO customer_info (customer_name, customer_state) VALUES ('John Smith', 'California') 32 | INTO customer_info (customer_name, customer_state) VALUES ('Alice Johnson', 'New York') 33 | INTO customer_info (customer_name, customer_state) VALUES ('Bob Miller', 'Texas') 34 | INTO customer_info (customer_name, customer_state) VALUES ('Emily Brown', 'Florida') 35 | INTO customer_info (customer_name, customer_state) VALUES ('Daniel Kim', 'Illinois') 36 | SELECT 1 FROM DUAL; 37 | 38 | 39 | 40 | -- order_info 41 | -- order_id(pk) order_date customer_id(fk) 42 | -- 301 2024-02-01 201 43 | -- 302 2024-02-02 202 44 | -- 303 2024-02-03 203 45 | -- 304 2024-02-04 204 46 | -- 305 2024-02-05 205 47 | 48 | -- Insert data into order_info table 49 | INSERT ALL 50 | INTO order_info (order_date, customer_id) VALUES (TO_DATE('2024-02-01', 'YYYY-MM-DD'), 201) 51 | INTO order_info (order_date, customer_id) VALUES (TO_DATE('2024-02-02', 'YYYY-MM-DD'), 202) 52 | INTO order_info (order_date, customer_id) VALUES (TO_DATE('2024-02-03', 'YYYY-MM-DD'), 203) 53 | INTO order_info (order_date, customer_id) VALUES (TO_DATE('2024-02-04', 'YYYY-MM-DD'), 204) 54 | INTO order_info (order_date, customer_id) VALUES (TO_DATE('2024-02-05', 'YYYY-MM-DD'), 205) 55 | SELECT 1 FROM DUAL; 56 | 57 | 58 | -- order_Product 59 | -- product_id(fk) order_id(fk) quantity 60 | -- 101 301 2 61 | -- 103 301 1 62 | -- 102 302 3 63 | -- 105 303 1 64 | -- 104 304 2 65 | -- 101 305 1 66 | -- 103 305 2 67 | 68 | -- Insert data into order_Product table 69 | INSERT ALL 70 | INTO order_Product (product_id, order_id, quantity) VALUES (101, 301, 2) 71 | INTO order_Product (product_id, order_id, quantity) VALUES (103, 301, 1) 72 | INTO order_Product (product_id, order_id, quantity) VALUES (102, 302, 3) 73 | INTO order_Product (product_id, order_id, quantity) VALUES (105, 303, 1) 74 | INTO order_Product (product_id, order_id, quantity) VALUES (104, 304, 2) 75 | INTO order_Product (product_id, order_id, quantity) VALUES (101, 305, 1) 76 | INTO order_Product (product_id, order_id, quantity) VALUES (103, 305, 2) 77 | SELECT 1 FROM DUAL; 78 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/2. Assignment for 02-Feb-2024/162338_Assignment_004.sql: -------------------------------------------------------------------------------- 1 | --Assignment_004 2-FEB-24 2 | --SQL QUERIES 3 | 4 | -- 1. Select all products with a price greater than $100 5 | SELECT product_id, product_id 6 | FROM product_info 7 | WHERE product_price > 100; 8 | 9 | -- 2. Retrieve orders placed after '2024-02-02' //and also give the product_desc whith it's product_id 10 | SELECT * 11 | FROM order_info 12 | WHERE order_date > TO_DATE('2024-02-02', 'YYYY-MM-DD'); 13 | -- -- 14 | SELECT order_info.order_id, order_product.product_id, product_info.product_desc 15 | FROM order_info 16 | JOIN order_Product 17 | ON order_info.order_id = order_Product.order_id 18 | JOIN product_info 19 | ON order_Product.product_id = product_info.product_id 20 | WHERE order_date > TO_DATE('2024-02-02', 'YYYY-MM-DD'); 21 | 22 | 23 | -- 3. List customers from 'New York' 24 | SELECT customer_name 25 | FROM customer_info 26 | WHERE customer_state = 'New York'; 27 | 28 | -- 4. Show products and their quantities where quantity is not null 29 | SELECT product_id, quantity 30 | from order_Product 31 | WHERE quantity IS NOT NULL; 32 | 33 | -- 5. Retrieve orders placed by customers from 'California' 34 | SELECT * 35 | FROM customer_info 36 | WHERE customer_state = 'California'; 37 | -- -- 38 | SELECT * 39 | FROM product_info 40 | WHERE product_id IN ( 41 | SELECT product_id 42 | FROM order_Product 43 | WHERE order_id IN ( 44 | SELECT order_id 45 | FROM order_info 46 | WHERE customer_id IN ( 47 | SELECT customer_id 48 | FROM customer_info 49 | WHERE customer_state = 'California' 50 | ) 51 | ) 52 | ); 53 | 54 | -- 6. Find products with a price less than or equal to $200 and in stock 55 | SELECT * 56 | FROM product_info 57 | WHERE product_price <= 200; 58 | 59 | -- 7. Calculate the total quantity of products in all orders 60 | SELECT SUM(quantity) AS total_quantity 61 | FROM order_Product; 62 | 63 | -- 8. Display distinct product descriptions 64 | SELECT DISTINCT product_desc 65 | FROM product_info; 66 | 67 | -- 9. Find the average price of products 68 | SELECT AVG(product_price) AS average_price 69 | FROM product_info; 70 | 71 | -- 10. Show products and their quantities, replacing null quantities with 0 72 | SELECT product_id, NVL(quantity, 0) AS quantity 73 | FROM order_Product; 74 | 75 | -- 11. Retrieve the first 5 products in the Product_Info table 76 | SELECT * 77 | FROM product_info 78 | WHERE ROWNUM <= 5; 79 | 80 | -- 12. Display orders with quantities sorted in descending order: 81 | SELECT order_id, quantity 82 | FROM order_Product 83 | ORDER BY quantity DESC; 84 | -- -- 85 | SELECT order_id, quantity 86 | FROM order_Product 87 | FETCH FIRST 5 ROWS ONLY; 88 | 89 | -- 13. Retrieve products with descriptions containing 'Phone' 90 | SELECT product_id, product_desc 91 | FROM product_info 92 | WHERE product_desc LIKE '%Phone%'; 93 | 94 | -- 14. Find customers in 'California' or 'New York' 95 | SELECT customer_name, customer_state 96 | FROM customer_info 97 | WHERE customer_state IN ('California', 'New York'); 98 | 99 | -- 15. Show products with prices between $100 and $500 100 | SELECT product_id, product_desc, product_price 101 | FROM product_info 102 | WHERE product_price BETWEEN 100 AND 500; 103 | 104 | -- 16. List orders placed between '2024-02-02' and '2024-02-05' 105 | SELECT order_id, order_date 106 | FROM order_info 107 | WHERE order_date BETWEEN TO_DATE('2024-02-02', 'YYYY-MM-DD') AND TO_DATE('2024-02-05', 'YYYY-MM-DD'); 108 | 109 | -- 17. Retrieve orders with quantities not between 1 and 5 110 | SELECT order_id, quantity 111 | FROM order_Product 112 | WHERE quantity NOT BETWEEN 1 AND 5; 113 | 114 | -- 18. Display products with prices increased by 10%, handling null prices 115 | SELECT product_id, product_desc, 116 | CASE WHEN product_price IS NULL THEN NULL 117 | ELSE product_price * 1.1 118 | END AS increased_price 119 | FROM product_info; 120 | -- END: ed8c6549bwf9 121 | 122 | -- 19. Find the average quantity of products in orders 123 | SELECT AVG(quantity) AS average_quantity 124 | FROM order_Product; 125 | 126 | -- 20. Show orders with dates one week ahead of '2024-02-01' 127 | SELECT order_id, order_date 128 | FROM order_info 129 | WHERE order_date BETWEEN TO_DATE('2024-02-01', 'YYYY-MM-DD') AND TO_DATE('2024-02-01', 'YYYY-MM-DD') + 7; 130 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/2. Assignment for 02-Feb-2024/162338_Assignment_005.sql: -------------------------------------------------------------------------------- 1 | --Assignment_005 2-FEB-24 2 | --SQL QUERIES 3 | 4 | -- 21. List customers with names in uppercase 5 | SELECT UPPER(customer_name) AS customer_name 6 | FROM customer_info; 7 | 8 | -- 22. Retrieve products with descriptions starting with 'Lap' 9 | SELECT product_id, product_desc 10 | FROM product_info 11 | WHERE product_desc LIKE 'Lap%'; 12 | -- 23. Find customers with names ending in 'son' 13 | SELECT customer_name 14 | FROM customer_info 15 | WHERE customer_name LIKE '%son'; 16 | 17 | -- 24. Display orders placed on the last day of each month 18 | SELECT * 19 | FROM order_info 20 | WHERE EXTRACT(DAY FROM order_date + 1) = 1; 21 | -- using last_day function 22 | SELECT * 23 | FROM order_info 24 | WHERE order_date = LAST_DAY(order_date); 25 | 26 | -- 25. Show products with prices rounded to the nearest integer 27 | SELECT product_id, product_desc, ROUND(product_price) AS rounded_price 28 | FROM product_info; 29 | 30 | -- 26. Retrieve customers with states replaced by their first two characters 31 | SELECT customer_name, SUBSTR(customer_state, 1, 2) AS state 32 | FROM customer_info; 33 | 34 | -- 27. List orders with quantities multiplied by 2 35 | SELECT order_id, quantity * 2 AS multiplied_quantity 36 | FROM order_Product; -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/2. Assignment for 02-Feb-2024/normalization.txt: -------------------------------------------------------------------------------- 1 | for the example below we have one big table put the table in normalized form 1nf, 2nf, 3nf. 2 | 3 | OID = OrderID, 4 | O_Date = OrderDate, 5 | CID = CustomerID, 6 | C_Name = CustomerName, 7 | C_State = CustomerState, 8 | PID = ProductID, 9 | P_Desc = ProjectName, 10 | P_Price = ProductPrice, 11 | Qty = QuantityPurchased 12 | 13 | OID -> O_Date 14 | CID -> C_Name 15 | PID -> P_Desc 16 | PID -> P_Price 17 | OID -> CID 18 | CID -> C_State 19 | (PID, OID) -> Qty 20 | 21 | relations: 22 | OID -> (O_Date, CID) 23 | CID -> (C_Name, C_State) 24 | PID -> (P_Desc, P_Price) 25 | (OID, PID) -> Qty 26 | 27 | Candidate key: (OID, PID) 28 | (OID, PID) ->(OID, PID, O_Date, CID, C_Name, C_State, P_Desc, P_Price, Qty) 29 | 30 | 2nf: 31 | Candidate key: (OID, PID) 32 | pa -> npa 33 | OID -> CID, O_Date, C_Name, C_State 34 | PID -> P_Desc, P_Price 35 | (PID, OID) -> Qty 36 | 37 | TABLES for 2nf: 38 | Order(OID, CID, O_Date, C_Name, C_State) 39 | Product(PID, P_Desc, P_Price) 40 | OrderDetails(OID, PID, Qty) 41 | 42 | 43 | 3nf: 44 | npa -> npa 45 | CID -> (C_Name, C_State) 46 | 47 | TABLES for 3nf: 48 | Customer(CID_, C_Name, C_State) 49 | Product(PID_, P_Desc, P_Price) 50 | Order(OID_, CID*, O_Date) 51 | OrderDetails(_OID*, _PID*, Qty) 52 | 53 | 54 | Final Tables: 55 | Order-Product (OID*, PID*, Qty) 56 | Product_Info (PID, P_Desc, P_Price) 57 | Order_Info (OID, O_Date, CID*) 58 | Customer_Info (CID, C_Name, C_State) 59 | 60 | 61 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/2. Assignment for 02-Feb-2024/touch-assignment.sh: -------------------------------------------------------------------------------- 1 | # bash script to create 20 files with name 162338_Assignment_001.sql to 162338_Assignment_020.sql 2 | # Run bash ./touch-assignment.sh 3 | 4 | for i in {1..10} 5 | do 6 | touch 162338_Assignment_$(printf "%03d" $i).sql 7 | done -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/3. Assignment for 03-Feb-2024/Assignment_006.sql: -------------------------------------------------------------------------------- 1 | --Assignment_006 3-FEB-24 2 | -- CREATE DB 3 | 4 | -- Create below tables in assignmentUser 5 | -- Grade (SID*,CID*,Grade) 6 | -- Student (SID, S_name) 7 | -- Course (CID, C_name, FID*) 8 | -- Faculty (FID, Faculty, F_phone) 9 | 10 | 11 | -- Create student table 12 | CREATE TABLE student ( 13 | student_id NUMBER GENERATED BY DEFAULT AS IDENTITY 14 | START WITH 101 PRIMARY KEY, 15 | student_name VARCHAR2( 50 ) NOT NULL 16 | ); 17 | 18 | -- Create faculty table 19 | CREATE TABLE faculty ( 20 | faculty_id NUMBER GENERATED BY DEFAULT AS IDENTITY 21 | START WITH 201 PRIMARY KEY, 22 | faculty_name VARCHAR2( 50 ) NOT NULL, 23 | faculty_phone VARCHAR2( 20 ) NOT NULL 24 | ); 25 | 26 | -- Create course table 27 | CREATE TABLE course ( 28 | course_id NUMBER GENERATED BY DEFAULT AS IDENTITY 29 | START WITH 301 PRIMARY KEY, 30 | faculty_id NUMBER NOT NULL, -- fk 31 | course_name VARCHAR2( 50 ) NOT NULL, 32 | CONSTRAINT fk_course_faculty 33 | FOREIGN KEY( faculty_id ) 34 | REFERENCES faculty( faculty_id ) 35 | ON DELETE SET NULL 36 | ); 37 | 38 | -- Create students_grade table 39 | CREATE TABLE students_grade ( 40 | student_id NUMBER NOT NULL, -- fk 41 | course_id NUMBER NOT NULL, -- fk 42 | student_grade VARCHAR2( 2 ) NOT NULL, 43 | CONSTRAINT pk_students_grade 44 | PRIMARY KEY ( student_id, course_id ), 45 | CONSTRAINT fk_students_grade_student_id 46 | FOREIGN KEY( student_id ) 47 | REFERENCES student( student_id ) 48 | ON DELETE CASCADE, 49 | CONSTRAINT fk_students_grade_course_id 50 | FOREIGN KEY( course_id ) 51 | REFERENCES course( course_id ) 52 | ON DELETE CASCADE 53 | ); 54 | 55 | 56 | -- Select all data from all tables 57 | SELECT * FROM student; 58 | SELECT * FROM faculty; 59 | SELECT * FROM course; 60 | SELECT * FROM students_grade; 61 | 62 | -- Drop the tables 63 | DROP TABLE students_grade; 64 | DROP TABLE course; 65 | DROP TABLE faculty; 66 | DROP TABLE student; 67 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/3. Assignment for 03-Feb-2024/Assignment_007.sql: -------------------------------------------------------------------------------- 1 | --Assignment_007 3-FEB-24 2 | -- ADD RECORDS 3 | 4 | -- Student 5 | -- (student, student_name), 6 | -- (101, 'John Smith'), 7 | -- (102, 'Alice Johnson'), 8 | -- (103, 'Bob Miller'), 9 | -- (104, 'Emily Brown'), 10 | -- (105, 'Daniel Kim'), 11 | -- (106, 'Eva Martinez'), 12 | -- (107, 'Gary Wilson'), 13 | -- (108, 'Hannah Lee'), 14 | -- (109, 'Ian Turner'), 15 | -- (110, 'Jessica Hall'); 16 | 17 | -- Insert data into student table 18 | INSERT INTO student ( student_name ) VALUES ( 'John Smith' ); 19 | INSERT INTO student ( student_name ) VALUES ( 'Alice Johnson' ); 20 | INSERT INTO student ( student_name ) VALUES ( 'Bob Miller' ); 21 | INSERT INTO student ( student_name ) VALUES ( 'Emily Brown' ); 22 | INSERT INTO student ( student_name ) VALUES ( 'Daniel Kim' ); 23 | INSERT INTO student ( student_name ) VALUES ( 'Eva Martinez' ); 24 | INSERT INTO student ( student_name ) VALUES ( 'Gary Wilson' ); 25 | INSERT INTO student ( student_name ) VALUES ( 'Hannah Lee' ); 26 | INSERT INTO student ( student_name ) VALUES ( 'Ian Turner' ); 27 | INSERT INTO student ( student_name ) VALUES ( 'Jessica Hall' ); 28 | 29 | 30 | -- Faculty 31 | -- (faculty_id, faculty_name, faculty_phone), 32 | -- (201, 'Dr. Anderson', '555-1234'), 33 | -- (202, 'Prof. Davis', '555-5678'), 34 | -- (203, 'Dr. White', '555-9876'), 35 | -- (204, 'Prof. Harris', '555-4321'), 36 | -- (205, 'Dr. Robinson', '555-8765'), 37 | -- (206, 'Prof. Garcia', '555-2345'), 38 | -- (207, 'Dr. Baker', '555-6789'), 39 | -- (208, 'Prof. Murphy', '555-3456'), 40 | -- (209, 'Dr. Carter', '555-7890'), 41 | -- (210, 'Prof. Martin', '555-0123'); 42 | 43 | -- Insert data into faculty table 44 | INSERT INTO faculty ( faculty_name, faculty_phone ) VALUES ( 'Dr. Anderson', '555-1234' ); 45 | INSERT INTO faculty ( faculty_name, faculty_phone ) VALUES ( 'Prof. Davis', '555-5678' ); 46 | INSERT INTO faculty ( faculty_name, faculty_phone ) VALUES ( 'Dr. White', '555-9876' ); 47 | INSERT INTO faculty ( faculty_name, faculty_phone ) VALUES ( 'Prof. Harris', '555-4321' ); 48 | INSERT INTO faculty ( faculty_name, faculty_phone ) VALUES ( 'Dr. Robinson', '555-8765' ); 49 | INSERT INTO faculty ( faculty_name, faculty_phone ) VALUES ( 'Prof. Garcia', '555-2345' ); 50 | INSERT INTO faculty ( faculty_name, faculty_phone ) VALUES ( 'Dr. Baker', '555-6789' ); 51 | INSERT INTO faculty ( faculty_name, faculty_phone ) VALUES ( 'Prof. Murphy', '555-3456' ); 52 | INSERT INTO faculty ( faculty_name, faculty_phone ) VALUES ( 'Dr. Carter', '555-7890' ); 53 | INSERT INTO faculty ( faculty_name, faculty_phone ) VALUES ( 'Prof. Martin', '555-0123' ); 54 | 55 | 56 | -- Course 57 | -- (course_id, course_name, faculty_id), 58 | -- (301, 'Database Management', 201), 59 | -- (302, 'Programming Fundamentals', 202), 60 | -- (303, 'Data Structures', 203), 61 | -- (304, 'Web Development', 204), 62 | -- (305, 'Algorithms', 205), 63 | -- (306, 'Network Security', 206), 64 | -- (307, 'Artificial Intelligence', 207), 65 | -- (308, 'Software Engineering', 208), 66 | -- (309, 'Computer Graphics', 209), 67 | -- (310, 'Operating Systems', 210); 68 | 69 | -- Insert data into course table 70 | INSERT INTO course ( faculty_id, course_name ) VALUES ( 201, 'Database Management' ); 71 | INSERT INTO course ( faculty_id, course_name ) VALUES ( 202, 'Programming Fundamentals' ); 72 | INSERT INTO course ( faculty_id, course_name ) VALUES ( 203, 'Data Structures' ); 73 | INSERT INTO course ( faculty_id, course_name ) VALUES ( 204, 'Web Development' ); 74 | INSERT INTO course ( faculty_id, course_name ) VALUES ( 205, 'Algorithms' ); 75 | INSERT INTO course ( faculty_id, course_name ) VALUES ( 206, 'Network Security' ); 76 | INSERT INTO course ( faculty_id, course_name ) VALUES ( 207, 'Artificial Intelligence' ); 77 | INSERT INTO course ( faculty_id, course_name ) VALUES ( 208, 'Software Engineering' ); 78 | INSERT INTO course ( faculty_id, course_name ) VALUES ( 209, 'Computer Graphics' ); 79 | INSERT INTO course ( faculty_id, course_name ) VALUES ( 210, 'Operating Systems' ); 80 | 81 | 82 | -- Grade 83 | -- (student_id, course_id, grade), 84 | -- (101, 301, 'A'), 85 | -- (102, 302, 'B'), 86 | -- (103, 303, 'C'), 87 | -- (104, 304, 'A'), 88 | -- (105, 305, 'B'), 89 | -- (106, 306, 'A'), 90 | -- (107, 307, 'C'), 91 | -- (108, 308, 'B'), 92 | -- (109, 309, 'A'), 93 | -- (110, 310, 'C'); 94 | 95 | -- Insert data into students_grade table 96 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 101, 301, 'A' ); 97 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 102, 302, 'B' ); 98 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 103, 303, 'C' ); 99 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 104, 304, 'A' ); 100 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 105, 305, 'B' ); 101 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 106, 306, 'A' ); 102 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 107, 307, 'C' ); 103 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 108, 308, 'B' ); 104 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 109, 309, 'A' ); 105 | INSERT INTO students_grade ( student_id, course_id, student_grade ) VALUES ( 110, 310, 'C' ); 106 | 107 | -- Select all data from all tables 108 | SELECT * FROM student; 109 | SELECT * FROM faculty; 110 | SELECT * FROM course; 111 | SELECT * FROM students_grade; -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/3. Assignment for 03-Feb-2024/Assignment_008.sql: -------------------------------------------------------------------------------- 1 | --Assignment_008 3-FEB-24 2 | --SQL QUERIES 3 | 4 | -- 1. Select all students and their grades 5 | SELECT s.student_name, c.course_name, sg.student_grade 6 | FROM student s 7 | JOIN students_grade sg ON s.student_id = sg.student_id 8 | JOIN course c ON sg.course_id = c.course_id; 9 | -- can also use ROLEUP to show the average grade of each student. 10 | 11 | -- 2. List courses and their respective faculties 12 | SELECT c.course_name, f.faculty_name 13 | FROM course c 14 | JOIN faculty f ON c.faculty_id = f.faculty_id; 15 | 16 | -- 3. Display all grades for a specific course (e.g., "Database Management') 17 | SELECT s.student_name, sg.student_grade 18 | FROM student s 19 | JOIN students_grade sg ON s.student_id = sg.student_id 20 | JOIN course c ON sg.course_id = c.course_id 21 | WHERE c.course_name = 'Database Management'; 22 | 23 | -- 4. Show the average grade for each course 24 | SELECT c.course_name, AVG( CASE sg.student_grade 25 | WHEN 'A' THEN 4 26 | WHEN 'B' THEN 3 27 | WHEN 'C' THEN 2 28 | WHEN 'D' THEN 1 29 | ELSE 0 30 | END ) AS avg_grade 31 | FROM course c 32 | JOIN students_grade sg ON c.course_id = sg.course_id 33 | GROUP BY c.course_name; 34 | 35 | -- 5. List students and their grades for courses taught by a specific faculty (e.g., "Dr. Anderson') 36 | SELECT s.student_name, c.course_name, sg.student_grade 37 | FROM student s 38 | JOIN students_grade sg ON s.student_id = sg.student_id 39 | JOIN course c ON sg.course_id = c.course_id 40 | JOIN faculty f ON c.faculty_id = f.faculty_id 41 | WHERE f.faculty_name = 'Dr. Anderson'; 42 | 43 | -- 6. Display the highest grade in each course 44 | SELECT c.course_name, MAX( CASE sg.student_grade 45 | WHEN 'A' THEN 4 46 | WHEN 'B' THEN 3 47 | WHEN 'C' THEN 2 48 | WHEN 'D' THEN 1 49 | ELSE 0 50 | END ) AS max_grade 51 | FROM course c 52 | JOIN students_grade sg ON c.course_id = sg.course_id 53 | GROUP BY c.course_name; 54 | 55 | -- 7. Show the number of students in each course 56 | SELECT c.course_name, COUNT( sg.student_id ) AS num_students 57 | FROM course c 58 | JOIN students_grade sg ON c.course_id = sg.course_id 59 | GROUP BY c.course_name; 60 | 61 | -- 8. List courses with the number of students and average grade 62 | SELECT c.course_name, COUNT( sg.student_id ) AS num_students, AVG( CASE sg.student_grade 63 | WHEN 'A' THEN 4 64 | WHEN 'B' THEN 3 65 | WHEN 'C' THEN 2 66 | WHEN 'D' THEN 1 67 | ELSE 0 68 | END ) AS avg_grade 69 | FROM course c 70 | JOIN students_grade sg ON c.course_id = sg.course_id 71 | GROUP BY c.course_name; 72 | 73 | -- 9. Retrieve students who scored 'A' in any course 74 | SELECT s.student_name, c.course_name, sg.student_grade 75 | FROM student s 76 | JOIN students_grade sg ON s.student_id = sg.student_id 77 | JOIN course c ON sg.course_id = c.course_id 78 | WHERE sg.student_grade = 'A'; 79 | 80 | -- 10. Display courses with more than 2 students and average grade above 80 81 | SELECT c.course_name, COUNT( sg.student_id ) AS num_students, AVG( CASE sg.student_grade 82 | WHEN 'A' THEN 4 83 | WHEN 'B' THEN 3 84 | WHEN 'C' THEN 2 85 | WHEN 'D' THEN 1 86 | ELSE 0 87 | END ) AS avg_grade 88 | FROM course c 89 | JOIN students_grade sg ON c.course_id = sg.course_id 90 | GROUP BY c.course_name 91 | HAVING 92 | COUNT( sg.student_id ) > 2 93 | AND AVG( CASE sg.student_grade 94 | WHEN 'A' THEN 100 95 | WHEN 'B' THEN 90 96 | WHEN 'C' THEN 80 97 | WHEN 'D' THEN 70 98 | WHEN 'F' THEN 60 99 | 100 | ELSE 0 101 | END ) > 80; 102 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/3. Assignment for 03-Feb-2024/Assignment_009.sql: -------------------------------------------------------------------------------- 1 | --Assignment_0089 3-FEB-24 2 | --SQL QUERIES 3 | 4 | -- 1. For each question, provide the SQL query that answers the question. 5 | -- 2. Include comments in your queries to explain the purpose of each query. 6 | -- 3. Test your queries on the provided tables. 7 | -- 4. Submit the queries and the output for verification. 8 | 9 | 10 | -- DDL Level 1 Assignment : 11 | -- 1. Create a Table: 12 | -- - Create a table named 'Employee with columns: 'EmpID (Primary Key), 'EmpName`, `EmpSalary, and 'EmpDepartment. 13 | CREATE TABLE Employee ( 14 | EmpID INT PRIMARY KEY, 15 | EmpName VARCHAR(100), 16 | EmpSalary DECIMAL(10, 2), 17 | EmpDepartment VARCHAR(100) 18 | ); 19 | 20 | -- 2. Add a Column: 21 | -- - Alter the 'Employee table to add a new column named 'EmpAddress` of data type VARCHAR(100). 22 | ALTER TABLE Employee 23 | ADD EmpAddress VARCHAR(100); 24 | 25 | -- 3. Create an Index: 26 | -- - Create an Index named 'Idx_salary' on the 'EmpSalary column In the 'Employee table. 27 | CREATE INDEX Idx_salary 28 | ON Employee (EmpSalary); 29 | 30 | -- 4. Define a Primary Key: 31 | -- - Define 'EmpID` as the primary key for the 'Employee table. 32 | ALTER TABLE Employee 33 | ADD CONSTRAINT PK_Employee_EmpID PRIMARY KEY (EmpID); 34 | 35 | -- 5. Remove a Table: 36 | -- Drop the 'Employee table if it exists. 37 | -- DROP TABLE IF EXISTS Employee; -- ⚠️ oracle database does not support IF EXISTS clause for create as well as drop table statement. 38 | 39 | DECLARE 40 | table_exists NUMBER; 41 | BEGIN 42 | SELECT COUNT(*) INTO table_exists FROM user_tables WHERE table_name = 'Employee'; 43 | 44 | IF table_exists > 0 THEN 45 | EXECUTE IMMEDIATE 'DROP TABLE Employee'; 46 | DBMS_OUTPUT.PUT_LINE('Table dropped successfully.'); 47 | ELSE 48 | DBMS_OUTPUT.PUT_LINE('Table does not exist.'); 49 | END IF; 50 | END; 51 | / 52 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/3. Assignment for 03-Feb-2024/Assignment_010.sql: -------------------------------------------------------------------------------- 1 | --Assignment_010 3-FEB-24 2 | --SQL QUERIES 3 | 4 | -- DDL Level 2 5 | -- 1. Create a Sequence: - Create a sequence named 'emp_ld_seq` with a starting value of 100 and an Increment of 1. 6 | CREATE SEQUENCE emp_ld_seq 7 | START WITH 100 8 | INCREMENT BY 1; 9 | 10 | SELECT emp_ld_seq.NEXTVAL FROM dual; -- 101 11 | SELECT emp_ld_seq.NEXTVAL FROM dual; -- 102 12 | SELECT emp_ld_seq.NEXTVAL FROM dual; -- 103 13 | 14 | 15 | -- 2. Add a Foreign Key: - Create a table named 'Department with 16 | -- columns: 'DeptID' (Primary Key) and 'DeptName'. 17 | -- Alter the 'Employee table to add a foreign key 18 | -- constraint on the 'EmpDepartment column referencing the 'Department table. 19 | 20 | drop table Employee; 21 | drop table Department; 22 | CREATE TABLE Department( 23 | DeptID NUMBER(2) PRIMARY KEY, 24 | DeptName VARCHAR2(50) 25 | ); 26 | 27 | CREATE TABLE Employee( 28 | EmpID NUMBER(5) PRIMARY KEY, 29 | EmpName VARCHAR2(50), 30 | EmpDepartment NUMBER(2), 31 | EmpAddress VARCHAR2(100), 32 | EmpSalary NUMBER(10,2) 33 | ); 34 | 35 | ALTER TABLE Employee 36 | ADD CONSTRAINT fk_emp_dept 37 | FOREIGN KEY (EmpDepartment) 38 | REFERENCES Department(DeptID); 39 | 40 | 41 | -- 3. Modify Data Type: 42 | -- Modify the data type of the 'EmpSalary column in the 'Employee table to NUMBER(10,2). 43 | ALTER TABLE Employee 44 | MODIFY (EmpSalary NUMBER(10,2)); 45 | 46 | -- 4. Rename a Column: 47 | -- - Rename the column 'EmpAddress` in the 'Employee' table to 'EmpLocation'. 48 | ALTER TABLE Employee 49 | RENAME COLUMN EmpAddress TO EmpLocation; 50 | 51 | -- 5. Create a Unique Constraint: 52 | -- - Add a unique constraint named 'uniq_name` on the 'EmpName' column in the 'Employee table. 53 | ALTER TABLE Employee 54 | ADD CONSTRAINT uniq_name UNIQUE(EmpName); 55 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/4. Assignment for 10-Feb-2024/0. Oracle_Northwind_CreateUser.sql: -------------------------------------------------------------------------------- 1 | /* 2 | QUESTIONS: 3 | Create an user name "assignmentUser" Connect to "assignmentUser". 4 | Create all entities/tables found 3nf of Assignment_001. 5 | While creating the tables ensure to consider all Constraints are used. 6 | */ 7 | 8 | --Assignment_002 2-FEB-24 9 | 10 | -- Create an user name "assignmentUser" 11 | alter session set "_ORACLE_SCRIPT"=true; 12 | CREATE USER northwind_schema IDENTIFIED BY 321654; 13 | 14 | ------------------------------------------------------ 15 | -- DCL: Grant Control 16 | ------------------------------------------------------ 17 | GRANT CREATE SESSION TO northwind_schema; 18 | GRANT CREATE TABLE TO northwind_schema; 19 | GRANT CREATE VIEW TO northwind_schema; 20 | GRANT CREATE ANY TRIGGER TO northwind_schema; 21 | GRANT CREATE ANY PROCEDURE TO northwind_schema; 22 | GRANT CREATE SYNONYM TO northwind_schema; 23 | GRANT ALL PRIVILEGES TO northwind_schema; 24 | GRANT CONNECT TO northwind_schema; 25 | GRANT RESOURCE TO northwind_schema; 26 | 27 | -- Grant all privileges to northwind_schema 28 | GRANT ALL PRIVILEGES TO northwind_schema; 29 | GRANT DBA TO northwind_schema; -- system-level privileges 30 | -- GRANT SELECT, INSERT, UPDATE, DELETE ON exampleTable TO northwind_schema; -- object-level privileges 31 | 32 | -- dba_users display 33 | SELECT 34 | username, 35 | default_tablespace, 36 | profile, 37 | authentication_type 38 | FROM 39 | dba_users 40 | WHERE 41 | account_status = 'OPEN' 42 | ORDER BY 43 | username; 44 | 45 | -- drop user northwind_schema 46 | -- drop user northwind_schema; -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/4. Assignment for 10-Feb-2024/1. Oracle_Northwind_CreateObjects.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/4. Assignment for 10-Feb-2024/1. Oracle_Northwind_CreateObjects.sql -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/4. Assignment for 10-Feb-2024/3. Oracle_Northwind_DropTables.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE OrderDetails; 2 | DROP TABLE Orders; 3 | DROP TABLE CustomerCustomerDemo; 4 | DROP TABLE CustomerDemographics; 5 | DROP TABLE EmployeeTerritories; 6 | DROP TABLE Employees; 7 | DROP TABLE Customers; 8 | DROP TABLE Shippers; 9 | DROP TABLE Products; 10 | DROP TABLE Suppliers; 11 | DROP TABLE Categories; 12 | DROP TABLE Territories; 13 | DROP TABLE Region; 14 | 15 | 16 | SELECT * FROM Region; 17 | SELECT * FROM Territories; 18 | SELECT * FROM Categories; 19 | SELECT * FROM Suppliers; 20 | SELECT * FROM Products; 21 | SELECT * FROM Shippers; 22 | SELECT * FROM Customers; 23 | SELECT * FROM Employees; 24 | SELECT * FROM EmployeeTerritories; 25 | SELECT * FROM CustomerDemographics; 26 | SELECT * FROM CustomerCustomerDemo; 27 | SELECT * FROM Orders; 28 | SELECT * FROM OrderDetails; 29 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/4. Assignment for 10-Feb-2024/Assignment_Northwind Database_v_1_0.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/4. Assignment for 10-Feb-2024/Assignment_Northwind Database_v_1_0.pdf -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/4. Assignment for 10-Feb-2024/README.md: -------------------------------------------------------------------------------- 1 | # 🧩🪛🧬🧮 Schema 2 | ![image](https://github.com/Ayon-SSP/Ayon-SSP/assets/80549753/8cfb7ef3-6500-44fc-a060-fafdcf7e61f4) -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/5. Assignment for 12-Feb-2024/Assignment_12Feb2024.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/5. Assignment for 12-Feb-2024/Assignment_12Feb2024.pdf -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/6. Assignment for 14-Feb-2024/06.Assignment_14Feb2024.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/6. Assignment for 14-Feb-2024/06.Assignment_14Feb2024.pdf -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/6. Assignment for 14-Feb-2024/OUTPUT.md: -------------------------------------------------------------------------------- 1 | ![image](https://github.com/Ayon-SSP/SQL/assets/80549753/fdc11a0b-6e52-4ecd-aa2f-523ff8b843ee) 2 | 3 | ![image](https://github.com/Ayon-SSP/SQL/assets/80549753/c1266493-7aff-4416-9e98-bbfd217edc8d) 4 | 5 | ![image](https://github.com/Ayon-SSP/SQL/assets/80549753/566ef85c-7b5b-4848-a69d-8a45634b9618) 6 | 7 | ![image](https://github.com/Ayon-SSP/SQL/assets/80549753/3d31e81b-55eb-48af-a363-e967242b5200) 8 | 9 | ![image](https://github.com/Ayon-SSP/SQL/assets/80549753/894066de-f06d-4dab-b315-fbf1498d4e48) 10 | 11 | ![image](https://github.com/Ayon-SSP/SQL/assets/80549753/1b3d2579-22b2-400f-8410-fb1e534aa014) 12 | 13 | ![image](https://github.com/Ayon-SSP/SQL/assets/80549753/8b45e458-9cc8-4493-bd5c-d784c136d4cc) 14 | 15 | ![image](https://github.com/Ayon-SSP/SQL/assets/80549753/66f71941-cb28-4a1a-902c-ece38df88bbf) 16 | 17 | ![image](https://github.com/Ayon-SSP/SQL/assets/80549753/a8124a60-da3a-47c4-b686-0be89788b09b) 18 | 19 | ![image](https://github.com/Ayon-SSP/SQL/assets/80549753/de7dd5fe-387d-4b2a-95c6-80cb7b4cc5c9) 20 | 21 | ![image](https://github.com/Ayon-SSP/SQL/assets/80549753/40c1e502-dc86-4c3a-a6dd-8ada56320343) 22 | 23 | ![image](https://github.com/Ayon-SSP/SQL/assets/80549753/06a0b4ae-8122-43ea-a4b8-ef18f0ea0011) 24 | 25 | ![image](https://github.com/Ayon-SSP/SQL/assets/80549753/0acce611-082c-4afa-97f8-8fdfe0d73545) 26 | 27 | ![image](https://github.com/Ayon-SSP/SQL/assets/80549753/d1805d34-7868-454e-a94f-f7b170004aaa) 28 | 29 | ![image](https://github.com/Ayon-SSP/SQL/assets/80549753/b05f48b1-2e1f-4f86-a16a-1589927d2dd9) 30 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/7. Assignment for 21-Feb-2024/07.Assignment_21Feb2024.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/7. Assignment for 21-Feb-2024/07.Assignment_21Feb2024.pdf -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/assignments/README.md: -------------------------------------------------------------------------------- 1 | # 📝 Mastek Trainee Notes 2 | ```css 3 | Assignments: 4 | 1. Normalization Prac 5 | a. Normalization exercersie 1_31Jan24 6 | b. Normalization exercersie 2_31Jan24 7 | 2. DDL & DML 8 | a. 162338_nex1_31Jan24.sql 9 | b. 162338_nex2_31Jan24.sql 10 | 3. 20 Questions (exercise 1 and 2) 11 | a. 162338_hr_31Jan24.sql 12 | b. 162338_nex1_practice_31Jan24.sql 13 | c. 162338_nex2_practice1_31Jan24.sql 14 | ``` 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/notes-from-trainer/DAY2_25jan24.sql: -------------------------------------------------------------------------------- 1 | -- create product table - DDL 2 | create table products( 3 | pid varchar2(5) primary key, 4 | productname varchar(25) not null, 5 | unitPrice NUMERIC(7,2) not null 6 | ); 7 | 8 | -- TO ADD RECORDS / MANUPULATE THE DAA WE USE DML INSERT 9 | INSERT INTO PRODUCTS VALUES('p1001','Butter',10); 10 | INSERT INTO PRODUCTS VALUES('p1002','Bread',40); 11 | INSERT INTO PRODUCTS VALUES('p1003','Jam',20); 12 | INSERT INTO PRODUCTS VALUES('p1004','Maggie',20); 13 | INSERT INTO PRODUCTS VALUES('p1005','Sugar 1 Kg',45); 14 | INSERT INTO PRODUCTS VALUES('p1006','Rice 1 Kg',100); 15 | 16 | -- DQL DATA QUERY LANGUAGE USES SELECT STATEMENT 17 | select * from products; 18 | select pid,productname,unitprice from products where pid='P1001'; 19 | -- data in side the column is case-sensative 20 | select Pid,ProductName,UnitPrice from Products where Pid='p1001'; 21 | 22 | -- comment and uncomment cltr+/ 23 | --customers 24 | -- cid customername 25 | -- c1001 Amit Jha 26 | -- c1002 Amit Kumar 27 | -- c1003 Sumit Shah 28 | 29 | create table customers( 30 | cust_id varchar2(5) primary key, 31 | cust_name varchar(25) not null 32 | ); 33 | INSERT INTO customers values ('c1001','Amit Jha'); 34 | INSERT INTO customers values ('c1002','Amit Kumar'); 35 | INSERT INTO customers values ('c1003','Sumit Shah'); 36 | -- DQL 37 | select * from customers; 38 | select cust_id,cust_name from customers; 39 | 40 | --orders 41 | -- oderid orderdate cid 42 | -- o1001 12-Dec-23 c1001 43 | -- o1002 15-Dec-23 c1001 44 | -- o1003 12-Dec-23 c1002 45 | -- o1004 15-Dec-23 c1002 46 | -- o1005 12-Dec-23 c1003 47 | -- o1006 15-Dec-23 c1003 48 | 49 | create table orders( 50 | order_id varchar2(5) primary key, 51 | orderdate date not null, 52 | cust_id varchar2(5) references customers(cust_id) 53 | ); 54 | 55 | insert into orders values('o1001','12-Dec-23','c1001'); 56 | insert into orders values('o1002','15-Dec-23','c1001'); 57 | insert into orders values('o1003','12-Dec-23','c1002'); 58 | insert into orders values('o1004','15-Dec-23','c1002'); 59 | insert into orders values('o1005','12-Dec-23','c1003'); 60 | insert into orders values('o1006','15-Dec-23','c1003'); 61 | 62 | -- DQL 63 | select * from orders; 64 | 65 | --ordersdetails 66 | -- orderid pid qunatity 67 | -- o1001 p1001 1 68 | -- o1001 p1002 1 69 | -- o1002 p1003 1 70 | -- o1002 p1004 1 71 | -- o1003 p1001 1 72 | -- o1003 p1002 1 73 | -- o1004 p1003 1 74 | -- o1004 p1004 1 75 | -- o1005 p1001 1 76 | -- o1005 p1002 1 77 | -- o1006 p1003 1 78 | -- o1006 p1004 1 79 | -- o1006 p1005 1 80 | -- o1007 p1006 1 81 | 82 | create table orderdetails( 83 | order_id varchar2(5) references orders(order_id), 84 | pid varchar2(5) references products(pid), 85 | quantity numeric(3) not null, 86 | constraint pk_orderdetails primary key (order_id,pid) 87 | ) 88 | 89 | insert into orderdetails values('o1001','p1001',1); 90 | insert into orderdetails values('o1001','p1002',1); 91 | insert into orderdetails values('o1002','p1003',1); 92 | insert into orderdetails values('o1002','p1004',1); 93 | 94 | select * from orderdetails; 95 | -- below will give error due to the primary key constraint 96 | --insert into orderdetails values(null,'p1004',1); 97 | --insert into orderdetails values('o1002',null ,1); 98 | 99 | 100 | 101 | -- do not un comment its just for your reference 102 | --create table dummy( 103 | --order_id varchar2(5) references orders(order_id), 104 | --pid varchar2(5) references products(pid), 105 | --quantity numeric(3) not null 106 | --); 107 | -- 108 | --insert into dummy values(null,'p1004',1); 109 | --insert into dummy values('o1002',null ,1); 110 | -- 111 | --select * from dummy; 112 | 113 | --drop table dummy; 114 | --truncate table orderdetails; 115 | 116 | --create table dummy( 117 | --order_id varchar2(5) references orders(order_id) primary key, 118 | --pid varchar2(5) references products(pid) primary key, 119 | --quantity numeric(3) not null 120 | --); 121 | --Error report - 122 | --ORA-02260: table can have only one primary key 123 | --02260. 00000 - "table can have only one primary key" 124 | --*Cause: Self-evident. 125 | --*Action: Remove the extra primary key. 126 | -- explicit declartion of composit primary key 127 | -- constraint pk_orderdetails primary key (order_id,pid) 128 | commit; -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/notes-from-trainer/DAY3_29jan24.sql: -------------------------------------------------------------------------------- 1 | --create table person( 2 | -- name varchar2(25), 3 | -- dateOfBirth date 4 | --); 5 | --select * from person; 6 | -- 7 | --insert into person values(null,null); 8 | --insert into person values(null,'12-Dec-23'); 9 | --insert into person values('Sheldon',null); 10 | --insert into person values('Sheldon','12-dec-23'); 11 | -- 12 | ---- Data -> Valid not null unless we really don't know the value 13 | ---- WE want to ensure that name,date has a value its not null 14 | ----a. Drop table and recreate -- best option 15 | ----b. alter table 16 | --truncate table person; 17 | -- 18 | --alter table person 19 | --modify name varchar2(25) not null; 20 | -- 21 | --select * from person; 22 | -- 23 | --insert into person values(null,null); 24 | --insert into person values(null,'12-Dec-23'); 25 | --insert into person values('Sheldon',null); 26 | --insert into person values('Sheldon','12-dec-23'); 27 | -- 28 | ---- if dob is not know default '01-Jun-1975' 29 | --alter table person 30 | --modify dateofbirth date default '01-Jun-1975'; 31 | -- 32 | ---- DML Insert -> add new record 33 | ---- DML Update -> when you want to modify/change a value of a column 34 | --update person 35 | --set dateofbirth='01-Jun-1975' 36 | --where name='Sheldon'; 37 | -- 38 | --rollback ; 39 | --select * from person; 40 | --update person 41 | --set dateofbirth='01-Jun-1975' 42 | --where name='Sheldon' and dateofbirth is null; 43 | -- ######################### 44 | CREATE TABLE people( 45 | person_id NUMBER(3,0) primary key, 46 | persona_name varchar2(35) not null, 47 | dateOfBirth date default '01-Jun-1950' 48 | ); 49 | -- dml 50 | -- 1. In the order of creation 51 | -- People(perso_id, person_name,dateofbirth) 52 | insert into people values(1,'Sakshi War','01-Jan-1999'); 53 | insert into people values(2,'Yash Tripathi','01-Feb-1999'); 54 | insert into people values(3,'Pradyumna Thakare','01-Mar-1999'); 55 | insert into people values(4,'Gaurav Shelke','01-Apr-1999'); 56 | -- 2. Change the order of insertion the data 57 | -- People( person_name,dateofbirth,perso_id) 58 | insert into people 59 | (persona_name,dateofbirth,person_id) 60 | values('Ankita Vishnupurikar','01-May-1999',5); 61 | 62 | 63 | --create table test1( 64 | --nuid number(3,0), 65 | --uid numeric(2,0) 66 | --) 67 | --drop table test1; 68 | 69 | 70 | create table dept( 71 | deptno number(3) primary key, 72 | dname varchar2(25) not null 73 | ); 74 | 75 | CREATE TABLE emp( 76 | empno number(3) primary key, 77 | ename varchar2(50) not null, 78 | job varchar2(25) not null, 79 | hiredate date not null, 80 | sal number(7,2) check(sal>0), 81 | comm number(7,2), 82 | mgr number(3) , 83 | deptno number(3) references dept(deptno) 84 | ); 85 | --mgr number(3) REFERENCES emp(empno), 86 | -- alter table -> create foreignkey for mgr 87 | 88 | 89 | create table test1( 90 | pk_id number(2) primary key, 91 | uk_id number(2) unique 92 | ); 93 | select * from test1; 94 | INSERT INTO test1 VALUES (1,11); 95 | INSERT INTO test1 VALUES (2,null); 96 | --INSERT INTO test1 VALUES (null,12);--we get error for primary key 97 | INSERT INTO test1 VALUES (3,null); 98 | INSERT INTO test1 VALUES (4,null); 99 | 100 | select distinct uk_id,pk_id from test1 101 | 102 | 103 | drop table test1; 104 | --create table test1( 105 | --id number(3) primary key, 106 | --text 107 | --) 108 | 109 | 110 | create table test1( 111 | id number(3) not null, 112 | text varchar2(10) not null, 113 | primary key (id,text) 114 | ) 115 | 116 | INSERT INTO test1 VALUES (1,'text1'); 117 | INSERT INTO test1 VALUES (2,'text1'); 118 | select * from test1; 119 | INSERT INTO test1 VALUES (1,'text2'); 120 | INSERT INTO test1 VALUES (2,'text2'); 121 | -- reenter 122 | INSERT INTO test1 VALUES (1,'text1'); 123 | INSERT INTO test1 VALUES (2,'text1'); 124 | 125 | select * from orderdetails; 126 | commit; 127 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/notes-from-trainer/DAY4_30jan24_createuser.sql: -------------------------------------------------------------------------------- 1 | alter session set "_ORACLE_SCRIPT"=true; 2 | create user myuser identified by root; 3 | 4 | --############ creating user on oracle instance for custom schema 5 | alter session set "_ORACLE_SCRIPT"=true; 6 | -- Create user 7 | create user myuser IDENTIFIED by root; 8 | 9 | SELECT 10 | username, 11 | default_tablespace, 12 | profile, 13 | authentication_type 14 | FROM 15 | dba_users 16 | WHERE 17 | account_status = 'OPEN' 18 | ORDER BY 19 | username; 20 | -- ################################################################ 21 | -- DCL: Grant Control 22 | -- ################################################################ 23 | grant create session to myuser; 24 | grant create table to myuser; 25 | grant create view to myuser; 26 | grant create any trigger to myuser; 27 | grant create any procedure to myuser; 28 | grant create SEQUENCE to myuser; 29 | grant create SYNONYM to myuser; 30 | grant all PRIVILEGES to myuser; 31 | grant connect to myuser; 32 | grant RESOURCE to myuser; 33 | grant dba to myuser; 34 | -- 35 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/notes-from-trainer/Day2_NormalizationtoDDL_25JAN24.sql: -------------------------------------------------------------------------------- 1 | -- create product table - DDL 2 | create table products( 3 | pid varchar2(5) primary key, 4 | productname varchar(25) not null, 5 | unitPrice NUMERIC(7,2) not null 6 | ); 7 | create table customers( 8 | cust_id varchar2(5) primary key, 9 | cust_name varchar(25) not null 10 | ); 11 | create table orders( 12 | order_id varchar2(5) primary key, 13 | orderdate date not null, 14 | cust_id varchar2(5) references customers(cust_id) 15 | ); 16 | create table orderdetails( 17 | order_id varchar2(5) references orders(order_id), 18 | pid varchar2(5) references products(pid), 19 | quantity numeric(3) not null, 20 | constraint pk_orderdetails primary key (order_id,pid) 21 | ) 22 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/Oracle Notes/2]_Traner_notes/work_with_shree.sql: -------------------------------------------------------------------------------- 1 | -- create product table - DDL 2 | create table products( 3 | pid varchar2(5) primary key, 4 | productname varchar(25) not null, 5 | unitPrice NUMERIC(7,2) not null 6 | ); 7 | 8 | -- TO ADD RECORDS / MANUPULATE THE DAA WE USE DML INSERT 9 | INSERT INTO PRODUCTS VALUES('p1001','Butter',10); 10 | INSERT INTO PRODUCTS VALUES('p1002','Bread',40); 11 | INSERT INTO PRODUCTS VALUES('p1003','Jam',20); 12 | INSERT INTO PRODUCTS VALUES('p1004','Maggie',20); 13 | INSERT INTO PRODUCTS VALUES('p1005','Sugar 1 Kg',45); 14 | INSERT INTO PRODUCTS VALUES('p1006','Rice 1 Kg',100); 15 | 16 | -- DQL DATA QUERY LANGUAGE USES SELECT STATEMENT 17 | select * from products; 18 | select pid,productname,unitprice from products where pid='P1001'; 19 | -- data in side the column is case-sensative 20 | select Pid,ProductName,UnitPrice from Products where Pid='p1001'; 21 | 22 | -- comment and uncomment cltr+/ 23 | --customers 24 | -- cid customername 25 | -- c1001 Amit Jha 26 | -- c1002 Amit Kumar 27 | -- c1003 Sumit Shah 28 | 29 | create table customers( 30 | cust_id varchar2(5) primary key, 31 | cust_name varchar(25) not null 32 | ); 33 | INSERT INTO customers values ('c1001','Amit Jha'); 34 | INSERT INTO customers values ('c1002','Amit Kumar'); 35 | INSERT INTO customers values ('c1003','Sumit Shah'); 36 | -- DQL 37 | select * from customers; 38 | select cust_id,cust_name from customers; 39 | 40 | --orders 41 | -- oderid orderdate cid 42 | -- o1001 12-Dec-23 c1001 43 | -- o1002 15-Dec-23 c1001 44 | -- o1003 12-Dec-23 c1002 45 | -- o1004 15-Dec-23 c1002 46 | -- o1005 12-Dec-23 c1003 47 | -- o1006 15-Dec-23 c1003 48 | 49 | create table orders( 50 | order_id varchar2(5) primary key, 51 | orderdate date not null, 52 | cust_id varchar2(5) references customers(cust_id) 53 | ); 54 | 55 | insert into orders values('o1001','12-Dec-23','c1001'); 56 | insert into orders values('o1002','15-Dec-23','c1001'); 57 | insert into orders values('o1003','12-Dec-23','c1002'); 58 | insert into orders values('o1004','15-Dec-23','c1002'); 59 | insert into orders values('o1005','12-Dec-23','c1003'); 60 | insert into orders values('o1006','15-Dec-23','c1003'); 61 | 62 | -- DQL 63 | select * from orders; 64 | 65 | --ordersdetails 66 | -- orderid pid qunatity 67 | -- o1001 p1001 1 68 | -- o1001 p1002 1 69 | -- o1002 p1003 1 70 | -- o1002 p1004 1 71 | -- o1003 p1001 1 72 | -- o1003 p1002 1 73 | -- o1004 p1003 1 74 | -- o1004 p1004 1 75 | -- o1005 p1001 1 76 | -- o1005 p1002 1 77 | -- o1006 p1003 1 78 | -- o1006 p1004 1 79 | -- o1006 p1005 1 80 | -- o1007 p1006 1 81 | 82 | create table orderdetails( 83 | order_id varchar2(5) references orders(order_id), 84 | pid varchar2(5) references products(pid), 85 | quantity numeric(3) not null, 86 | constraint pk_orderdetails primary key (order_id,pid) 87 | ) 88 | 89 | insert into orderdetails values('o1001','p1001',1); 90 | insert into orderdetails values('o1001','p1002',1); 91 | insert into orderdetails values('o1002','p1003',1); 92 | insert into orderdetails values('o1002','p1004',1); 93 | 94 | select * from orderdetails; 95 | 96 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/PL-SQL/README.md: -------------------------------------------------------------------------------- 1 | # PL/SQL 2 | > Resources and notes on PL/SQL (Oracle). [Link](https://www.oracletutorial.com/plsql-tutorial/) to the tutorial. 3 | 4 | - Once you submit a PL/SQL block to the Oracle Database server, the PL/SQL engine collaborates with the SQL engine to compile and execute the code. PL/SQL engine runs the procedural elements while the SQL engine processes the SQL statements. 5 | 6 | 7 | # 🏃‍♂️Complete PL/SQL Revision 8 | ```sql 9 | 10 | ``` -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/PL-SQL/SQL Developer/PlayGroundSQL.sql: -------------------------------------------------------------------------------- 1 | SET SERVEROUTPUT ON; 2 | DECLARE 3 | v_test VARCHAR2(20) := 'Hello World'; 4 | BEGIN 5 | dbms_output.put_line(v_test); 6 | END; 7 | 8 | -- write a plsql code to display the 1 to 10 numbers 9 | -- SET SERVEROUTPUT ON; 10 | -- DECLARE 11 | -- v_test NUMBER := 1; 12 | -- BEGIN 13 | -- WHILE v_test <= 10 LOOP 14 | -- dbms_output.put_line(v_test); 15 | -- v_test := v_test + 1; 16 | -- END LOOP; 17 | -- END; 18 | 19 | -- SELECT * FROM tab; 20 | 21 | 22 | -- write sql query to create employee table create and insert some random data. 23 | CREATE TABLE employee ( 24 | emp_id NUMBER, 25 | emp_name VARCHAR2(20), 26 | emp_salary NUMBER, 27 | emp_dept VARCHAR2(20) 28 | ); 29 | 30 | INSERT INTO employee VALUES (1, 'John', 10000, 'IT'); 31 | INSERT INTO employee VALUES (2, 'Smith', 20000, 'IT'); 32 | INSERT INTO employee VALUES (3, 'Raj', 30000, 'IT'); 33 | INSERT INTO employee VALUES (4, 'Rahul', 40000, 'IT'); 34 | INSERT INTO employee VALUES (5, 'Ramesh', 50000, 'IT'); 35 | INSERT INTO employee VALUES (6, 'Rajesh', 60000, 'IT'); 36 | 37 | SELECT * FROM employee; 38 | DROP TABLE employee; 39 | 40 | 41 | 42 | CREATE OR REPLACE TRIGGER check_salary 43 | BEFORE INSERT ON employees 44 | FOR EACH ROW 45 | BEGIN 46 | IF :NEW.salary < 30000 THEN 47 | RAISE_APPLICATION_ERROR(-20001, 'Salary must be at least 30000.'); 48 | END IF; 49 | END; 50 | / 51 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/PL-SQL/plsql-package.sql: -------------------------------------------------------------------------------- 1 | -- PL/SQL Packages 2 | /* 3 | - packages are logical groups of related pl/sql object'-- Select rows from a Table 4 | - packages are named pl/sql blocks || they are permanently stored in the schema's. and can be referenced or reused by your program. 5 | 6 | Packages contains: 7 | - Stored Procedures & functions 8 | - cursers 9 | - variables 10 | - Collections 11 | - records 12 | 13 | 14 | Package Architecture: 15 | - Package Specification(Header): 16 | - declatation of all the element's (publically available/can be accessed by other packages) 17 | - declare public items can access only the declaration of the package like pak_name.funk or pak_name.var 18 | - Package Body (Implementation): 19 | 20 | 21 | Package state: 22 | If the package specification has at least one variable, constant, or cursor, the package is stateful; or else it is stateless. 23 | */ 24 | 25 | -- Syntax of Package specification && package body 26 | CREATE [OR REPLACE] PACKAGE [schema_name.] 27 | IS | AS 28 | declarations; 29 | END []; 30 | 31 | CREATE [OR REPLACE] PACKAGE BODY [schema_name.] 32 | IS | AS 33 | declarations 34 | implementations; 35 | [BEGIN 36 | EXCEPTION] 37 | END []; 38 | 39 | 40 | -- Example 1: 41 | CREATE OR REPLACE PACKAGE order_mgmt AS 42 | gc_shipped_status CONSTANT VARCHAR(10) := 'Shipped'; 43 | gc_pending_status CONSTANT VARCHAR(10) := 'Pending'; 44 | gc_canceled_status CONSTANT VARCHAR(10) := 'Canceled'; 45 | 46 | -- cursor that returns the order detail 47 | CURSOR g_cur_order(p_order_id NUMBER) AS 48 | SELECT 49 | customer_id, 50 | status, 51 | salesman_id, 52 | order_date, 53 | item_id, 54 | product_name, 55 | quantity, 56 | unit_price 57 | FROM order_items 58 | INNER JOIN orders USING (order_id) 59 | INNER JOIN products USING (product_id) 60 | WHERE order_id = p_order_id; 61 | 62 | -- get net value of a order 63 | FUNCTION get_net_value( 64 | p_order_id NUMBER 65 | ) RETURN NUMBER; 66 | 67 | -- Get net value by customer 68 | FUNCTION get_net_value_by_customer( 69 | p_customer_id NUMBER, 70 | p_year NUMBER 71 | ) RETURN NUMBER; 72 | 73 | PROCEDURE update_order_status( 74 | p_order_id NUMBER, 75 | p_status VARCHAR2 76 | ); 77 | 78 | TYPE order_rec IS RECORD( 79 | customer_id orders.customer_id%TYPE, 80 | status orders.status%TYPE, 81 | salesman_id orders.salesman_id%TYPE, 82 | order_date orders.order_date%TYPE, 83 | ); 84 | END order_mgmt; 85 | / 86 | 87 | 88 | 89 | CREATE OR REPLACE PACKAGE BODY order_mgmt AS 90 | -- both the functions are independent of each other 91 | -- get net value of a order 92 | FUNCTION get_net_value( 93 | p_order_id NUMBER 94 | ) RETURN NUMBER 95 | IS 96 | ln_net_value NUMBER 97 | BEGIN 98 | SELECT SUM(unit_price * quantity) INTO ln_net_value 99 | FROM order_items 100 | WHERE order_id = p_order_id; 101 | 102 | RETURN p_order_id; 103 | 104 | EXCEPTION 105 | WHEN no_data_found THEN 106 | DBMS_OUTPUT.PUT_LINE( SQLERRM ); 107 | END get_net_value; 108 | 109 | -- Get net value by customer 110 | FUNCTION get_net_value_by_customer( 111 | p_customer_id NUMBER, 112 | p_year NUMBER 113 | ) RETURN NUMBER 114 | IS 115 | ln_net_value NUMBER 116 | BEGIN 117 | SELECT SUM(quantity * unit_price) 118 | INTO ln_net_value 119 | FROM order_items 120 | INNER JOIN orders USING (order_id) 121 | WHERE extract(YEAR FROM order_date) = p_year 122 | AND customer_id = p_customer_id 123 | AND status = gc_shipped_status; 124 | RETURN ln_net_value; 125 | EXCEPTION 126 | WHEN no_data_found THEN 127 | DBMS_OUTPUT.PUT_LINE( SQLERRM ); 128 | END get_net_value_by_customer; 129 | END order_mgmt; 130 | / 131 | 132 | SELECT 133 | order_mgmt.get_net_value_by_customer(1,2017) sales 134 | FROM dual; 135 | 136 | 137 | 138 | 139 | 140 | 141 | -- Example 2: 142 | CREATE TABLE new_superheroes ( 143 | f_name VARCHAR2(50), 144 | l_name VARCHAR2(50) 145 | ); 146 | -- Package Specification 147 | CREATE OR REPLACE PACKAGE pkg_foo IS 148 | FUNCTION prnt_strng RETURN VARCHAR2; 149 | PROCEDURE proc_superhero(f_name VARCHAR2, l_name VARCHAR2); 150 | END pkg_foo; 151 | / 152 | 153 | --Package Body 154 | CREATE OR REPLACE PACKAGE BODY pkg_foo IS 155 | --Function Implementation 156 | FUNCTION prnt_strng RETURN VARCHAR2 IS 157 | BEGIN 158 | RETURN 'foo.com'; 159 | END prnt_strng; 160 | 161 | --Procedure Implementation 162 | PROCEDURE proc_superhero(f_name VARCHAR2, l_name VARCHAR2) IS 163 | BEGIN 164 | INSERT INTO new_superheroes (f_name, l_name) VALUES(f_name, l_name); 165 | END; 166 | 167 | END pkg_foo; 168 | / 169 | 170 | --Package Calling Function 171 | BEGIN 172 | -- create the table new_superheroes 173 | DBMS_OUTPUT.PUT_LINE (pkg_foo.prnt_strng); 174 | pkg_foo.proc_superhero('Clark', 'Kent'); 175 | 176 | END; 177 | 178 | SELECT * FROM new_superheroes; 179 | 180 | 181 | 182 | 183 | 184 | 185 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/PL-SQL/plsql-tutorial-plsql-record.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/PL-SQL/plsql-tutorial-plsql-record.sql -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/PLSQL-Revision.txt: -------------------------------------------------------------------------------- 1 | Q. tell some non-anonymous blocks. 2 | Q. `/` and `edit` does. 3 | Q. SQL does not have the BOOLEAN data type. True 4 | 5 | 1. Basics: dataTypes, var declaration, conditions, case, loops, continue. 6 | 2. Record(rowtype) & INTO 7 | 3. Exception handelers. 8 | 4. Cursors 9 | 5. Procedures, Functions & Packages. 10 | 6. Triggers 11 | 7. Collections 12 | 13 | 14 | - famous for querying and updating data. 15 | - overcome sql limitations. 16 | - PL/SQL engine can only be installed in oracle database server or ad tool Oracle Forms. 17 | - submit[PL/SQL] block -> Oracle DB server [plsql engine collaborates with sql engine to compile] 18 | 19 | Anonymous Block(SQL*Plus(command-line interface for executing)): 20 | [Declaration] (declaretion[type, cursors]) 21 | {excutable block} 22 | [exception] 23 | - block without a name is an anonymous block (not saved in the oracle database.)(one line use)(used in testing) 24 | rest other blocks like procedure, function, triggers are saved in db. 25 | - you can nest exec blocks 26 | - SET SERVEROUTPUT ON; || DBMS_OUTPUT.put_line("hello"); 27 | - / will start execution. / will exec previous command. 28 | - if want to edit the code use `edit` .buf file(recent runned script). 29 | Non-anonymous blocks like with triggers, porcedures, functions. 30 | 31 | DataType(SQL datatypes & there own datatypes): (scalar[Number, Boolean, Character, Datetime.], composite[record & collection]): 32 | BOOLEAN: datavalues True, False, Null 33 | - varchar2(n) vs Char(n) 34 | - '' == NULL 35 | 36 | Variables: 37 | var_name datatype [NOT NULL] {[DEFAULT 'val'] [:= val]}; 38 | - good practice use %TYPE && %ROWTYPE while declatation. 39 | - constant 40 | 41 | DECLARE 42 | -- l_counter NUMBER NOT NULL DEFAULT 5 := 0; -- ERROR 43 | l_counter NUMBER NOT NULL DEFAULT 5; 44 | -- l_counter2 VARCHAR2(10) NOT NULL; 45 | l_counter2 VARCHAR2(10) NOT NULL DEFAULT 'A'; 46 | BEGIN 47 | l_counter := 5; 48 | -- l_counter2 := ''; -- a variable declared NOT NULL must have an initialization assignment(v_variable VARCHAR2(50) NOT NULL := 'Initial Value';) 49 | -- NULL; 50 | END; 51 | / 52 | 53 | Conditions: 54 | -- if elsif else 55 | IF condition THEN 56 | to_do; 57 | ELSIF condition THEN 58 | to_do; 59 | ELSE to_do; 60 | END IF; 61 | 62 | -- case 2types(simple case statement, searched case) 63 | - PL/SQL CASE statement vs. CASE expression 64 | val := 65 | CASE selector 66 | WHEN selector_val THEN 67 | to_do; 68 | [WHEN selector_val THEN 69 | to_do;] 70 | [ELSE to_do;] 71 | END CASE; 72 | 73 | -- GOTO: First, you cannot use a GOTO statement to transfer control into an IF, CASE or LOOP statement, the same for the sub-block. 74 | 75 | 76 | GOTO label_name; 77 | <>; 78 | 79 | -- NULL: '' equals to NULL 80 | - null statement 'NULL;' 81 | - <> 82 | NULL; --error will occur if no NULL: 83 | 84 | 85 | 86 | -- LOOPS 87 | <> LOOP 88 | to_do; 89 | EXIT WHEN condition; or EXIT; 90 | END LOOP lable; 91 | 92 | 93 | -- INTO: ERRORS are'NO_DATA_FOUND' 'TOO_MANY_ROWS' 94 | - x, y, z INTO a, b -> not enough values 95 | - x, y INTO a, b, c -> too many values 96 | - IF datatypes are different of corresponding LHS and RHS then numeric or value error 97 | 98 | SELECT 99 | name, 100 | first_name, 101 | last_name 102 | INTO 103 | {l_customer_name, 104 | l_contact_first_name, 105 | l_contact_last_name / towtype} 106 | FROM 107 | customers 108 | INNER JOIN contacts USING( customer_id ) 109 | WHERE 110 | customer_id = 100; 111 | 112 | -- RecordType: PL/SQL has three types of records: table-based, cursor-based, and programmer-defined. 113 | user_rec_type user%ROWTPE 114 | TYPE join_rec_type RECORD ( 115 | uid id%type, 116 | uname name%type 117 | ); 118 | user_rec user_rec_type; 119 | user_rec.uid = xxx; 120 | 121 | select uid, uname INTO user_rec...; 122 | FETCH user_rec INTO uid, uname; 123 | - update: 124 | update user 125 | set ROW = user_rec 126 | where condition; 127 | - insert: 128 | insert into tbl_user values user_rec; 129 | - nested record 130 | 131 | 132 | 133 | 134 | Exception: TODO: only notes topic done. 135 | - A user-defined exception must be assigned error_code(EXCEPTION_INIT) 136 | - integer that ranges from -20,999 to -20,000 137 | - reraise exception 138 | declaration: 139 | - unhandled exception: Note that an unhandled exception stops the execution of the block. 140 | not_found exception; 141 | pragma exception_init(name, err_code); 142 | 143 | if xxx then raise not_found; 144 | raise_application_error(errcode, 'new exception no optional(definition)) 145 | raise errname 146 | exception -- if you don't do this it will stop the program 147 | when not_found then 148 | dbms... 149 | when other then 150 | dbms SQLCODE 151 | 152 | -- collection 153 | TYPE t_num IS TABLE OF NUMBER; 154 | TYPE t_num IS VARRAY(2) OF NUMBER; 155 | TYPE t_num IS TABLE OF NUMBER INDEX BY NUMBER; 156 | 157 | -- functions & procedures 158 | create or replace procedure/funck pro_name( 159 | parms 160 | ) return number 161 | is/as 162 | declarations 163 | begin 164 | return number 165 | end; 166 | 167 | 168 | -- curssors: 169 | cursor c is 170 | query; 171 | open c; 172 | fetch c into rec; 173 | 174 | close c; 175 | ---- 176 | type c_type is ref cursor return rowtype; 177 | c c_type; 178 | 179 | open c for 180 | statement; 181 | CURSOR C IS 182 | STATEM 183 | FOR UPDATE; -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/PROJECT/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/B]_PL-SQL (Oracle)/PROJECT/README.md -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/README.md: -------------------------------------------------------------------------------- 1 | # 🛢️ PL/SQL 2 | 3 | ## Overview 4 | - PL/SQL is Oracle's proprietary extension of SQL. 5 | - Used Server-side programming language. 6 | 7 | ## ➡️ [sql-style-guide](https://handbook.gitlab.com/handbook/business-technology/data-team/platform/sql-style-guide/) 8 | ## 📐 Setting Up PL/SQL on Linux Ubuntu/WSL 9 | > REFER TO [SETUP.md](SETUP.md) or [`Setting Up PL/SQL on Linux Ubuntu/WSL`](https://dev.to/ayon_ssp/setting-up-plsql-on-linux-ubuntuwsl-376d) FOR SETUP. 10 | 11 | ## 📚 Resources & 📑 Notes: [`my chatGPT`](https://chat.openai.com/c/6b158380-a1a0-47dc-82c8-89b1d013a655) 12 | > before we start, let's see the basic structure of PL/SQL block. 13 | Example 1: 14 | ```sql 15 | DECLARE 16 | qty_on_hand NUMBER(5); 17 | BEGIN 18 | SELECT quantity INTO qty_on_hand FROM inventory 19 | WHERE product = 'TENNIS RACKET' 20 | FOR UPDATE OF quantity; 21 | IF qty_on_hand > 0 THEN -- check quantity 22 | UPDATE inventory SET quantity = quantity - 1 23 | WHERE product = 'TENNIS RACKET'; 24 | INSERT INTO purchase_record 25 | VALUES ('Tennis racket purchased', SYSDATE); 26 | ELSE 27 | INSERT INTO purchase_record 28 | VALUES ('Out of tennis rackets', SYSDATE); 29 | END IF; 30 | COMMIT; 31 | END; 32 | ``` 33 | Example 2: 34 | ```sql 35 | -- available online in file 'sample1' 36 | DECLARE 37 | x NUMBER := 100; 38 | BEGIN 39 | FOR i IN 1..10 LOOP 40 | IF MOD(i,2) = 0 THEN -- i is even 41 | INSERT INTO temp VALUES (i, x, 'i is even'); 42 | ELSE 43 | INSERT INTO temp VALUES (i, x, 'i is odd'); 44 | END IF; 45 | x := x + 100; 46 | END LOOP; 47 | COMMIT; 48 | END; 49 | -- look 👇 50 | ``` 51 | 52 | Output Table 53 | ``` 54 | SQL> SELECT * FROM temp 55 | ORDER BY col1; 56 | 57 | NUM_COL1 NUM_COL2 CHAR_COL 58 | -------- -------- --------- 59 | 1 100 i is odd 60 | 2 200 i is even 61 | 3 300 i is odd 62 | 4 400 i is even 63 | 5 500 i is odd 64 | 6 600 i is even 65 | 7 700 i is odd 66 | 8 800 i is even 67 | 9 900 i is odd 68 | 10 1000 i is even 69 | ``` 70 | 71 | > More examples: [PL/SQL samps](https://docs.oracle.com/cd/B10500_01/appdev.920/a96624/a_samps.htm) 72 | 73 | 74 | ### **PL/SQL Block Types**: 75 | - Anonymous Block 76 | - Named Block 77 | - Subprogram 78 | ```sql 79 | DECLARE 80 | Declaration Statements(Variables, Constants, Cursors, User-defined exceptions, Records, Collections, Subprograms, etc.) - Optional 81 | BEGIN 82 | Executable Statements(Queries, DML, DDL, Transaction Control Statements, etc.) - Mandatory 83 | EXCEPTION 84 | Exception Handling Statements(Handling Exceptions, Propagating Exceptions, etc.) - Optional 85 | END; 86 | ``` 87 | 88 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/SQL-Revision.txt: -------------------------------------------------------------------------------- 1 | create user ayon identified by 321654; 2 | grant all privileges to ayon; 3 | 4 | - Oracle FETCH 5 | 6 | 7 | -- complete query. 8 | SELECT 9 | column_name AS alias_name 10 | COUNT(*), SUM(), AVG(), MIN(), MAX(), LENGTH(), 11 | ROUND(), UCASE(), LCASE(), MID(), NOW(), FORMAT()... 12 | DISTINCT column_name, 13 | FROM table_name 14 | JOIN table_name ON table_name.column_name = table_name.column_name 15 | LEFT JOIN table_name ON table_name.column_name = table_name.column_name 16 | RIGHT JOIN table_name ON table_name.column_name = table_name.column_name 17 | FULL JOIN table_name ON table_name.column_name = table_name.column_name 18 | CROSS JOIN table_name 19 | INNER JOIN table_name ON table_name.column_name = table_name.column_name 20 | NATURAL JOIN table_name 21 | UNION 22 | UNION ALL 23 | INTERSECT 24 | EXCEPT 25 | WHERE column_name > 10 26 | AND column_name IS NOT NULL 27 | AND column_name IN (value1, value2, value3) 28 | OR column_name BETWEEN value1 AND value2 29 | OR column_name LIKE 'value%' 30 | OR column_name IN/NOT IN (SELECT column_name FROM table_name WHERE column_name = value) 31 | AND column_name ALL/ANY/SOME/EXISTS (SELECT column_name FROM table_name WHERE column_name = value) 32 | AND column_name = value 33 | 34 | GROUP BY 35 | column_name 36 | HAVING 37 | SUM(column_name) > 10 38 | ORDER BY 39 | column_name DESC 40 | column_name ASC 41 | OFFSET 10 ROWS 42 | FETCH NEXT 10 ROWS ONLY; 43 | 44 | Joins. 45 | 46 | 47 | 48 | 49 | WITH view_name AS (query). 50 | 51 | CONSTRAINT fk_locations_countries 52 | FOREIGN KEY( country_id ) 53 | REFERENCES countries( country_id ) 54 | ON DELETE CASCADE 55 | CONSTRAINT pk_locations 56 | PRIMARY KEY ( location_id ) 57 | 58 | 59 | 60 | id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY START WITH 10 INCREMENT BY 10, 61 | 62 | 63 | Oracle-grouping 64 | 65 | ref: common-notes.sql 66 | 67 | 68 | -------------------------------------------------------------------------------- /B]_PL-SQL (Oracle)/social_media.sql: -------------------------------------------------------------------------------- 1 | -- * Mastek Intern (ORACLE) Notes: https://notepad.pw/oraclesql_jan24 2 | 3 | /* 4 | +----------------+ +----------------+ +---------------+ 5 | | products | | customers | | orders | 6 | +----------------+ +----------------+ +---------------+ 7 | | prod_id (PK) | | cust_id (PK) | | order_id (PK) | 8 | | product_name | | cust_name | | order_date | 9 | | unit_price | +----------------+ | cust_id (FK) | 10 | +----------------+ +---------------+ 11 | 12 | +-------------------+ 13 | | orderdetails | 14 | +-------------------+ 15 | | order_id (FK, PK) | 16 | | prod_id (FK, PK) | 17 | | quantity | 18 | +-------------------+ 19 | 20 | 21 | */ 22 | 23 | --products 24 | -- PRIMARY KEY (prod_id) 25 | -- prod_id productname unitprice 26 | -- p1001 Butter 10 27 | -- p1002 Bread 40 28 | -- p1003 Jam 20 29 | -- p1004 Maggie 20 30 | -- p1005 Sugar 1 Kg 45 31 | -- p1006 Rice 1 Kg 100 32 | 33 | --customers 34 | -- cust_id customername 35 | -- c1001 Amit Jha 36 | -- c1002 Amit Kumar 37 | -- c1003 Sumit Shah 38 | 39 | --orders 40 | -- oderid orderdate cust_id 41 | -- o1001 12-Dec-23 c1001 42 | -- o1002 15-Dec-23 c1001 43 | -- o1003 12-Dec-23 c1002 44 | -- o1004 15-Dec-23 c1002 45 | -- o1005 12-Dec-23 c1003 46 | -- o1006 15-Dec-23 c1003 47 | 48 | --orderdetails 49 | -- orderid prod_id qunatity 50 | -- o1001 p1001 1 51 | -- o1001 p1002 1 52 | -- o1002 p1003 1 53 | -- o1002 p1004 1 54 | -- o1003 p1001 1 55 | -- o1003 p1002 1 56 | -- o1004 p1003 1 57 | -- o1004 p1004 1 58 | -- o1005 p1001 1 59 | -- o1005 p1002 1 60 | -- o1006 p1003 1 61 | -- o1006 p1004 1 62 | -- o1006 p1005 1 63 | -- o1007 p1006 1 64 | 65 | -- product table 66 | DROP TABLE products; 67 | 68 | CREATE TABLE products( 69 | prod_id VARCHAR2(5) PRIMARY KEY, 70 | product_name VARCHAR2(25) NOT NULL, 71 | unit_price NUMERIC(7, 2) NOT NULL 72 | ); 73 | 74 | INSERT INTO products VALUES('p1001', 'Butter',10); 75 | INSERT INTO products VALUES ('p1002', 'Bread', 40); 76 | INSERT INTO products VALUES ('p1003','Jam', 20); 77 | INSERT INTO products VALUES ('p1004', 'Maggie', 20); 78 | INSERT INTO products VALUES ('p1005', 'Sugar 1 Kg',45); 79 | INSERT INTO products VALUES ('p1006', 'Rice 1 Kg',100); 80 | 81 | SELECT * FROM products; 82 | 83 | 84 | -- customer table 85 | DROP TABLE customers; 86 | 87 | CREATE TABLE customers( 88 | cust_id VARCHAR2(5) PRIMARY KEY, 89 | cust_name VARCHAR(25) NOT NULL 90 | ); 91 | 92 | INSERT INTO customers VALUES('c1001', 'Amit Jha'); 93 | INSERT INTO customers VALUES('c1002', 'Amit Kumar'); 94 | INSERT INTO customers VALUES('c1003', 'Sumit Sha'); 95 | 96 | SELECT * FROM customers; 97 | 98 | 99 | 100 | -- orders table 101 | DROP TABLE orders; 102 | 103 | CREATE TABLE orders( 104 | order_id VARCHAR2(5) PRIMARY KEY, 105 | order_date DATE NOT NULL, 106 | cust_id VARCHAR2(5) REFERENCES customers(cust_id) 107 | ); 108 | 109 | INSERT INTO orders VALUES('o1001', '12-Dec-23', 'c1001'); 110 | INSERT INTO orders VALUES('o1002', '15-Dec-23', 'c1001'); 111 | INSERT INTO orders VALUES('o1003', '12-Dec-23', 'c1002'); 112 | INSERT INTO orders VALUES('o1004', '15-Dec-23', 'c1002'); 113 | INSERT INTO orders VALUES('o1005', '12-Dec-23', 'c1003'); 114 | INSERT INTO orders VALUES('o1006', '15-Dec-23', 'c1003'); 115 | 116 | SELECT * FROM orders; 117 | 118 | 119 | -- orderdetails table 120 | -- customer.cust_id (1-N) orders.cust_id 121 | 122 | DROP TABLE orderdetails; 123 | 124 | CREATE TABLE orderdetails( 125 | order_id VARCHAR2(5) REFERENCES orders(order_id), 126 | prod_id VARCHAR2(5) REFERENCES products(prod_id), 127 | quantity NUMERIC(7, 2) NOT NULL, 128 | CONSTRAINT pk_orderdetails PRIMARY KEY (order_id, prod_id) -- composite primary key 129 | ); 130 | 131 | INSERT INTO orderdetails VALUES('o1001', 'p1001', 1); 132 | INSERT INTO orderdetails VALUES('o1001', 'p1002', 1); 133 | INSERT INTO orderdetails VALUES('o1002', 'p1003', 1); 134 | INSERT INTO orderdetails VALUES('o1002', 'p1004', 1); 135 | INSERT INTO orderdetails VALUES('o1003', 'p1001', 1); 136 | INSERT INTO orderdetails VALUES('o1003', 'p1002', 1); 137 | INSERT INTO orderdetails VALUES('o1004', 'p1003', 1); 138 | INSERT INTO orderdetails VALUES('o1004', 'p1004', 1); 139 | INSERT INTO orderdetails VALUES('o1005', 'p1001', 1); 140 | INSERT INTO orderdetails VALUES('o1005', 'p1002', 1); 141 | INSERT INTO orderdetails VALUES('o1006', 'p1003', 1); 142 | INSERT INTO orderdetails VALUES('o1006', 'p1004', 1); 143 | INSERT INTO orderdetails VALUES('o1006', 'p1005', 1); 144 | -- INSERT INTO orderdetails VALUES('o1007', 'p1006', 1); -- not pk in order table; 145 | -- INSERT INTO orderdetails VALUES('o1001', 'p1001', 1); 146 | 147 | SELECT * FROM orderdetails; 148 | 149 | 150 | 151 | 152 | 153 | 154 | -- CREATE TABLE orders( 155 | -- order_id VARCHAR2(5) REFERENCES orders(order_id), 156 | -- prod_id varchar2(5) REFERENCES products(prod_id), 157 | -- customer_id VARCHAR2(5), 158 | -- order_date DATE NOT NULL, 159 | 160 | -- -- cust_id VARCHAR2(5) NOT NULL, 161 | -- -- order_date DATE NOT NULL, 162 | -- -- order_amount NUMERIC(7, 2) NOT NULL, 163 | -- -- FOREIGN KEY (cust_id) REFERENCES customers(cust_id) 164 | -- ); 165 | 166 | /* 167 | * for Primary and foreign KEYS 168 | ON DELETE SET NULL 169 | ON DELETE CASCADE 170 | */ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 AYON 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Database 🛢️ 2 | ## All 🧢 My LeetCode & HackerRank SQL 🗃️ Solutions. 3 | ![LeetCodeSql](Res/LeetCodeSql.jpg) 4 | ![HackerRankSql](Res/HackerRankSql.jpg) 5 | -------------------------------------------------------------------------------- /Res/HackerRankSql.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/Res/HackerRankSql.jpg -------------------------------------------------------------------------------- /Res/LeetCodeSql.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayon-SSP/SQL/9b247f025e21a058fa3aa7e9c3ab81cf0f6d96c3/Res/LeetCodeSql.jpg -------------------------------------------------------------------------------- /common-notes.sql: -------------------------------------------------------------------------------- 1 | create table table_name( 2 | colname data_type constrent; 3 | ) 4 | 5 | Constraint: 6 | 1. NOT NULL 7 | 2. UNIQUE 8 | 3. PRIMARY KEY 9 | 4. FOREIGN KEY 10 | 5. CHECK 11 | 6. DEFAULT 12 | 7. CREATE INDEX 13 | 14 | 15 | -- insertion order is maintained 16 | insert into table_name (col1, col2, col3); 17 | 18 | 19 | 20 | 21 | -- column 22 | alter table table_name 23 | add column new_col_name data_tupe; 24 | -- drop column col_name; 25 | -- drop column (col_name, col_name2); 26 | -- alter column column_name new_datatype; 27 | -- rename column old_name to new_colname; 28 | 29 | alter table table_name 30 | add/drop/enable/disable constraint constraint_name 31 | ... 32 | -- default 33 | ALTER TABLE table_name 34 | ALTER COLUMN column_name SET DEFAULT new_default_value; 35 | 36 | -- table name 37 | alter table table_name 38 | rename to new_table_name; 39 | 40 | -- keys 41 | alter table table_name 42 | add constraint pk_constraint_name 43 | add ( 44 | column_name `data_type` constraints, 45 | column_name `data_type` constraints, 46 | ); 47 | primary key (column_name); 48 | -- add constraint fk_constraint_name 49 | foreign key (column_name) references reference_table(ref_column); 50 | -- drop constraint pk_constraint_name; 51 | -- drop constraint (pk_constraint_name, fk_constraint_name); 52 | 53 | 54 | rename old_table to new_table; 55 | 56 | Drop table_name; 57 | = 58 | database 59 | table 60 | view 61 | user 62 | index 63 | proceger 64 | 65 | truncate table table_name; 66 | 67 | TRUNCATE TABLE table_name 68 | CASCADE; 69 | 70 | 71 | comment on table table_name is 'This is a prat of online shopint project'; 72 | 73 | 74 | 75 | 76 | 77 | on delete set NULL 78 | on delete cascade 79 | --------------------------------------------------------------------------------