{"id":25189979,"url":"https://github.com/rakibrahman/sql","last_synced_at":"2025-07-17T07:08:08.073Z","repository":{"id":192943097,"uuid":"687786145","full_name":"RakibRahman/SQL","owner":"RakibRahman","description":null,"archived":false,"fork":false,"pushed_at":"2024-08-16T13:05:40.000Z","size":3632,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-04T11:28:38.216Z","etag":null,"topics":["mysql-database","sql","sqlite3"],"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/RakibRahman.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}},"created_at":"2023-09-06T02:13:39.000Z","updated_at":"2024-08-16T13:05:44.000Z","dependencies_parsed_at":"2024-08-08T09:17:05.475Z","dependency_job_id":"36ac7ada-35c5-4f97-b0cf-24c497c875cc","html_url":"https://github.com/RakibRahman/SQL","commit_stats":null,"previous_names":["rakibrahman/sql"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/RakibRahman/SQL","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RakibRahman%2FSQL","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RakibRahman%2FSQL/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RakibRahman%2FSQL/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RakibRahman%2FSQL/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RakibRahman","download_url":"https://codeload.github.com/RakibRahman/SQL/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RakibRahman%2FSQL/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265575519,"owners_count":23790782,"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-database","sql","sqlite3"],"created_at":"2025-02-09T21:18:27.755Z","updated_at":"2025-07-17T07:08:08.039Z","avatar_url":"https://github.com/RakibRahman.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# SQL\nSQL is a programming language designed to manipulate and manage data stored in relational databases.\n\n`CREATE TABLE` creates a new table.\n```\n\nCREATE TABLE languages (\nid INTEGER,\nname TEXT\n);\n\n```\n`INSERT INTO` adds a new row to a table.\n```\nINSERT INTO languages\nVALUES (1,'JS');\n\nINSERT INTO languages\nVALUES (2,'Python');\n\n```\n`SELECT` queries data from a table.\n```\nSELECT * FROM languages // returns all columns\n\nSELECT id from languages // returns only id column\n```\n`ALTER TABLE` statement is used to add, delete, or modify columns in an existing table.\n```\nALTER TABLE languages\nADD COLUMN year INTEGER; // add a column named year to languages table\n\nRENAME COLUMN old_name to new_name; //rename a column\nDROP COLUMN column_name; // Drop a column\n```\n`UPDATE` edits a row in a table.\n```\nUPDATE languages \nSET year = 1997 \nWHERE id = 1; \n\nUPDATE languages\nSET year = 2000\nWHERE id = 2;\n```\n`DELETE FROM` deletes rows from a table\n```\nDELETE FROM languages\nWHERE id = 3;\n```\n\n# Constraints\nConstraints that add information about how a column can be used are invoked after specifying the data type for a column. They can be used to tell the database to reject inserted data that does not adhere to a certain restriction. The statement below sets constraints on the celebs table.\n\n```\nCREATE TABLE celebs (\n   id INTEGER PRIMARY KEY, \n   name TEXT UNIQUE,\n   date_of_birth TEXT NOT NULL,\n   date_of_death TEXT DEFAULT 'Not Applicable'\n);\n\n```\n\n\n1. PRIMARY KEY columns can be used to uniquely identify the row. Attempts to insert a row with an identical value to a row already in the table will result in a constraint violation which will not allow you to insert the new row.\n\n2. UNIQUE columns have a different value for every row. This is similar to PRIMARY KEY except a table can have many different UNIQUE columns.\n\n3. NOT NULL columns must have a value. Attempts to insert a row without a value for a NOT NULL column will result in a constraint violation and the new row will not be inserted.\n\n4. DEFAULT columns take an additional argument that will be the assumed value for an inserted row if the new row does not specify a value for that column.\n\n--- \n\n# Primary Key vs Foreign Key\n\nPrimary keys have a few requirements:\n\n- None of the values can be NULL.\n- Each value must be unique (i.e., you can’t have two customers with the same customer_id in the customers table).\n- A table can not have more than one primary key column.\n\n   When the primary key for one table appears in a different table, it is called a **foreign key**. \n---\n\n# DISTINCT\n`DISTINCT` is used to return unique values in the output. It filters out all duplicate values in the specified column(s).\n```\nSELECT DISTINCT tools \nFROM inventory;\n\nSELECT DISTINCT course_id, exercise_id FROM courses;\n```\n---\n# WHERE\nThe `WHERE` clause filters the result set to only include rows where the following condition is true.\n```\nSELECT *\nFROM students\nWHERE age \u003e 8;\n\nSELECT ROUND(LONG_W,4) from STATION\nWHERE lat_n = (SELECT MIN(lat_n) from STATION\nWHERE LAT_N \u003e 38.7780); \n```\n\nComparison operators used with the WHERE clause are:\n\n    = equal to\n    != not equal to\n    \u003e greater than\n    \u003c less than\n    \u003e= greater than or equal to\n    \u003c= less than or equal to\n\n---\n\n# LIKE\n\n`LIKE` is a special operator used with the `WHERE` clause to search for a specific pattern in a column.\n\n```\nSELECT * from names;\nWHERE first_name LIKE 'r_b' //it will look for columns whrer name starts with 'r' and ends with 'b'\n```\n _ means you can substitute any individual character.\n\n% is a wildcard character that matches zero or more missing letters in the pattern. For example:\n\n    A% matches all movies with names that begin with letter ‘A’\n    %a matches all movies that end with ‘a’\n```\nSELECT * \nFROM movies\nWHERE name LIKE 'A%'\n```\nWe can also use % both before and after a pattern:\n\n```\nSELECT * \nFROM movies \nWHERE name LIKE '%man%';\n```\n```\nSELECT * FROM Customers\nWHERE City LIKE 'a%b'; //column start with 'a' and ends with 'b'\n\n\nSELECT * FROM Customers\nWHERE City LIKE '[acs]%'; //Select all records where the first letter of the City is an \"a\" or a \"c\" or an \"s\".\n\n\nSELECT * FROM Customers\nWHERE City LIKE '[a-f]%'; //Select all records where the first letter of the City starts with anything from an \"a\" to an \"f\". \n\n\nSELECT * FROM Customers\nWHERE City LIKE '[!acs]%'; //Select all records where the first letter of the City is NOT an \"a\" or a \"c\" or an \"f\".\n\n //with regular expression\n \nSELECT distinct city from station\nwhere city regexp  '^[aeiouAEIOU].'; CITY names starting with vowels (a, e, i, o, u)\n\nSELECT distinct city from station\nwhere city regexp  '[aeiouAEIOU]$'; //CITY names ending with vowels (a, e, i, o, u)\n```\n\nif a patterns contains '%' or '_' , we can use escape character \\ to include it\n```\nSELECT *\nFROM books\nWHERE title LIKE '% 100\\%';\n```\nHere, any movie that contains the word ‘man’ in its name will be returned in the result.\n\n---\n\n# Is Null\nUnknown or missing values are indicated by NULL.It is not possible to test for NULL values with comparison operators, such as = and !=. \n\nto test for NULL values we can use:\n\n    IS NULL // contains value\n    IS NOT NULL //value is missing\n```\nSELECT name\nFROM people \nWHERE address IS NOT NULL;\n```\n\n---\n\n\n# BETWEEN\n\nThe `BETWEEN` operator is used in a WHERE clause to filter the result set within a certain range.\n\n```\nSELECT * FROM students\nWHERE year BETWEEN 1990 AND 1999;\nWHERE name BETWEEN 'A' AND 'J'; // in this statement BEETWEEN filters the result set only to include names that begin with 'A' ,upto but not including 'J'. \n\n```\n---\n\n# AND \u0026 OR Operator\n To combine multiple conditions in a `WHERE`clause to make the result set more specific and useful we can use `AND` or `OR`  operator.\n\n With `AND`, both conditions must be true for the row to be included in the result.\n `OR` operator displays a row if any condition is true.\n\n ```\nSELECT * FROM results\nWHERE year BETWEEN 1990 AND 1999 AND grade = 'a+';\n\nSELECT * FROM schools\nWHERE year \u003c 1985 AND type = 'public';\n\n\n\nSELECT *\nFROM students\nWHERE year \u003e 2014\n   OR grade = 'D';\n ```\n ---\n\n# IN Operator\nThe IN operator allows the user to specify multiple values in the WHERE clause.\n```\nSELECT *\nFROM inventory\nWHERE item_name IN ('plunger', 'soap', 'wipes'); // this statement will return result set where item_name is equal to  'plunger', 'soap', 'wipes'.\n\n\nSELECT *\nFROM customers\nWHERE country IN (\n  SELECT country\n  FROM suppliers\n);\n\nselect distinct city from station where left (city , 1) in ('a','e','i','o','u') and right (city , 1) in ('a','e','i','o','u');\n```\n---\n\n # ORDER BY\n`ORDER BY` clause is used to sort the results.\n```\nSELECT *\nFROM students\nORDER BY name; // sort every from A through Z by students name;\n\nSELECT *\nFROM students\nWHERE grade = 'A+'\nORDER BY pass_year DESC;\n\n\nSELECT year, name\nFROM students\nORDER BY year ASC, name DESC; // with multiple columns?\n```\n\n`DESC` is a keyword used in ORDER BY to sort the results in descending order (high to low or Z-A).\n\n`ASC` is a keyword used in ORDER BY to sort the results in ascending order (low to high or A-Z).\n\n\n---\n\n# LIMIT\n`LIMIT` is a clause that lets you specify the maximum number of rows the result set will have.\n\n```\nSELECT *\nFROM students\nLIMIT 10;\n```\n\n---\n\n# CASE\nA `CASE` statement allows us to create different outputs based on condition. It's the if-else of SQL.\n\n```\nselect name,\nCASE\n  WHEN grade = 'A+' THEN 'Fantastic' \n  WHEN grade = 'F' THEN 'Fail'\n  ELSE 'Absent'\nEND // The CASE statement must end with END.\nEND AS 'Review' //rename column\nFROM students;\n```\n---\n\n# Aggregate Functions\nCalculations performed on multiple rows of a table are called `aggregates`.\nsome important aggregates:\n\n- COUNT(): count the number of rows\n   ```\n   SELECT COUNT (*) FROM fake_apps // * - count every row\n   WHERE price = 0.0;\n\n   COUNT() is used to take a name of a column, and counts the number of non-empty values in that column\n   ```\n- SUM(): the sum of the values in a column\n   ```\n   SELECT SUM(downloads)\n   FROM fake_apps;\n\n    use COUNT() when you want to count how many rows contain a non-empty value for a specified column. Use SUM() when you want to get the total sum of all values in a column.\n   ```\n- MAX()/MIN(): the largest/smallest value\n   ```\n   SELECT MAX(downloads)\n   FROM fake_apps;\n\n   SELECT MIN(downloads)\n   FROM fake_apps;\n   ```\n- AVG(): the average of the values in a column\n   ```\n   SELECT AVG(downloads)\n   FROM fake_apps;\n   ```\n- ROUND(): round the values in the column\n\n`ROUND()` function takes two arguments inside the parenthesis:\n\n- a column name\n- an integer\nIt rounds the values in the column to the number of decimal places specified by the integer. \n\n```\nSELECT ROUND(price, 0)\nFROM fake_apps;\n\nSELECT ROUND(AVG(price), 2)\nFROM fake_apps;\n\n```\n---\n\n# GROUP BY\nGROUP BY is a clause in SQL that is used with aggregate functions. It is used in collaboration with the SELECT statement to arrange identical data into groups.\n\nThe GROUP BY statement comes after any WHERE statements, but before ORDER BY or LIMIT.\n\n```\nSELECT year,\n   AVG(price)\nFROM app_list\nGROUP BY year\nORDER BY year;\n\nSELECT price, COUNT(*) \nFROM fake_apps\nGROUP BY price; //The result contains the total number of apps for each price.\n\nSELECT category, SUM(downloads) \nFROM fake_apps\nGROUP BY category; // calculates the total number of downloads for each category.\n```\n---\n\n# HAVING\n`HAVING` clause  allows you to filter which groups to include and which to exclude.\n\n- When we want to limit the results of a query based on values of the individual rows, use WHERE.\n- When we want to limit the results of a query based on an aggregate property, use HAVING.\n\n`HAVING` statement always comes after GROUP BY, but before ORDER BY and LIMIT.\n\n```\nSELECT price, \n   ROUND(AVG(downloads)),\n   COUNT(*)\nFROM fake_apps\nGROUP BY price\nHAVING COUNT(*) \u003e 10;\n\n\u003c!-- WHERE \u0026 HAVING --\u003e\n\nSELECT genre, ROUND(AVG(score))\nFROM students\nWHERE bill \u003e 500000 \nGROUP BY class\nHAVING COUNT(*) \u003e 5;\n```\n---\n\n# JOIN - Combining Tables with SQL\nWe can combine tables in SQL with `JOIN` sequence. `INNER JOIN`  is the default join.\n```\nSELECT * from orders\nJOIN customers\n   ON orders.customer_id = customers.customer_id;\n```\n---\n\n# LEFT JOIN\nA `left join` will keep all rows from the first table, regardless of whether there is a matching row in the second table.\n```\nSELECT *\nFROM newspaper\nLEFT JOIN online\n   ON newspaper.id = online.id\nWHERE online.id IS NULL;\n```\n---\n\n# RIGHT JOIN\nA `right join` will keep all rows from the second(right) table, regardless of whether there is a matching row in the first(left) table.\n```\nSELECT column_name(s)\nFROM table_1\nRIGHT JOIN table_2\n  ON table_1.column_name = table_2.column_name;\n```\n\n---\n\n# CROSS JOIN\n`CROSS JOIN`  clause is used when we need to compare each row of a table to a list of values or  to combine all rows of one table with all rows of another table.\n\n `CROSS JOIN`  don’t require an ON statement as we're not really joining on any columns!\n\n```\nSELECT shirts.shirt_color,\n   pants.pants_color\nFROM shirts\nCROSS JOIN pants;\n\n\nSELECT shirts.shirt_color,\npants.pants_color,\nsocks.sock_color\nFROM shirts\nCROSS JOIN pants\nCROSS JOIN socks;\n\nIf the tables had 3 shirts, 2 pants, and 6 socks, then the result of this CROSS JOIN will give\n\n3 x 2 x 6 = 36 combinations, or 36 total rows.\n```\n\n---\n\n# UNION\n\nThe UNION command combines the results of two or more SELECT queries. \n\n```\nSELECT * from newspaper\nUNION\nSELECT * from online;\n```\n\nSQL has strict rules for appending data:\n\n- Tables must have the same number of columns.\n- The columns must have the same data types in the same order as the first table.\n\nWhen you combine tables with UNION, duplicate rows will be excluded.\n\n---\n\n# WITH\n\n`WITH` clause can store the result of a query using an alias;\n\n```\nWITH temporary_students AS (\n   SELECT *\n   FROM students\n)\nSELECT *\nFROM temporary_students\nWHERE grade = 'A+';\n\n\nWITH previous_query AS (\n  SELECT customer_id,\n   COUNT(subscription_id) AS 'subscriptions'\nFROM orders\nGROUP BY customer_id\n)\nSELECT  customers.customer_name, \n   previous_query.subscriptions from previous_query\nJOIN customers\nON previous_query.customer_id = customers.customer_id;\n\n\nWITH AGGREGATE_STATION AS (\n  SELECT MIN(COMMISSION) as [a],\n          MAX(COMMISSION) as [b]\n  FROM AGENTS)\n  \n  select * from AGGREGATE_STATION;\n\n\u003c!-- MYSQL --\u003e\n  WITH AGGREGATE_STATION AS (\n  SELECT MIN(LAT_N) as a,\n          MIN(LONG_W) as b,\n          MAX(LAT_N) as c,\n          MAX(LONG_W) as d\n  FROM STATION)\n  \n  select ROUND(ABS(a-c)+ABS(b-d),4) from AGGREGATE_STATION;\n\n\n  WITH AGGREGATE_STATION AS (\n  SELECT MIN(LAT_N) as a,\n          MIN(LONG_W) as c,\n          MAX(LAT_N) as b,\n          MAX(LONG_W) as d\n  FROM STATION)\n  \n  select ROUND(SQRT(POW(b-a,2)+POW(d-c,2)),4) from AGGREGATE_STATION;                               \n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frakibrahman%2Fsql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frakibrahman%2Fsql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frakibrahman%2Fsql/lists"}