{"id":27939464,"url":"https://github.com/kanadshee-18/sql_in_one_go","last_synced_at":"2025-05-07T09:54:21.628Z","repository":{"id":291367016,"uuid":"976643730","full_name":"KanadShee-18/SQl_IN_ONE_GO","owner":"KanadShee-18","description":"🐬A repo to revise SQL in one go. 🧑‍💻","archived":false,"fork":false,"pushed_at":"2025-05-04T06:21:30.000Z","size":5952,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-04T07:23:23.661Z","etag":null,"topics":["mysql","sql"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/KanadShee-18.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-05-02T13:35:31.000Z","updated_at":"2025-05-04T06:21:33.000Z","dependencies_parsed_at":"2025-05-04T07:23:27.337Z","dependency_job_id":"7702011b-8a2d-4de3-834e-55ecb97a0097","html_url":"https://github.com/KanadShee-18/SQl_IN_ONE_GO","commit_stats":null,"previous_names":["kanadshee-18/sql_in_one_go"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KanadShee-18%2FSQl_IN_ONE_GO","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KanadShee-18%2FSQl_IN_ONE_GO/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KanadShee-18%2FSQl_IN_ONE_GO/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KanadShee-18%2FSQl_IN_ONE_GO/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/KanadShee-18","download_url":"https://codeload.github.com/KanadShee-18/SQl_IN_ONE_GO/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252856424,"owners_count":21814853,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["mysql","sql"],"created_at":"2025-05-07T09:54:20.832Z","updated_at":"2025-05-07T09:54:21.609Z","avatar_url":"https://github.com/KanadShee-18.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"```sql\n-------------- SQL ---------------\n\n\n-- Creating table in database\nCREATE TABLE student (\n    id INT PRIMARY KEY,\n    name VARCHAR(50),\n    age INT NOT NULL\n);\n\n-- Inserting values in a table/schema\nINSERT INTO student VALUES(1, \"Kanad\", 23);\nINSERT INTO student VALUES(2, \"Sudip\", 25);\n\n-- Show all data from a table\nSELECT * FROM student;\n\n/*\nTypes of SQL commands:\n---------------------\n\nDDL (Data Definition Language): create, alter, rename, truncate and drop\nDQL (Data Query Language): select\nDML (Data Manipulation Language): insert, update, delete\nDCL (Data Control Language): grant and revoke permissions to users\nTCL (Transaction Control Language): start transaction, commit, rollback (advanced)\n*/\n\n/*\nDatabase Related Queries:\n------------------------\nCREATE DATABASE db_name;\nCREATE DATABASE IF NOT EXISTS db_name;\n\nDROP DATABASE db_name;\nDROP DATABASE IF EXISTS db_name;\n\nSHOW DATABASES;\nSHOW TABLES;\n*/\n\nCREATE DATABASE IF NOT EXISTS college;\nDROP DATABASE IF EXISTS company;\n\nSHOW DATABASES;\nSHOW TABLES;\n\n/*\nTable Related Queries:\n----------------------\n1. create\nCREATE TABLE table_name (\n    column_name1 dataype constraint,\n    column_name2 dataype constraint,\n);\n*/\n\nCREATE TABLE student(\n    id INT PRIMARY KEY, -- not null and unique\n    name VARCHAR(50)\n);\n\n-- 2. Select and view all columns\n-- SELECT * FROM table_name;\n\nSELECT * FROM student;\n\n/*\n3. Insert\nINSERT INTO table_name(column1, column2)\nVALUES\n(col1_val1, col2_val1),\n(col1_val2, col2_val2);\n*/\n-- For multiple value we run this query\nINSERT INTO student (id, name)\nVALUES\n(1, \"Kanad\"),\n(2, \"Sudip\"),\n(3, \"Koushik\");\n\n-- For single value\nINSERT INTO student VALUES(4, \"Soumya\");\n\n/*\n---------------------------------------------------\nPractice Question:\nQs: Create a database for your company named 'xyz'.\n    -\u003e Create a table inside this DB to store \n    employee info(id, name, salary)\n    -\u003e Add following information into the DB:\n        1, \"adam\", 25000\n        2, \"bob\", 30000\n        3, \"casey\", 40000\n    -\u003e Select and view all your table data.\n---------------------------------------------------\n*/\nCREATE DATABASE IF NOT EXISTS xyz;\nUSE xyz;\n-- Ans 1: Creating table\nCREATE TABLE employees_info(\n    id INT PRIMARY KEY,\n    name VARCHAR(100),\n    salary INT\n);\n\n-- Ans 2: inerting data into that table\nINSERT INTO employees_info (id, name, salary)\nVALUES\n(1, \"adam\", 25000),\n(2, \"bob\", 30000),\n(3, \"casey\", 40000);\n\n-- Ans 3: showing data from a table\nSELECT * FROM employees_info;\n\n\n/*\nKEYS:\n\n1. Primary Key:\n---------------\n-\u003e It is a column (or a set of columns) in a table that uniquely identifies each row. (a unique id).\n-\u003e There can be only 1 Primary Key and it should be NOT NULL.\n\n\n2. Foreign Key:\n---------------\n-\u003e A foreign key is a column (or a set of columns) in a table that refers to the primary key in an another table.\n-\u003e There can be multiple foreign keys.\n-\u003e Foreign keys can have duplicate and null values.\n\n\n--- CONSTRAINTS ---\n\n1. NOT NULL (columns cannot have a null value) col1 int NOT NULL\n2. UNIQUE (all values in column are different) col2 int UNIQUE\n3. PRIMARY KEY ()\n*/\n\nUSE college;\n\nCREATE TABLE temp1(\n    id INT UNIQUE\n);\n\nINSERT INTO temp1 VALUES(101); -- this will run fine\nINSERT INTO temp1 VALUES(101); -- but here this will give error as duplicate entry 101. \n\nSELECT * FROM temp1;\n\nCREATE TABLE temp2(\n    id INT UNIQUE,\n    name VARCHAR(50) NOT NULL,\n    age INT\n);\n\nINSERT INTO temp2 VALUES(1, \"Kanad\", 23);\nINSERT INTO temp2(id, age) VALUES(2, 25); -- error: field 'name' doesn't have a default value.\nINSERT INTO temp2(id, name) VALUES(2, \"Sudip\"); -- this will run fine as age is not necessary.\n\n/*\n-\u003e Ways to define Primary Key:\n*/\n\n-- First syntax:\nCREATE TABLE temp3(\n    id INT PRIMARY KEY,\n    name VARCHAR(50),\n    age INT,\n    city VARCHAR(30)\n);\n\n-- Second syntax:\nCREATE TABLE temp3(\n    id INT,\n    name VARCHAR(50),\n    age INT,\n    city VARCHAR(30),\n    PRIMARY KEY (id)\n);\n\n-- Third syntax: (combination as primary key)\n\nCREATE TABLE temp3(\n    id INT,\n    name VARCHAR(50),\n    age INT,\n    city VARCHAR(30),\n    PRIMARY KEY (id, name) -- id or name can be duplciate but (id, name) combination can't\n);\n\n/*\n--- FOREIGN KEY ---\n-\u003e Prevent action that would detroy links between tables\n\n*/\nCREATE TABLE customer (\n    id INT PRIMARY KEY,\n    name VARCHAR(50),\n);\nCREATE TABLE buying_items(\n    cust_id int,\n    FOREIGN KEY (cust_id) REFERENCES customer(id)\n);\n\n/*\n--- DEFAULT ---\n-\u003e sets the default value of a column\n= salary INT DEFAULT 20000\n*/\n\nCREATE TABLE emp (\n    id INT,\n    salary INT DEFAULT 25000\n);\n\nINSERT INTO emp(id) VALUES(2154); -- here salary is not mandatory\nSELECT * FROM emp; -- this will show one row with | 2154 | 25000 |\n\n/*\n--- CHECK ---\n-\u003e It can limit the values allowed in a column\n*/\n\nCREATE TABLE newTab (\n    age INT CHECK (age \u003e= 18)\n);\n\nINSERT INTO newtab VALUES(17); -- this shows check constraint is violated\nINSERT INTO newtab VALUES(18); -- this one will run fine \n\nSELECT * FROM newtab;\n\n-- One more way to use CHECK:\nCREATE TABLE city (\n    id INT PRIMARY KEY,\n    city VARCHAR(50),\n    age INT,\n    CONSTRAINT age_check CHECK (age \u003e= 18 AND city=\"Delhi\")\n);\n\nINSERT INTO city VALUES(1, \"Mumbai\", 21); -- age_check violated\nINSERT INTO city VALUES(1, \"Delhi\", 17); -- age_check violated\nINSERT INTO city VALUES(1, \"delhi\", 27); -- runs fine\nINSERT INTO city VALUES(2, \"Delhi\", 23); -- runs fine\nINSERT INTO city VALUES(3, \"DELHI\", 23); -- runs fine\nINSERT INTO city VALUES(4, \"dElHI\", 23); -- runs fine\n\n\n\n\n\n-------------------- Part 1 ------------------------\n\nUSE college;\n\nCREATE TABLE student (\n    rollNo INT PRIMARY KEY,\n    name VARCHAR(50),\n    marks INT NOT NULL,\n    grade VARCHAR(1),\n    city VARCHAR(20)\n);\n\nINSERT INTO student\n(rollNo, name, marks, grade, city)\nVALUES\n(101, \"anil\", 78, \"C\", \"Pune\"),\n(102, \"bhumika\", 93, \"A\", \"Mumbai\"),\n(103, \"chetan\", 85, \"B\", \"Mumbai\"),\n(104, \"dhruv\", 96, \"A\", \"Delhi\"),\n(105, \"emanuel\", 12, \"F\", \"Delhi\"),\n(106, \"farah\", 82, \"B\", \"Delhi\");\n\nSELECT * FROM student;\n\n/*\n------- SELECT in detail -----------\n*/\n\n-- Basic: SELECT col1, col2 FROM table_name;\nSELECT name, marks FROM student; -- this will show name and marks in table\nSELECT city FROM student; -- show all cities\nSELECT DISTINCT city FROM student; -- shows all distinct city (for this: Pune, Mumbai, Delhi)\n\n/*\n---------- WHERE Clause ------------\n-\u003e to define some conditions\nSYNTAX:\n    SELECT col1, col2 FROM table_name\n    WHERE condition;\n*/\n\nSELECT * FROM student WHERE marks \u003e 80; -- showing 4 rows\nSELECT * FROM student WHERE city = \"Mumbai\"; -- showing 2 results\nSELECT * FROM student WHERE (city = \"Delhi\" AND grade = \"A\"); -- showing one result\n\n/*\n-------------- OPERATORS --------------\n\n=\u003e While using \"WHERE\", we use a lot of operators\n\n1. Arithmetic Operators: +, -, *, /, %\n2. Comparison Operators: =, !=, \u003e, \u003e=, \u003c, \u003c=\n3. Logical Operators: AND, OR, NOT, IN, BETWEEN, ALL, LIKE, ANY\n4. Bitwise Operators: \u0026(bitwise AND), | (bitwise OR)\n*/\n\nSELECT * FROM student WHERE (marks \u003e 80+10 AND grade = \"A\"); -- showing 2 result\nSELECT * FROM student WHERE (marks % 2 = 0 AND grade = \"A\"); -- showing 1 result\nSELECT * FROM student WHERE (marks % 2 = 0 OR grade = \"A\"); -- showing 5 result\nSELECT * FROM student WHERE marks BETWEEN 80 AND 90; -- showing 2 result (it includes 80 and 90)\nSELECT * FROM student WHERE city IN (\"Delhi\", \"Kolkata\", \"Mumbai\", \"Hyderabad\"); -- showing 5 result\nSELECT * FROM student WHERE city NOT IN (\"Delhi\", \"Kolkata\", \"Mumbai\", \"Hyderabad\"); -- showing 1 result\n\n\n/*\n---------- LIMIT Clause -------------\n=\u003e Sets an upper limit on number of (tuples) rows to be returned\nSYNTAX:\n    SELECT col1, col2 FROM table_name\n    LIMIT number;\n*/\n\nSELECT * FROM student LIMIT 2; -- shows 2 rows\nSELECT * FROM student WHERE marks \u003e 75 LIMIT 10; -- shows 5 rows\n\n\n/*\n---------- ORDER BY Clause -------------\n=\u003e To sort results in ASC(ascending) or DESC (descending) order\nSYNTAX:\n    SELECT col1, col2 FROM table_name\n    ORDER BY col_name(s) ASC;\n*/\n\nSELECT name, marks FROM student\nORDER BY city ASC; -- gives result in ascending order of city (delhi then mumbai then pune)\n\n-- Lets find out top 3 students\nSELECT * FROM student\nORDER BY marks DESC LIMIT 3; -- dhruv, bhumika, chetan\n\n\n/*\n------------------- Aggregate Functions ------------------------\n-\u003e Aggregate functions performs a calculation on a set of values, and return a single value\n\n- COUNT()\n- MAX()\n- MIN()\n- SUM()\n- AVG()\n\n=\u003e For example: SELECT max(marks) FROM student;\n*/\n\nSELECT MAX(marks) FROM student; -- shows 96\nSELECT MIN(marks) FROM student; -- shows 12\nSELECT AVG(marks) FROM student; -- shows 74.3333\nSELECT COUNT(rollNo) FROM student; -- shows 6\nSELECT SUM(marks) FROM student; -- shows 446\n\n\n/*\n------------------ Group By Clause -------------------\n-\u003e Groups rows that have the same values into summary rows.\n-\u003e It collects data from multiple records and groups the result by one or more column.\n\n-\u003e Generally we use group by with some aggregation function.\n\nFor ex: Count number of students in each city\n*/\n\nSELECT city, COUNT(rollNo)\nFROM student\nGROUP BY city;\n/*\n-\u003e Group the data based on cities\nPune    1\nMumbai  2\nDelhi   3\n*/\n\nSELECT city, name, COUNT(rollNo)\nFROM student\nGROUP BY city, name;\n/*\n-\u003e Group the data based on cities and name\nPune        anil        1\nMumbai      bhumika     1\nMumbai      chetan      1\nDelhi       dhruv       1\nDelhi       emanuel     1\nDelhi       farah       1\n*/\n\n-- Lets get the average marks based on city\nSELECT city, AVG(marks)\nFROM student\nGROUP BY city;\n/*\nPune    78.0000\nMumbai  89.0000\nDelhi   63.3333\n*/\n\n/*\n---------------------------------------------------------------------\nPractice Qs:\nQs: Write the query to find avg marks in each city in ascending order\n*/\n\nSELECT city, AVG(marks)\nFROM student\nGROUP BY city\nORDER BY city ASC;\n/*\nDelhi   63.3333\nMumbai  89.0000\nPune    78.0000\n*/\n\nSELECT city, AVG(marks)\nFROM student\nGROUP BY city\nORDER BY AVG(marks) ASC;\n/*\nDelhi   63.3333\nPune    78.0000\nMumbai  89.0000\n*/\n----------------------------------------------------------\n\n/*\n-----------------------------------------------------------\nPractice Qs:\n-\u003e For a given table, find the total payment according to each payment method.\n\n-----------------------------------------------------------------------------\ncustomer id    -         customer      -      mode       -     city         -\n-----------------------------------------------------------------------------\n101            -     Olivia Barrett    -  Netbanking     -     Portland     -\n102            -     Ethan Sinclair    -  Credit Card    -     Miami        -\n103            -     Maya Hernandez    -  Credit Card    -     Seattle      -\n104            -     Liam Donovan      -  Netbanking     -     Denver       -\n105            -     Sophia Nguyen     -  Credit Card    -     New Orleans  -\n106            -     Caleb Foster      -  Debit Card     -     Minneapolis  -\n107            -     Ava Patel         -  Debit Card     -     Phoenix      -\n108            -     Lucas Carter      -  Netbanking     -     Boston       -\n109            -     Isabella Martinez -  Netbanking     -     Nashville    -\n110            -     Jackson Brooks    -  Credit Card    -     Boston       -\n-----------------------------------------------------------------------------\n*/\n\n-- Create the table\nCREATE TABLE customers (\n    customer_id INT PRIMARY KEY,\n    customer_name VARCHAR(100),\n    payment_mode VARCHAR(20),\n    city VARCHAR(50)\n);\n\n-- Insert the data\nINSERT INTO customers (customer_id, customer_name, payment_mode, city) VALUES\n(101, 'Olivia Barrett', 'Netbanking', 'Portland'),\n(102, 'Ethan Sinclair', 'Credit Card', 'Miami'),\n(103, 'Maya Hernandez', 'Credit Card', 'Seattle'),\n(104, 'Liam Donovan', 'Netbanking', 'Denver'),\n(105, 'Sophia Nguyen', 'Credit Card', 'New Orleans'),\n(106, 'Caleb Foster', 'Debit Card', 'Minneapolis'),\n(107, 'Ava Patel', 'Debit Card', 'Phoenix'),\n(108, 'Lucas Carter', 'Netbanking', 'Boston'),\n(109, 'Isabella Martinez', 'Netbanking', 'Nashville'),\n(110, 'Jackson Brooks', 'Credit Card', 'Boston');\n\nSELECT payment_mode, COUNT(customer_name)\nFROM customers\nGROUP BY payment_mode;\n\n/*\nResult:\n-------\nNetbanking      4\nCredit Card     4\nDebit Card      2\n*/\n\n-----------------------\n\n-- Q: Lets take the above student table and write a query to group students\n-- according to their grade.\n\nSELECT grade, COUNT(rollNo)\nFROM student\nGROUP BY grade\nORDER BY grade ASC;\n/*\nResult:\n------\nA   2\nB   2\nC   1\nF   1\n*/\n\n/*\n--------------- Having Clause ---------------\n                -------------\n-\u003e Simialr to Where i.e. appliess some condition on rows.\n-\u003e Used when we want to apply any condition after grouping.\n\n-\u003e For ex: Count number of students in each city where max marks cross 90/\n*/\n\nSELECT city, COUNT(rollNo)\nFROM student\nGROUP BY city;\n/*\nResult:\n------\nPune    1\nMumbai  2\nDelhi   3\n*/\n\n-- Now, after applying having clause on this query,\nSELECT city, COUNT(rollNo)\nFROM student\nGROUP BY city\nHAVING MAX(marks) \u003e 90;\n/*\nResult:\n------\nMumbai  2\nDelhi   3\n*/\n\n/*\n--------------- General Order --------------\n                ------------\nSELECT column(s)\nFROM table_name\nWHERE condition\nGROUP BY condition\nHAVING condition\nORDER BY column(s) ASC;\n*/\n\nSELECT city\nFROM student\nWHERE grade = \"A\"\nGROUP BY city\nHAVING MAX(marks) \u003e 90\nORDER BY city DESC;\n/*\nResult:\n------\nMumbai\nDelhi\n*/\n\n/*\n---------- Table Related Queries ------------\n\nUpdate (to update existing rows)\n--------------------------------\nSYNTAX:-\n------\n    UPDATE table_name\n    SET col1 = val1, col2 = val2\n    WHERE condition;\n*/\n\n-- Sometime SQL strict us to update any table. So in that case we have to run one command\nSET SQL_SAFE_UPDATES = 0; -- mostly this problem visible in SQL Workbench\n\nUPDATE student\nSET grade = \"O\"\nWHERE grade = \"A\";\n\nSELECT * FROM student; -- here the grade \"A\" changed to grade \"O\".\n\n-- Update student emanuel marks to 82 and grade A\n\nUPDATE student\nSET marks = 82, grade = \"B\"\nWHERE rollNo = 105;\n\n\n/*\nLets say we have to increment each student marks by 1\n*/\n\nUPDATE student\nSET marks = marks + 1; -- this will increment each student marks by 1\n\n/*\n----------------- Delete ---------------\n                  ------\n-\u003e To delete existing rows\nSYNTAX:-\n    DELETE FROM table_name\n    WHERE condition;\n*/\n\nUPDATE student\nSET marks = 12\nWHERE rollNo = 105; -- this will again set emanuel marks to 12\n\n-- Now we can apply a delete query\n-- Delete the student whose marks \u003c 33\n\nDELETE FROM student\nWHERE marks \u003c 33; -- this has deleted emanuel's row\n\n\n\n\n-------------------- Part 2 ------------------------\n\n\n/*\n------------- Foreign Key in Detail ---------------\n\n*/\n\n\nUSE college;\nCREATE TABLE dept (\n\tid INT PRIMARY KEY,\n    subject_name VARCHAR(50)\n);\n\nCREATE TABLE teacher (\n\tid INT PRIMARY KEY,\n    name VARCHAR(50),\n    dept_id INT,\n    FOREIGN KEY (dept_id) REFERENCES dept(id)\n);\n\n-- We can see the connection between these two table in the er diagram provided in github\n\n-- dept -\u003e parent table\n-- teacher -\u003e child table\n\n--------------------------------------------------------------\n\n----------------- Cascading for Foreign Key ---------------------\n                  -------------------------\n/*\nOn Delete Cascade:\n------------------\nWhen we create a foreign key using this option, it deletes the referencing rows in the child table\nwhen the referenced row is deleted in the parent table which has a primary key.\n\nOn Update Cascade:\n------------------\nWhen we create a foreign key using UPDATE CASCADE the referencing rows are updated in the child\ntable when the referenced row is updated in the parent table which has a primary key\n*/\n\n-- so we have to write this create table in this way\nCREATE TABLE teacher (\n\tid INT PRIMARY KEY,\n    name VARCHAR(50),\n    dept_id INT,\n    FOREIGN KEY (dept_id) REFERENCES dept(id)\n    ON UPDATE CASCADE\n    ON DELETE CASCADE\n);\n\nINSERT INTO dept\nVALUES\n(101, \"CSE\"),\n(102, \"IT\");\n\nSELECT * FROM dept;\n\nINSERT INTO teacher\nVALUES\n(1001, \"jayanta\", 101),\n(1002, \"arindam\", 101),\n(1003, \"sagar\", 102),\n(1004, \"tanaya\", 101),\n(1005, \"yusuf\", 102);\n\nSELECT * FROM teacher;\n\nUPDATE dept\nSET id = 103\nWHERE subject_name = \"CSE\" AND id = 101; \n-- this will not just update dept table it will also update teacher table's dept_id\n\n----------------------------------------------------\n-------------- Table Related Queries ---------------\n\n/*\n------------------- ALTER (to change the schema) --------------------\n----------------------------\n\nADD Column\n----------\nALTER TABLE table_name\nADD COLUMN column_name datatype constraint;\n\nDROP Column\n-----------\nALTER TABLE table_name\nDROP COLUMN column_name;\n\nRENAME Table\n------------\nALTER TABLE table_name\nRENAME TO new_table_name;\n\nCHANGE Column (rename):\n---------------------\nALTER TABLE table_name\nCHANGE COLUMN old_name new_name new_datatype new_constraint;\n\nMODIFY Column (modify datatype/constraint):\n------------------------------------------\nALTER TABLE table_name\nMODIFY col_name new_datatype new_contraint;\n\n*/\n\nALTER TABLE student\nADD COLUMN age INT; -- this will add a new column age in student\n\nALTER TABLE student\nDROP COLUMN age; -- this will delete the age column from student\n\nALTER TABLE student\nRENAME TO stu; -- this will rename student table to stu\n\nALTER TABLE stu\nADD COLUMN age INT; -- adding new col age\n\nALTER TABLE stu\nCHANGE age stu_age INT; -- change column name from age to stu_age\n\nALTER TABLE stu\nMODIFY stu_age VARCHAR(2); -- change column datatype int to varchar\n\nSELECT * FROM stu;\n\n/*\n----------------------------- TRUNCATE ----------------------------\n                            -----------\n-\u003e DROP TABLE deletes whole table with data whereas\n-\u003e TRUNCATE TABLE table_name delete only table's data not the table\n*/\n\nTRUNCATE TABLE stu; -- this will delete all the data but not the table\n\n\n/*\n--------------------------- PRACTICE Qs: ---------------------------------\nQs: In the student table:\n    -\u003e change the name of the column \"name\" to \"full_name\".\n    -\u003e Delete all the students who scored marks less than 80.\n    -\u003e Delete the column for grades\n*/\n\nSELECT * FROM stu;\n\n--- Ans: Q1\nALTER TABLE stu\nCHANGE name full_name VARCHAR(50);\n\n--- Ans: Q2\n\nDELETE FROM stu\nWHERE marks \u003c 80;\n\n--- Ans: Q3\nALTER TABLE stu\nDROP COLUMN grade;\n\n----------------------------------------------------------------\n\n/*\n------------------ JOINS in SQL ---------------------\n                ------------------\n\n-\u003e Join is used to combine rows from two or more tables, based on a related column between them.\n\n            Employee                            Salary\n        id          name                    id      salary\n        ----------------                    --------------\n        101         john                    102     25000\n        102         bob                     103     50000\n\n        So, here from the above columns we can join name and salary based on related id 102.\n\n\n----------------- Types of Joins -----------------\n\n1. Inner Join\n-------------\n    A         B\n   [   ]---[   ]\n     \\     /\n      \\___/   ← Only matching records (A ∩ B)\n\n\n2. Outer Join\n-------------\n    i) Left Join, ii) Right Join, iii) Full Outer Join\n\n\n--- Left Join ---\n    ---------\n    A         B\n   [   ]---[   ]\n   [_______]\n     \\___/       ← All from A + matching from B\n\n--- Right Join ---\n    ----------\n\n    A         B\n   [   ]---[   ]\n           [_______]\n             \\___/   ← All from B + matching from A\n\n--- Full Outer Join ---\n    ---------------\n    A         B\n   [   ]   [   ]\n   [___________]   ← All from A + B (matched or not)\n\n\nFor better understanding see the diagram in google or in this repo.\n\n*/\n\n\n------------ INNER JOIN -------------\n            ------------\n/*\n-- Return records that have matching values in  both tables\nSYNTAX:\n------\n        SELECT column(s)\n        FROM tableA\n        INNER JOIN tableB\n        ON tableA.col_name = tableB.col_name\n\n-\u003e For ex:\nThis is our student table\n\n+--------+-----------+-------+--------+\n| rollNo | full_name | marks | city   |\n+--------+-----------+-------+--------+\n|  102   | bhumika   |  93   | Mumbai |\n|  103   | chetan    |  85   | Mumbai |\n|  104   | dhruv     |  96   | Delhi  |\n|  106   | farah     |  82   | Delhi  |\n+--------+-----------+-------+--------+\n\nand course table is:\n+--------+------------------+\n| rollNo | course           |\n+--------+------------------+\n|  102   | english          |\n|  103   | math             |\n|  104   | science          |\n|  106   | computer science |\n+--------+------------------+\n\nand now after performing inner join on student and course table with respect to rollNo and want to\nsee full_name, city and marks column then the result will be:\n\n+-----------+--------+-------+\n| full_name | city   | marks |\n+-----------+--------+-------+\n| bhumika   | Mumbai |  93   |\n| chetan    | Mumbai |  85   |\n| dhruv     | Delhi  |  96   |\n| farah     | Delhi  |  82   |\n+-----------+--------+-------+\n\n\n*/\n\nSELECT * FROM stu;\n\nCREATE TABLE course(\n    rollNo INT,\n    course VARCHAR(50),\n    FOREIGN KEY (rollNo) REFERENCES stu(rollNo)\n);\n\nINSERT INTO course\nVALUES\n(102, \"english\"),\n(103, \"math\"),\n(104, \"science\"),\n(106, \"computer science\");\n\nSELECT * FROM course;\n\n---- Inner Join ----\nSELECT full_name, city, marks\nFROM stu\nINNER JOIN course\nON stu.rollNo = course.rollNo;\n\n/*\nRESULT:\n------\n\n+-----------+--------+-------+\n| full_name | city   | marks |\n+-----------+--------+-------+\n| bhumika   | Mumbai |  93   |\n| chetan    | Mumbai |  85   |\n| dhruv     | Delhi  |  96   |\n| farah     | Delhi  |  82   |\n+-----------+--------+-------+\n\n*/\n\n\n------------ LEFT JOIN -------------\n            -----------\n/*\n-- Returns all records from the left table, and the matched records from the right table\nSYNTAX:\n------\n        SELECT column(s)\n        FROM tableA\n        LEFT JOIN tableB\n        ON tableA.col_name = tableB.col_name\n\n-\u003e For ex:\nThis is our student table\n\n+--------+-----------+-------+--------+\n| rollNo | full_name | marks | city   |\n+--------+-----------+-------+--------+\n|  102   | bhumika   |  93   | Mumbai |\n|  103   | chetan    |  85   | Mumbai |\n|  104   | dhruv     |  96   | Delhi  |\n|  106   | farah     |  82   | Delhi  |\n+--------+-----------+-------+--------+\n\nand course table is:\n+--------+------------------+\n| rollNo | course           |\n+--------+------------------+\n|  102   | english          |\n|  111   | math             |\n|  114   | science          |\n|  106   | computer science |\n+--------+------------------+\n\nand now after performing left join on student and course table with respect to rollNo and want to\nsee full_name, city and marks column then the result will be:\n\n+--------+-----------+-------+--------+--------+------------------+\n| rollNo | full_name | marks | city   | rollNo | course           |\n+--------+-----------+-------+--------+--------+------------------+\n|  102   | bhumika   |  93   | Mumbai |  102   | english          |\n|  103   | chetan    |  85   | Mumbai | (NULL) | (NULL)           |\n|  104   | dhruv     |  96   | Delhi  | (NULL) | (NULL)           |\n|  106   | farah     |  82   | Delhi  |  106   | computer science |\n+--------+-----------+-------+--------+--------+------------------+\n\n*/\n\nDROP TABLE course;\n\nCREATE TABLE course(\n    rollNo INT,\n    course VARCHAR(50)\n);\n\nINSERT INTO course\nVALUES\n(102, \"english\"),\n(111, \"math\"),\n(114, \"science\"),\n(106, \"computer science\");\n\nSELECT * FROM course;\n\nSELECT *\nFROM stu as s\nLEFT JOIN course as c\nON s.rollNo = c.rollNo;\n\n/*\nRESULT:\n------\n\n+--------+-----------+-------+--------+--------+------------------+\n| rollNo | full_name | marks | city   | rollNo | course           |\n+--------+-----------+-------+--------+--------+------------------+\n|  102   | bhumika   |  93   | Mumbai |  102   | english          |\n|  103   | chetan    |  85   | Mumbai | (NULL) | (NULL)           |\n|  104   | dhruv     |  96   | Delhi  | (NULL) | (NULL)           |\n|  106   | farah     |  82   | Delhi  |  106   | computer science |\n+--------+-----------+-------+--------+--------+------------------+\n\n*/\n\n------------ RIGHT JOIN -------------\n            -----------\n/*\n-- Returns all records from the right table, and the matched records from the left table\nSYNTAX:\n------\n        SELECT column(s)\n        FROM tableA\n        RIGHT JOIN tableB\n        ON tableA.col_name = tableB.col_name\n\n-\u003e For ex:\nThis is our student table\n\n+--------+-----------+-------+--------+\n| rollNo | full_name | marks | city   |\n+--------+-----------+-------+--------+\n|  102   | bhumika   |  93   | Mumbai |\n|  103   | chetan    |  85   | Mumbai |\n|  104   | dhruv     |  96   | Delhi  |\n|  106   | farah     |  82   | Delhi  |\n+--------+-----------+-------+--------+\n\nand course table is:\n+--------+------------------+\n| rollNo | course           |\n+--------+------------------+\n|  102   | english          |\n|  111   | math             |\n|  114   | science          |\n|  106   | computer science |\n+--------+------------------+\n\nand now after performing left join on student and course table with respect to rollNo and want to\nsee full_name, city and marks column then the result will be:\n\n+--------+-----------+-------+--------+--------+------------------+\n| rollNo | full_name | marks | city   | rollNo | course           |\n+--------+-----------+-------+--------+--------+------------------+\n|  102   | bhumika   |  93   | Mumbai |  102   | english          |\n| (NULL) | (NULL)    | NULL  | NULL   |  111   | math             |\n| (NULL) | (NULL)    | NULL  | NULL   |  114   | science          |\n|  106   | farah     |  82   | Delhi  |  106   | computer science |\n+--------+-----------+-------+--------+--------+------------------+\n\n\n*/\n\nSELECT *\nFROM stu as s\nRIGHT JOIN course as c\nON s.rollNo = c.rollNo;\n\n/*\nRESULT:\n------\n\n+--------+-----------+-------+--------+--------+------------------+\n| rollNo | full_name | marks | city   | rollNo | course           |\n+--------+-----------+-------+--------+--------+------------------+\n|  102   | bhumika   |  93   | Mumbai |  102   | english          |\n| (NULL) | (NULL)    | NULL  | NULL   |  111   | math             |\n| (NULL) | (NULL)    | NULL  | NULL   |  114   | science          |\n|  106   | farah     |  82   | Delhi  |  106   | computer science |\n+--------+-----------+-------+--------+--------+------------------+\n\n*/\n\n/*\n-------------- FULL JOIN / FULL OUTER JOIN ----------------\n              -----------------------------\n\n-\u003e Returns all records when there is a match in either left or right table.\n\n*** In MySQL, Full Join does not work. But in Oracle database it does.\n\nso, the general syntax for FULL JOIN is:\nSYNTAX:\n------\n        SELECT column(s)\n        FROM tableA\n        FULL JOIN tableB\n        ON tableA.col_name = tableB.col_name\n\nBut in MySQL, we can use Union to perform full join\n\nSYNTAX:\n-------\n        SELECT *\n        FROM tableA\n        LEFT JOIN tableB\n        ON tableA.rollNo = tableB.rollNo\n\n        UNION\n\n        SELECT *\n        FROM tableA\n        RIGHT JOIN tableB\n        ON tableA.rollNo = tableB.rollNo;\n\n*/\n\nSELECT *\nFROM stu as s\nLEFT JOIN course as c\nON s.rollNo = c.rollNo\n\nUNION\n\nSELECT *\nFROM stu as s\nRIGHT JOIN course as c\nON s.rollNo = c.rollNo;\n\n/*\nRESULT:\n------\n\n+--------+-----------+-------+--------+--------+------------------+\n| rollNo | full_name | marks | city   | rollNo | course           |\n+--------+-----------+-------+--------+--------+------------------+\n| 102    | bhumika   | 93    | Mumbai | NULL   | english          |\n| 103    | chetan    | 85    | Mumbai | NULL   | NULL             |\n| 104    | dhruv     | 96    | Delhi  | NULL   | NULL             |\n| 106    | farah     | 82    | Delhi  | 106    | computer scier   |\n| NULL   | NULL      | NULL  | NULL   | 111    | math             |\n| NULL   | NULL      | NULL  | NULL   | 114    | science          |\n+--------+-----------+-------+--------+--------+------------------+\n\n*/\n\n/*\nThere are also some another types of joins. Lets see them one by one.\n*/\n\n----------  Left Exclusive Join ------------\n            -------------------\n\nSELECT *\nFROM stu as s\nLEFT JOIN course as c\nON s.rollNo = c.rollNo\nWHERE c.rollNo IS NULL;\n\n/*\nRESULT:\n------\n+--------+-----------+-------+--------+--------+------------------+\n| rollNo | full_name | marks | city   | rollNo | course           |\n+--------+-----------+-------+--------+--------+------------------+\n|  103   | chetan    |  85   | Mumbai | (NULL) | (NULL)           |\n|  104   | dhruv     |  96   | Delhi  | (NULL) | (NULL)           |\n+--------+-----------+-------+--------+--------+------------------+\n*/\n\n----------  Right Exclusive Join ------------\n            --------------------\n\nSELECT *\nFROM stu as s\nRIGHT JOIN course as c\nON s.rollNo = c.rollNo\nWHERE s.rollNo IS NULL;\n\n/*\nRESULT:\n------\n\n+--------+-----------+-------+--------+--------+------------------+\n| rollNo | full_name | marks | city   | rollNo | course           |\n+--------+-----------+-------+--------+--------+------------------+\n| (NULL) | (NULL)    | NULL  | NULL   |  111   | math             |\n| (NULL) | (NULL)    | NULL  | NULL   |  114   | science          |\n+--------+-----------+-------+--------+--------+------------------+\n*/\n\n\n----------  Full Exclusive Join ------------\n            -------------------\n\nSELECT *\nFROM stu as s\nLEFT JOIN course as c\nON s.rollNo = c.rollNo\nWHERE c.rollNo IS NULL\n\nUNION\n\nSELECT *\nFROM stu as s\nRIGHT JOIN course as c\nON s.rollNo = c.rollNo\nWHERE s.rollNo IS NULL;\n\n/*\nRESULT:\n------\n\n+--------+-----------+-------+--------+--------+------------------+\n| rollNo | full_name | marks | city   | rollNo | course           |\n+--------+-----------+-------+--------+--------+------------------+\n|  103   | chetan    |  85   | Mumbai | (NULL) | (NULL)           |\n|  104   | dhruv     |  96   | Delhi  | (NULL) | (NULL)           |\n| (NULL) | (NULL)    | NULL  | NULL   |  111   | math             |\n| (NULL) | (NULL)    | NULL  | NULL   |  114   | science          |\n+--------+-----------+-------+--------+--------+------------------+\n*/\n\n----------  Self Join ------------\n            ---------\n/*\nIt is a regular join but the table is joined with itself.\n\nSYNTAX:\n------\n        SELECT column(s)\n        FROM tableA AS a\n        JOIN tableB AS b\n        ON a.col_name = b.col_name;\n*/\n\n\nCREATE TABLE employee(\n    id INT PRIMARY KEY,\n    name VARCHAR(50),\n    manager_id INT\n);\n\nINSERT INTO employee (id, name, manager_id)\nVALUES\n(101, \"adam\", 103),\n(102, \"bob\", 104),\n(103, \"casey\", NULL),\n(104, \"donald\", 103);\n\nSELECT * FROM employee;\n\nSELECT a.name as manager_name, b.name\nFROM employee as a\nJOIN employee as b\nON a.id = b.manager_id;\n\n/*\nRESULT:\n------\n\n+--------+--------------+\n| manager_name | name   |\n+--------+--------------+\n|  casey       | chetan |\n|  donald      | dhruv  |\n|  casey       | donald |\n+--------+--------------+\n*/\n\n/*\n------------------------ UNION -------------------------\n                        -------\n\nIt is used to combine the result-set of two or more SELECT statements.\nGives UNIQUE records.\n\nTo use it:\n-\u003e Every SELECT should have same no. of columns.\n-\u003e columns must have similar data types.\n-\u003e columns in every SELECT should be in same order.\n\nSYNTAX:\n-------\n        SELECT column(s) FROM tableA\n        UNION\n        SELECT column(s) FROM tableB\n\nand\n        SELECT column(s) FROM tableA\n        UNION ALL\n        SELECT column(s) FROM tableB\n\n- the last query will give duplicates also.\n\n*/\n\n\n/*\n----------------------- SQL SUB QUERIES -----------------------\n                    ---------------------\n\n-\u003e A subquery or inner query or a nested query is a query within another SQL query.\n-\u003e It involves 2 select statements.\n\nSELECT column(s)\nFROM table_name\nWHERE col_name operator\n(subquery);\n\n*/\n\nSELECT * FROM student;\n\n/*\nExample:\n    Get names of all students who scored more than class average.\n\n    Step 1: Find the avg of class\n    Step 2: Find the names of students with marks \u003e avg\n*/\n\nSELECT AVG(marks) FROM student; -- 87.667\n\nSELECT name\nFROM student\nWHERE marks \u003e 87.667;\n\n-- But if more students join later then this will change.\n-- so for that reason we can use sub queries.\n\nSELECT name, marks\nFROM student\nWHERE marks \u003e (\n    SELECT AVG(marks)  FROM student\n);\n-- the above sub query will also give us the same result.\n-- this subquery is dynamic SQL query.\n\n-- Qs: Find the name of all students with even roll nubmers.\n-- Step 1: Find the even roll numbers.\n-- Step 2: Find the names of students will even roll no.\n\nSELECT rollNo\nFROM student\nWHERE rollNo % 2 = 0;\n\nSELECT name\nFROM student\nWHERE rollNo IN(102, 104, 106);\n/*\nResult:\n------\nbhumika\ndhruv\nfarah\n*/\n\n-- Now using sub query\nSELECT name\nFROM student\nWHERE rollNo IN (\n    SELECT rollNo\n    FROM student\n    WHERE rollNo % 2 = 0\n);\n\n-- this will also give us the same result\n/*\nResult:\n------\nbhumika\ndhruv\nfarah\n*/\n\n\n/*\n\nExample using FROM:\n------------------\n\nQs: Find the max marks from the students of Delhi.\n\nStep 1: Find the students of Delhi.\nStep 2: Find the max marks using the sublist in step 1\n\n*/\n\nSELECT *\nFROM student\nWHERE city = \"delhi\";\n\nSELECT MAX(marks)\nFROM (\n    SELECT *\n    FROM student\n    WHERE city = \"delhi\"\n) AS temp;\n/**\nResult:\n------\n96\n/\n\n-- as Temp is like a temporary table which we get from the sub query\n-- and if we are using FROM then we have to write this kind of aliases.\n\n/*\nUsing sub-queries inside SELECT\n*/\n\nSELECT (SELECT MAX(marks) FROM student), name FROM student;\n/*\nResult:\n-------\n96      anil\n96      bhumika\n96      chetan\n96      dhruv\n96      emanuel\n96      farah\n*/\n\n--------------------------------------------------\n /*\n -------------------    VIEWS   ------------------\n                    ------------\n\n-\u003e A view is a virtual table based on the result-set of an SQL statement.\nNOTE:\n----\n    A view always show us up-to-date data.\n    The database engine recreates the view each time a user make a \n    query.\n*/\n\nCREATE VIEW view1 AS\nSELECT rollNo, name\nFROM student;\n\n/*\nAfter creating a view we can make multiple queries in this view \nas like a table.\n*/\n\nSELECT name  FROM view1;\n\n/*\nResult:\n-------\nanil\nbhumika\nchetan\ndhruv\nemanuel\nfarah\n*/\n\n-------------------------------------------------------------\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkanadshee-18%2Fsql_in_one_go","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkanadshee-18%2Fsql_in_one_go","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkanadshee-18%2Fsql_in_one_go/lists"}