├── Cheatsheet ├── MySQL │ └── README.md ├── SQL │ └── README.MD └── SpecialFunctions │ └── Readme.md ├── HackerRank └── README.md ├── LICENSE ├── LeetCode └── Readme.md └── README.md /Cheatsheet/MySQL/README.md: -------------------------------------------------------------------------------- 1 | # MySQL cheatsheet 2 | 3 | ### General Commands 4 | To run sql files 5 | ```sql 6 | source .sql; 7 | ``` 8 | 9 | ## Data Types 10 | 11 | #### Integers 12 | 13 | ```sql 14 | INT 15 | ``` 16 | ```sql 17 | TINYINT 18 | ``` 19 | ```sql 20 | SMALLINT 21 | ``` 22 | ```sql 23 | MEDIUMINT 24 | ``` 25 | ```sql 26 | BIGINT 27 | ``` 28 | 29 | #### Float 30 | 31 | ```sql 32 | FLOAT(M,D) 33 | ``` 34 | 35 | #### Double 36 | 37 | ```sql 38 | DOUBLE(M,D) 39 | ``` 40 | 41 | #### Decimal 42 | 43 | ```sql 44 | DECIMAL(M,D) 45 | ``` 46 | 47 | #### Date 48 | 49 | ```sql 50 | DATE -- Format - (YYYY-MM-DD) 51 | ``` 52 | 53 | #### Date Time 54 | 55 | ```sql 56 | DATETIME -- Format - (YYYY-MM-DD HH:MM:SS) 57 | ``` 58 | 59 | #### Time 60 | 61 | ```sql 62 | TIME -- Format - (HH:MM:SS) 63 | ``` 64 | 65 | #### String 66 | 67 | ```sql 68 | CHAR(M) 69 | ``` 70 | 71 | ```sql 72 | VARCHAR(M) 73 | ``` 74 | 75 | ```sql 76 | BLOB or TEXT 77 | ``` 78 | 79 | ## Comments 80 | 81 | ```sql 82 | /* Multi 83 | line 84 | comment */ 85 | ``` 86 | 87 | ```sql 88 | # Single Line Comment 89 | ``` 90 | 91 | ```sql 92 | -- Single Line Comment 93 | ``` 94 | 95 | ## Data Definition Language (DDL) 96 | 97 | #### Create Database 98 | ```sql 99 | create database cheatsheet; 100 | ``` 101 | 102 | #### Use Database 103 | ```sql 104 | use cheatsheet; 105 | ``` 106 | 107 | #### Show Databases 108 | ```sql 109 | show databases; 110 | ``` 111 | 112 | #### Create Table 113 | ```sql 114 | create table employee 115 | ( 116 | employee_id int primary key, -- Setting primary key(1st method) 117 | first_name varchar(50), 118 | last_name varchar(50), 119 | dept_number int, 120 | age int, 121 | salary real 122 | ); 123 | 124 | create table department 125 | ( 126 | dept_number int, 127 | dept_name varchar(50), 128 | dept_location varchar(50), 129 | emp_id int, 130 | primary key(dept_number) -- Setting primary key(2nd method) 131 | ); 132 | ``` 133 | 134 | #### Show Tables 135 | ```sql 136 | show tables; 137 | ``` 138 | 139 | #### Describe Table 140 | ```sql 141 | describe employee; 142 | desc employee; 143 | show columns in employee; 144 | ``` 145 | 146 | #### Rename Table 147 | ```sql 148 | rename table employee to employee_table; 149 | alter table employee_table rename to employee; 150 | ``` 151 | 152 | #### Renaming Column 153 | ```sql 154 | alter table employee change column employee_id emp_id int; 155 | ``` 156 | 157 | #### Add Constraint to Column 158 | ```sql 159 | alter table employee change column first_name first_name varchar(50) not null; 160 | ``` 161 | 162 | #### Add Column 163 | ```sql 164 | alter table employee add column salary real; 165 | ``` 166 | 167 | #### Drop Column 168 | ```sql 169 | alter table employee drop column salary; 170 | ``` 171 | 172 | #### Modify the Datatype of column 173 | ```sql 174 | alter table employee modify column salary int; 175 | ``` 176 | 177 | #### Truncate Table 178 | ```sql 179 | truncate employee; 180 | ``` 181 | 182 | #### Drop Table 183 | ```sql 184 | drop table department; 185 | ``` 186 | 187 | #### Drop Database 188 | ```sql 189 | drop database cheatsheet; 190 | ``` 191 | ## Data Manipulation Language (DML) 192 | 193 | #### Insertion (Complete) 194 | ```sql 195 | insert into employee (employee_id, first_name, last_name, dept_number, age, salary) values (1, "Anurag", "Peddi", 1, 20, 93425.63); 196 | 197 | insert into employee values (2, "Anuhya", "Peddi", 2, 20, 83425.63); 198 | ``` 199 | #### Insertion (Partial) 200 | ```sql 201 | insert into employee (employee_id, first_name) values (3, "Vageesh"); 202 | ``` 203 | 204 | #### Updating all rows 205 | ```sql 206 | update employee set salary = 1.1 * salary; 207 | ``` 208 | 209 | #### Updating a specified row 210 | ```sql 211 | update employee set salary = 1.2 * salary where employee_id = 1; 212 | ``` 213 | 214 | #### Delete a specified row 215 | ```sql 216 | delete from employee where employee_id = 2; 217 | ``` 218 | 219 | #### Delete all rows 220 | ```sql 221 | delete from employee; 222 | ``` 223 | 224 | #### Enabling foreign key checks 225 | ```sql 226 | set foreign_key_checks = 1; 227 | ``` 228 | 229 | #### Disabling foreign key checks 230 | ```sql 231 | set foreign_key_checks = 0; 232 | ``` 233 | 234 | ## Data Query Language (DQL) 235 | 236 | #### Display Table 237 | ```sql 238 | select * from employee; 239 | ``` 240 | 241 | #### Select only specified columns 242 | ```sql 243 | select employee_id, first_name from employee; 244 | ``` 245 | 246 | #### Select only few rows 247 | ```sql 248 | select employee_id, first_name from employee where age > 25; 249 | ``` 250 | 251 | ### Where Clause 252 | 253 | #### Greater than(>) 254 | ```sql 255 | select * from employee where salary > 3100; 256 | ``` 257 | 258 | #### Greater than equal to(>=) 259 | ```sql 260 | select * from employee where salary >= 3100; 261 | ``` 262 | 263 | #### Less than(<) 264 | ```sql 265 | select * from employee where salary < 4500; 266 | ``` 267 | 268 | #### Less than equal to(<=) 269 | ```sql 270 | select * from employee where salary <= 4350; 271 | ``` 272 | 273 | #### Range 274 | ```sql 275 | select * from employee where salary > 3000 and salary < 4000; 276 | ``` 277 | 278 | #### BETWEEN and AND 279 | ```sql 280 | select * from employee where salary between 3000 and 4000; 281 | ``` 282 | 283 | #### Null 284 | ```sql 285 | select * from employee where salary is NULL; 286 | ``` 287 | 288 | #### Not null 289 | ```sql 290 | select * from employee where salary is NOT NULL; 291 | ``` 292 | 293 | ### ORDER BY Clause 294 | ```sql 295 | select * from employee ORDER BY salary DESC; 296 | ``` 297 | 298 | #### Like Operator 299 | ```sql 300 | select * from employee where name like '%Jo%'; -- Similar to *Jo* in regrex 301 | ``` 302 | ```sql 303 | select * from employee where name like 'Jo_'; -- Similar to Jo. in regrex 304 | ``` 305 | 306 | ## Views 307 | 308 | #### Create a view 309 | ```sql 310 | create view personal_info as select first_name, last_name, age from employees; 311 | ``` 312 | 313 | #### Displaying view 314 | ```sql 315 | select * from personal_info; 316 | ``` 317 | 318 | #### Updating in view 319 | ```sql 320 | update personal_info set salary = 1.1 * salary; 321 | ``` 322 | 323 | #### Deleting record from view 324 | ```sql 325 | delete from personal_info where age < 40; 326 | ``` 327 | 328 | #### Droping a view 329 | ```sql 330 | drop view personal_info; 331 | ``` 332 | 333 | ## Joins 334 | #### Inner join 335 | ```sql 336 | select e.fname, p.pname from employees as e inner join project as p on e.eid = p.eid; 337 | 338 | -- or 339 | 340 | select e.fname, p.pname from employees as e join project as p on e.eid = p.eid; 341 | ``` 342 | 343 | #### Full outer join 344 | ```sql 345 | select e.fname, p.pname from employees as e left outer join project as p on e.eid = p.eid 346 | union 347 | select e.fname, p.pname from employees as e right outer join project as p on e.eid = p.eid; 348 | ``` 349 | 350 | #### Left outer join 351 | ```sql 352 | select e.fname, p.pname from employees as e left outer join project as p on e.eid = p.eid; 353 | ``` 354 | 355 | #### Right outer join 356 | ```sql 357 | select e.fname, p.pname from employees as e right outer join project as p on e.eid = p.eid; 358 | ``` 359 | 360 | #### Left outer join - inner join 361 | ```sql 362 | select e.fname, p.pname from employees as e left outer join project as p on e.eid = p.eid where p.pname is null; 363 | ``` 364 | 365 | #### Right outer join - inner join 366 | ```sql 367 | select e.fname, p.pname from employees as e right outer join project as p on e.eid = p.eid where e.fname is null; 368 | ``` 369 | 370 | ## Aggregation 371 | 372 | #### Sum function 373 | ```sql 374 | select sum(population) from city group by population; 375 | ``` 376 | 377 | #### Average function 378 | ```sql 379 | select avg(population) from city group by population; 380 | ``` 381 | 382 | #### Count function 383 | ```sql 384 | select district, count(district) from city group by district; 385 | ``` 386 | 387 | #### Maximum function 388 | ```sql 389 | select max(population) from city group by population; 390 | ``` 391 | 392 | #### Minimum function 393 | ```sql 394 | select min(population) from city group by population; 395 | ``` 396 | 397 | #### Standard deviation function 398 | ```sql 399 | select stddev(population) from city group by population; 400 | ``` 401 | 402 | #### Group concat function 403 | ```sql 404 | select group_concat(population) from city group by population; 405 | ``` 406 | 407 | > Only COUNT function considers NULL values 408 | 409 | ## Procedure 410 | 411 | #### Creating procedure 412 | ```sql 413 | create procedure display_dbs() 414 | show databases; 415 | ``` 416 | 417 | #### Calling procedure 418 | ```sql 419 | call display_dbs(); 420 | ``` 421 | 422 | #### Drop procedure 423 | ```sql 424 | drop procedure display_dbs; 425 | ``` 426 | 427 | ## Transaction 428 | 429 | #### Begin transaction 430 | ```sql 431 | start transaction; 432 | ``` 433 | 434 | #### Create savepoint 435 | ```sql 436 | savepoint sv_pt; 437 | ``` 438 | 439 | ```sql 440 | delete from city; -- changing data in table 441 | ``` 442 | 443 | #### Rollback 444 | ```sql 445 | rollback to sv_pt; 446 | ``` 447 | 448 | #### Releasing savepoint 449 | ```sql 450 | release savepoint sv_pt; 451 | ``` 452 | 453 | #### Commiting changes 454 | ```sql 455 | commit; 456 | ``` 457 | 458 | ## Cloning 459 | 460 | #### Duplicate a Table Schema 461 | ```sql 462 | create table emp_dup like employee; 463 | ``` 464 | 465 | #### Duplicate a Table 466 | ```sql 467 | create table emp_dup select * from employee; 468 | ``` 469 | 470 | ## Access Controls 471 | 472 | #### Creating New User 473 | ```sql 474 | CREATE USER 'username'@'localhost' IDENTIFIED BY 'password'; 475 | ``` 476 | the hostname part is set to `localhost`, so the user will be able to connect to the MySQL server only from the localhost. 477 | To grant access from another host, change the hostname part with the remote machine IP. 478 | ```sql 479 | CREATE USER 'username'@'172.8.10.5' IDENTIFIED BY 'user_password'; 480 | ``` 481 | To create a user that can connect from any host, '%' is used in the hostname part: 482 | ```sql 483 | CREATE USER 'username'@'%' IDENTIFIED BY 'user_password'; 484 | ``` 485 | 486 | #### Grant All Permissions 487 | ```sql 488 | GRANT ALL PRIVILEGES ON * . * TO 'username'@'localhost'; 489 | ``` 490 | Asterisks(\*) refers to the database and table names respectively. 491 | By using asterisks we can give access of all the databases **or** tables to the user. 492 | 493 | #### Flush Privileges 494 | ```sql 495 | FLUSH PRIVILEGES 496 | ``` 497 | All the changes won't be in effect unless this query is fired. 498 | 499 | #### Specific User Permissions 500 | ```sql 501 | GRANT type_of_permission ON database_name.table_name TO 'username'@'localhost'; 502 | ``` 503 | `type_of_permission` may have one of these value: 504 | * **ALL PRIVILEGES** - Allows user full access to a designated database (or if no database is selected, global access across the system). 505 | * **CREATE** - allows them to create new tables or databases. 506 | * **DROP** - allows them to them to delete tables or databases. 507 | * **DELETE** - allows them to delete rows from tables. 508 | * **INSERT** - allows them to insert rows into tables. 509 | * **SELECT** - allows them to use the `SELECT` command to read through databases. 510 | * **UPDATE** - allow them to update table rows. 511 | * **GRANT OPTION** - allows them to grant or remove other users’ privileges. 512 | Multiple permissions are given with commas. 513 | 514 | #### Revoking permissions 515 | ```sql 516 | REVOKE type_of_permission ON database_name.table_name FROM 'username'@'localhost'; 517 | ``` 518 | 519 | #### Show User's Current Permissions 520 | ```sql 521 | SHOW GRANTS FOR 'username'@'localhost'; 522 | ``` 523 | 524 | #### Delete a User 525 | ```sql 526 | DROP USER 'username'@'localhost'; 527 | ``` 528 | 529 | #### Set new password to a user 530 | ```sql 531 | use mysql; 532 | update user set authentication_string=PASSWORD("") where User=''; 533 | flush privileges; 534 | ``` 535 | 536 | ## Reset Root Password 537 | Stop MySQL service 538 | ``` 539 | sudo systemctl stop mysql 540 | ``` 541 | Restart MySQL service without loading grant tables 542 | ```bash 543 | sudo mysqld_safe --skip-grant-tables & 544 | ``` 545 | The apersand (&) will cause the program to run in the background and `--skip-grant-tables` enables everyone to to connect to the database server without a password and with all privileges granted. 546 | Login to shell 547 | ``` 548 | mysql -u root 549 | ``` 550 | Set new password for root 551 | ```sql 552 | ALTER USER 'root'@'localhost' IDENTIFIED BY 'MY_NEW_PASSWORD'; 553 | FLUSH PRIVILEGES; 554 | ``` 555 | Stop and start the server once again 556 | ``` 557 | mysqladmin -u root -p shutdown 558 | sudo systemctl start mysql 559 | ``` 560 | ## Programming 561 | 562 | #### Declare variables 563 | ```sql 564 | set @num = 10; 565 | set @name = 'Anurag'; 566 | ``` 567 | 568 | #### Print them 569 | ```sql 570 | select @name; 571 | ``` 572 | 573 | #### For loop 574 | ```sql 575 | set @n = 21; 576 | select repeat("* ", @n := @n - 1) from information_schema.tables where @n > 0; 577 | ``` 578 | 579 | ## Miscellaneous 580 | 581 | #### Round 582 | ```sql 583 | select round(3.141596, 3); 584 | ``` 585 | 586 | #### Repeated concatenation 587 | ```sql 588 | select repeat("* ", 20); 589 | ``` 590 | 591 | #### Random float 592 | ```sql 593 | select rand(); 594 | ``` 595 | 596 | #### Typecast to Int 597 | ```sql 598 | select cast(23.01245 as signed); 599 | ``` 600 | 601 | #### Concatenation 602 | ```sql 603 | select concat("Mahesh", " ", "Chandra", " ", "Duddu", "!"); 604 | ``` 605 | 606 | #### Extract Month 607 | ```sql 608 | select month("1998-12-30"); 609 | ``` 610 | 611 | #### Extract Year 612 | ```sql 613 | select year("1998-12-30"); 614 | ``` 615 | -------------------------------------------------------------------------------- /Cheatsheet/SQL/README.MD: -------------------------------------------------------------------------------- 1 | 2 | ## Querying data from a table 3 | 4 | - Query data in columns c1, c2 from a table 5 | 6 | ```SQL 7 | SELECT c1, c2 FROM t; 8 | ``` 9 | 10 | - Query all rows and columns from a table 11 | 12 | ```SQL 13 | SELECT * FROM t; 14 | ``` 15 | 16 | - Query data and filter rows with a condition 17 | 18 | ```SQL 19 | SELECT c1, c2 FROM t 20 | WHERE condition; 21 | ``` 22 | 23 | - Query distinct rows from a table 24 | 25 | ```SQL 26 | SELECT DISTINCT c1 FROM t 27 | WHERE condition; 28 | ``` 29 | 30 | - Sort the result set in ascending or descending order 31 | 32 | ```SQL 33 | SELECT c1, c2 FROM t 34 | ORDER BY c1 ASC [DESC]; 35 | ``` 36 | 37 | - Skip offset of rows and return the next n rows 38 | 39 | 40 | ```SQL 41 | SELECT c1, c2 FROM t 42 | ORDER BY c1 43 | LIMIT n OFFSET offset; 44 | 45 | ``` 46 | 47 | - Group rows using an aggregate function 48 | 49 | ```SQL 50 | SELECT c1, aggregate(c2) 51 | FROM t 52 | GROUP BY c1; 53 | ``` 54 | 55 | - Filter groups using HAVING clause 56 | 57 | ```SQL 58 | SELECT c1, aggregate(c2) 59 | FROM t 60 | GROUP BY c1 61 | HAVING condition; 62 | ``` 63 | 64 | - Querying from multiple tables 65 | - Inner join t1 and t2 66 | ```SQL 67 | SELECT c1, c2 68 | FROM t1 69 | INNER JOIN t2 ON condition; 70 | ``` 71 | 72 | - Left join t1 and t1 73 | ```SQL 74 | SELECT c1, c2 75 | FROM t1 76 | LEFT JOIN t2 ON condition; 77 | ``` 78 | 79 | - Right join t1 and t2 80 | ```SQL 81 | SELECT c1, c2 82 | FROM t1 83 | RIGHT JOIN t2 ON condition; 84 | ``` 85 | - Perform full outer join 86 | ```SQL 87 | SELECT c1, c2 88 | FROM t1 89 | FULL OUTER JOIN t2 ON condition; 90 | ``` 91 | 92 | - Produce a Cartesian product of rows in tables 93 | ```SQL 94 | SELECT c1, c2 95 | FROM t1 96 | CROSS JOIN t2; 97 | ``` 98 | 99 | - Another way to perform cross join 100 | ```SQL 101 | SELECT c1, c2 102 | FROM t1, t2; 103 | ``` 104 | 105 | - Join t1 to itself using INNER JOIN clause 106 | ```SQL 107 | SELECT c1, c2 108 | FROM t1 A 109 | INNER JOIN t1 B ON condition; 110 | ``` 111 | 112 | - Using SQL Operators 113 | - Combine rows from two queries 114 | ```SQL 115 | SELECT c1, c2 FROM t1 116 | UNION [ALL] 117 | SELECT c1, c2 FROM t2; 118 | ``` 119 | 120 | - Return the intersection of two queries 121 | 122 | ```SQL 123 | SELECT c1, c2 FROM t1 124 | INTERSECT 125 | SELECT c1, c2 FROM t2; 126 | ``` 127 | - Subtract a result set from another result set 128 | 129 | ```SQL 130 | SELECT c1, c2 FROM t1 131 | MINUS 132 | SELECT c1, c2 FROM t2; 133 | ``` 134 | 135 | - Query rows using pattern matching %, _ 136 | 137 | ```SQL 138 | SELECT c1, c2 FROM t1 139 | WHERE c1 [NOT] LIKE pattern; 140 | ``` 141 | 142 | - Query rows in a list 143 | 144 | ```SQL 145 | SELECT c1, c2 FROM t 146 | WHERE c1 [NOT] IN value_list; 147 | ``` 148 | 149 | - Query rows between two values 150 | 151 | ```SQL 152 | SELECT c1, c2 FROM t 153 | WHERE c1 BETWEEN low AND high; 154 | ``` 155 | 156 | - Check if values in a table is NULL or not 157 | 158 | ```SQL 159 | SELECT c1, c2 FROM t 160 | WHERE c1 IS [NOT] NULL; 161 | ``` 162 | 163 | - Managing tables 164 | 165 | - Create a new table with three columns 166 | 167 | ```SQL 168 | CREATE TABLE t ( 169 | id INT PRIMARY KEY, 170 | name VARCHAR NOT NULL, 171 | price INT DEFAULT 0 172 | ); 173 | ``` 174 | 175 | - Delete the table from the database 176 | 177 | ```SQL 178 | DROP TABLE t ; 179 | ``` 180 | 181 | - Add a new column to the table 182 | 183 | ```SQL 184 | ALTER TABLE t ADD column; 185 | ``` 186 | 187 | - Drop column c from the table 188 | 189 | ```SQL 190 | ALTER TABLE t DROP COLUMN c ; 191 | ``` 192 | 193 | - Add a constraint 194 | 195 | ```SQL 196 | ALTER TABLE t ADD constraint; 197 | ``` 198 | 199 | - Drop a constraint 200 | 201 | ```SQL 202 | ALTER TABLE t DROP constraint; 203 | ``` 204 | 205 | - Rename a table from t1 to t2 206 | 207 | ```SQL 208 | ALTER TABLE t1 RENAME TO t2; 209 | ``` 210 | 211 | - Rename column c1 to c2 212 | 213 | ```SQL 214 | ALTER TABLE t1 RENAME c1 TO c2 ; 215 | ``` 216 | 217 | - Remove all data in a table 218 | 219 | ```SQL 220 | TRUNCATE TABLE t; 221 | ``` 222 | 223 | - Using SQL constraints 224 | - Set c1 and c2 as a primary key 225 | 226 | ```SQL 227 | CREATE TABLE t( 228 | c1 INT, c2 INT, c3 VARCHAR, 229 | PRIMARY KEY (c1,c2) 230 | ); 231 | ``` 232 | 233 | - Set c2 column as a foreign key 234 | 235 | ```SQL 236 | CREATE TABLE t1( 237 | c1 INT PRIMARY KEY, 238 | c2 INT, 239 | FOREIGN KEY (c2) REFERENCES t2(c2) 240 | ); 241 | ``` 242 | 243 | - Make the values in c1 and c2 unique 244 | 245 | ```SQL 246 | CREATE TABLE t( 247 | c1 INT, c1 INT, 248 | UNIQUE(c2,c3) 249 | ); 250 | ``` 251 | 252 | - Ensure c1 > 0 and values in c1 >= c2 253 | 254 | ```SQL 255 | CREATE TABLE t( 256 | c1 INT, c2 INT, 257 | CHECK(c1> 0 AND c1 >= c2) 258 | ); 259 | ``` 260 | 261 | - Set values in c2 column not NULL 262 | 263 | ```SQL 264 | CREATE TABLE t( 265 | c1 INT PRIMARY KEY, 266 | c2 VARCHAR NOT NULL 267 | ); 268 | ``` 269 | 270 | - Modifying Data 271 | 272 | - Insert one row into a table 273 | ```SQL 274 | INSERT INTO t(column_list) 275 | VALUES(value_list); 276 | ``` 277 | 278 | - Insert multiple rows into a table 279 | ```SQL 280 | INSERT INTO t(column_list) 281 | VALUES (value_list), 282 | (value_list), …; 283 | ``` 284 | 285 | - Insert rows from t2 into t1 286 | ```SQL 287 | INSERT INTO t1(column_list) 288 | SELECT column_list 289 | FROM t2; 290 | ``` 291 | 292 | - Update new value in the column c1 for all rows 293 | ```SQL 294 | UPDATE t 295 | SET c1 = new_value; 296 | ``` 297 | 298 | - Update values in the column c1, c2 that match the condition 299 | ```SQL 300 | UPDATE t 301 | SET c1 = new_value, 302 | c2 = new_value 303 | WHERE condition; 304 | ``` 305 | 306 | - Delete all data in a table 307 | ```SQL 308 | DELETE FROM t; 309 | ``` 310 | 311 | - Delete subset of rows in a table 312 | ```SQL 313 | DELETE FROM t 314 | WHERE condition; 315 | ``` 316 | 317 | - Managing Views 318 | 319 | - Create a new view that consists of c1 and c2 320 | ```SQL 321 | CREATE VIEW v(c1,c2) 322 | AS 323 | SELECT c1, c2 324 | FROM t; 325 | ``` 326 | 327 | - Create a new view with check option 328 | ```SQL 329 | CREATE VIEW v(c1,c2) 330 | AS 331 | SELECT c1, c2 332 | FROM t; 333 | WITH [CASCADED | LOCAL] CHECK OPTION; 334 | ``` 335 | 336 | - Create a recursive view 337 | ```SQL 338 | CREATE RECURSIVE VIEW v 339 | AS 340 | select-statement -- anchor part 341 | UNION [ALL] 342 | select-statement; -- recursive part 343 | ``` 344 | 345 | - Create a temporary view 346 | ```SQL 347 | CREATE TEMPORARY VIEW v 348 | AS 349 | SELECT c1, c2 350 | FROM t; 351 | ``` 352 | 353 | - Delete a view 354 | ```SQL 355 | DROP VIEW view_name; 356 | ``` 357 | 358 | - Managing indexes 359 | 360 | - Create an index on c1 and c2 of the t table 361 | ```SQL 362 | CREATE INDEX idx_name 363 | ON t(c1,c2); 364 | ``` 365 | - Create a unique index on c3, c4 of the t table 366 | ```SQL 367 | CREATE UNIQUE INDEX idx_name 368 | ON t(c3,c4) 369 | ``` 370 | 371 | - Drop an index 372 | ```SQL 373 | DROP INDEX idx_name; 374 | ``` 375 | 376 | - Managing triggers 377 | - Create or modify a trigger 378 | 379 | ```SQL 380 | CREATE OR MODIFY TRIGGER trigger_name 381 | WHEN EVENT 382 | ON table_name TRIGGER_TYPE 383 | EXECUTE stored_procedure; 384 | ``` 385 | -------------------------------------------------------------------------------- /Cheatsheet/SpecialFunctions/Readme.md: -------------------------------------------------------------------------------- 1 | ### This function, dense_rank(), will rank every row in a partition with no gaps. In essence, the ranks are given in a sequential order. 2 | ```SQL 3 | SELECT student_name, total_marks, dense_rank() 4 | OVER ( order by total_marks desc ) 5 | AS 'dense_rank' FROM school_result; 6 | 7 | ``` 8 | 9 | ### Within a partition with gaps, function rank() will rank each row. In this case, ranks are given out in a random order. 10 | ```SQL 11 | SELECT student_name, total_marks, rank() 12 | OVER ( order by total_marks desc ) 13 | AS 'rank' FROM school_result; 14 | ``` 15 | -------------------------------------------------------------------------------- /HackerRank/README.md: -------------------------------------------------------------------------------- 1 | # HackerRank SQL Solutions 2 | 3 | # Subdomains Wise Questions 4 | 5 | ## Basic Select 6 | - [Revising the Select Query I](https://www.hackerrank.com/challenges/revising-the-select-query/problem) 7 | ```SQL 8 | select * from CITY where COUNTRYCODE = 'USA' AND POPULATION > 100000; 9 | ``` 10 | 11 | - [Revising the Select Query II](https://www.hackerrank.com/challenges/revising-the-select-query-2) 12 | ```SQL 13 | select NAME from CITY where COUNTRYCODE = 'USA' AND POPULATION > 120000; 14 | ``` 15 | 16 | - [Select All](https://www.hackerrank.com/challenges/select-all-sql) 17 | ```SQL 18 | select * from CITY; 19 | ``` 20 | 21 | - [Select By ID](https://www.hackerrank.com/challenges/select-by-id) 22 | ```SQL 23 | select * from CITY where ID = 1661; 24 | ``` 25 | 26 | - [Japanese Cities' Attributes](https://www.hackerrank.com/challenges/japanese-cities-attributes) 27 | ```SQL 28 | select * from CITY where COUNTRYCODE = 'JPN'; 29 | ``` 30 | 31 | - [Japanese Cities' Names](https://www.hackerrank.com/challenges/japanese-cities-name) 32 | ```SQL 33 | select NAME from CITY where COUNTRYCODE = 'JPN'; 34 | ``` 35 | 36 | - [Weather Observation Station 1](https://www.hackerrank.com/challenges/weather-observation-station-1) 37 | ```SQL 38 | select CITY, STATE from STATION; 39 | ``` 40 | 41 | - [Weather Observation Station 3](https://www.hackerrank.com/challenges/weather-observation-station-3) 42 | ```SQL 43 | select distinct(CITY) from STATION where MOD(ID,2) = 0; 44 | ``` 45 | 46 | - [Weather Observation Station 4](https://www.hackerrank.com/challenges/weather-observation-station-4) 47 | ```SQL 48 | select COUNT(CITY) - COUNT(DISTINCT(CITY)) from STATION; 49 | ``` 50 | 51 | - [Weather Observation Station 5](https://www.hackerrank.com/challenges/weather-observation-station-5) 52 | ```SQL 53 | select city, length(city) from station 54 | order by length(city),city asc 55 | limit 1; 56 | select city, length(city) from station 57 | order by length(city) desc 58 | limit 1; 59 | ``` 60 | 61 | - [Weather Observation Station 6](https://www.hackerrank.com/challenges/weather-observation-station-6) 62 | ```SQL 63 | select distinct city from station 64 | where left(city,1) in ('a','e','i','o','u') 65 | ``` 66 | 67 | - [Weather Observation Station 7](https://www.hackerrank.com/challenges/weather-observation-station-7) 68 | ```SQL 69 | select distinct CITY from STATION where (CITY LIKE '%a' OR CITY LIKE '%e' OR CITY LIKE '%i' OR CITY LIKE '%u' OR CITY LIKE '%o'); 70 | ``` 71 | 72 | - [Weather Observation Station 8](https://www.hackerrank.com/challenges/weather-observation-station-8) 73 | ```SQL 74 | select distinct city from station 75 | where left(city,1) in ('a','e','i','o','u') 76 | and right(city, 1) in ('a','e','i','o','u') 77 | ``` 78 | 79 | - [Weather Observation Station 9](https://www.hackerrank.com/challenges/weather-observation-station-9) 80 | ```SQL 81 | select distinct city from station 82 | where left(city,1) NOT in ('a','e','i','o','u') 83 | ``` 84 | 85 | - [Weather Observation Station 10](https://www.hackerrank.com/challenges/weather-observation-station-10) 86 | ```SQL 87 | select distinct city from station where right(city, 1) NOT in ('a','e','i','o','u'); 88 | ``` 89 | 90 | - [Weather Observation Station 11](https://www.hackerrank.com/challenges/weather-observation-station-11) 91 | ```SQL 92 | select distinct CITY from STATION where left(CITY,1) NOT IN ('a','e','i','o','u') OR right(CITY,1) NOT IN ('a','e','i','o','u'); 93 | ``` 94 | 95 | - [Weather Observation Station 12](https://www.hackerrank.com/challenges/weather-observation-station-12) 96 | ```SQL 97 | select distinct CITY from STATION where left(CITY,1) NOT IN ('a','e','i','o','u') AND right(CITY,1) NOT IN ('a','e','i','o','u'); 98 | ``` 99 | 100 | - [Higher Than 75 Marks](https://www.hackerrank.com/challenges/more-than-75-marks) 101 | ```SQL 102 | select name from students where marks > 75 order by substr(name,length(name)-2, 3), id; 103 | ``` 104 | 105 | - [Employee Names](https://www.hackerrank.com/challenges/name-of-employees) 106 | ```SQL 107 | select name from employee order by name asc; 108 | ``` 109 | 110 | - [Employee Salaries](https://www.hackerrank.com/challenges/salary-of-employees) 111 | ```SQL 112 | select name from employee where salary > 2000 AND months < 10 order by employee_id; 113 | ``` 114 | 115 | ## Advanced Select 116 | - [Type of Triangle](https://www.hackerrank.com/challenges/what-type-of-triangle) 117 | ```SQL 118 | SELECT CASE WHEN A + B > C AND A+C>B AND B+C>A THEN CASE WHEN A = B AND B = C THEN 'Equilateral' WHEN A = B OR B = C OR A = C THEN 'Isosceles' WHEN A != B OR B != C OR A != C THEN 'Scalene' END ELSE 'Not A Triangle' END FROM TRIANGLES; 119 | ``` 120 | 121 | - [The PADS](https://www.hackerrank.com/challenges/the-pads) 122 | ```SQL 123 | select concat(name,'(',substr(occupation,1,1),')') from occupations order by name; 124 | select concat('There are a total of ',count(*),' ',lower(occupation),'s.') from occupations group by occupation order by count(*), occupation; 125 | ``` 126 | 127 | - [Binary Tree Nodes](https://www.hackerrank.com/challenges/binary-search-tree-1) 128 | ```SQL 129 | SELECT case 130 | when P IS NULL THEN CONCAT(N, ' Root') 131 | when N IN (SELECT DISTINCT P FROM BST) THEN CONCAT(N, ' Inner') 132 | ELSE CONCAT(N, ' Leaf') 133 | END 134 | FROM BST 135 | ORDER BY N ASC 136 | ``` 137 | 138 | ## Aggregation 139 | - [Revising Aggregations - The Count Function](https://www.hackerrank.com/challenges/revising-aggregations-the-count-function) 140 | ```SQL 141 | select COUNT(ID) from CITY where POPULATION > 100000; 142 | ``` 143 | 144 | - [Revising Aggregations - The Sum Function](https://www.hackerrank.com/challenges/revising-aggregations-sum) 145 | ```SQL 146 | select SUM(POPULATION) from CITY where DISTRICT = 'California'; 147 | ``` 148 | 149 | - [Revising Aggregations - Averages](https://www.hackerrank.com/challenges/revising-aggregations-the-average-function) 150 | ```SQL 151 | select AVG(POPULATION) from CITY where DISTRICT = 'California'; 152 | ``` 153 | 154 | - [Average Population](https://www.hackerrank.com/challenges/average-population) 155 | ```SQL 156 | select FLOOR(AVG(POPULATION)) from CITY; 157 | ``` 158 | 159 | - [Japan Population](https://www.hackerrank.com/challenges/japan-population/problem) 160 | ```SQL 161 | select SUM(POPULATION) from CITY where countrycode='JPN'; 162 | ``` 163 | 164 | - [Population Density Difference](https://www.hackerrank.com/challenges/population-density-difference/problem) 165 | ```SQL 166 | select max(population) - min(population) from CITY; 167 | ``` 168 | 169 | - [The Blunder](https://www.hackerrank.com/challenges/the-blunder/problem) 170 | ```SQL 171 | SELECT CEIL(AVG(Salary)-AVG(REPLACE(Salary,'0',''))) FROM EMPLOYEES; 172 | ``` 173 | 174 | - [Top Earners](https://www.hackerrank.com/challenges/earnings-of-employees/problem) 175 | ```SQL 176 | select months*salary as earn, count(*)from employee group by earn order by earn desc limit 1; 177 | ``` 178 | 179 | - [Weather Observation Station 2](https://www.hackerrank.com/challenges/weather-observation-station-2) 180 | ```SQL 181 | select round(sum(lat_n),2), round(sum(long_w),2) from station; 182 | ``` 183 | 184 | - [Weather Observation Station 13](https://www.hackerrank.com/challenges/weather-observation-station-13) 185 | ```SQL 186 | select round(sum(lat_n),4) from station where lat_n > 38.7880 AND lat_n < 137.2345; 187 | ``` 188 | 189 | - [Weather Observation Station 14](https://www.hackerrank.com/challenges/weather-observation-station-14) 190 | ```SQL 191 | select round(max(lat_n),4) from station where lat_n < 137.2345; 192 | ``` 193 | 194 | - [Weather Observation Station 15](https://www.hackerrank.com/challenges/weather-observation-station-15) 195 | ```SQL 196 | select round(long_w,4) from station where lat_n=(select max(lat_n) from station where lat_n < 137.2345); 197 | ``` 198 | 199 | - [Weather Observation Station 16](https://www.hackerrank.com/challenges/weather-observation-station-16) 200 | ```SQL 201 | select min(round(lat_n,4)) from station where lat_n > 38.7780; 202 | ``` 203 | 204 | - [Weather Observation Station 17](https://www.hackerrank.com/challenges/weather-observation-station-17) 205 | ```SQL 206 | select round(long_w,4) from station where lat_n=(select min(lat_n) from station where lat_n > 38.7780); 207 | ``` 208 | 209 | - [Weather Observation Station 18](https://www.hackerrank.com/challenges/weather-observation-station-18) 210 | ```SQL 211 | SELECT ROUND( MAX(lat_n)-MIN(lat_n) + MAX(long_w)-MIN(long_w), 4) FROM Station; 212 | ``` 213 | 214 | - [Weather Observation Station 19](https://www.hackerrank.com/challenges/weather-observation-station-19) 215 | ```SQL 216 | SELECT ROUND( 217 | SQRT( 218 | POWER((MAX(lat_n)-MIN(lat_n)), 2) 219 | + POWER((MAX(long_w)-MIN(long_w)), 2) 220 | ), 221 | 4) FROM Station; 222 | ``` 223 | 224 | - [Weather Observation Station 20](https://www.hackerrank.com/challenges/weather-observation-station-20) 225 | ```SQL 226 | select round(s.lat_n, 4) from station s where (select count(lat_n) from station where s.lat_n > lat_n ) = (select count(lat_n) from station where s.lat_n < lat_n ); 227 | ``` 228 | 229 | ## Basic Join 230 | - [Population Census](https://www.hackerrank.com/challenges/asian-population) 231 | ```SQL 232 | select sum(c.population) from city c, country d where c.countrycode = d.code AND d.continent ='Asia'; 233 | ``` 234 | 235 | - [African Cities](https://www.hackerrank.com/challenges/african-cities) 236 | ```SQL 237 | select c.name from city c, country d where c.countrycode = d.code AND d.continent ='Africa'; 238 | ``` 239 | 240 | - [Average Population of Each Continent](https://www.hackerrank.com/challenges/average-population-of-each-continent) 241 | ```SQL 242 | select d.continent, floor(avg(c.population)) from city c, country d where c.countrycode = d.code group by d.continent; 243 | ``` 244 | 245 | - [The Report](https://www.hackerrank.com/challenges/the-report) 246 | ```SQL 247 | select if(g.grade<8, 'NULL', s.name), g.grade, s.marks from students as s, grades as g where s.marks between g.min_mark and g.max_mark order by g.grade desc, s.name; 248 | ``` 249 | 250 | - [Contest Leaderboard](https://www.hackerrank.com/challenges/contest-leaderboard) 251 | ```SQL 252 | select h.hacker_id, name, sum(score) as total_score 253 | from 254 | hackers as h inner join 255 | (select hacker_id, max(score) as score from submissions group by challenge_id, hacker_id) max_score 256 | on h.hacker_id=max_score.hacker_id 257 | group by h.hacker_id, name 258 | having total_score > 0 259 | order by total_score desc, h.hacker_id; 260 | ``` 261 | 262 | ## Advanced Join 263 | - [Interviews](https://www.hackerrank.com/challenges/interviews/problem) 264 | ```SQL 265 | select con.contest_id, 266 | con.hacker_id, 267 | con.name, 268 | sum(total_submissions), 269 | sum(total_accepted_submissions), 270 | sum(total_views), sum(total_unique_views) 271 | from contests con 272 | join colleges col on con.contest_id = col.contest_id 273 | join challenges cha on col.college_id = cha.college_id 274 | left join 275 | (select challenge_id, sum(total_views) as total_views, sum(total_unique_views) as total_unique_views 276 | from view_stats group by challenge_id) vs on cha.challenge_id = vs.challenge_id 277 | left join 278 | (select challenge_id, sum(total_submissions) as total_submissions, sum(total_accepted_submissions) as total_accepted_submissions from submission_stats group by challenge_id) ss on cha.challenge_id = ss.challenge_id 279 | group by con.contest_id, con.hacker_id, con.name 280 | having sum(total_submissions)!=0 or 281 | sum(total_accepted_submissions)!=0 or 282 | sum(total_views)!=0 or 283 | sum(total_unique_views)!=0 284 | order by contest_id; 285 | ``` 286 | 287 | - [15 Days of Learning SQL](https://www.hackerrank.com/challenges/15-days-of-learning-sql/problem) 288 | ```SQL 289 | select 290 | submission_date , 291 | 292 | ( SELECT COUNT(distinct hacker_id) 293 | FROM Submissions s2 294 | WHERE s2.submission_date = s1.submission_date AND (SELECT COUNT(distinct s3.submission_date) FROM Submissions s3 WHERE s3.hacker_id = s2.hacker_id AND s3.submission_date < s1.submission_date) = dateDIFF(s1.submission_date , '2016-03-01')) , 295 | 296 | (select hacker_id from submissions s2 where s2.submission_date = s1.submission_date 297 | group by hacker_id order by count(submission_id) desc , hacker_id limit 1) as shit, 298 | (select name from hackers where hacker_id = shit) 299 | from 300 | (select distinct submission_date from submissions) s1 301 | group by submission_date 302 | ``` 303 | 304 | - [SQL Project Planning](https://www.hackerrank.com/challenges/sql-projects/problem) 305 | ```SQL 306 | 307 | SET sql_mode = ''; 308 | SELECT Start_Date, End_Date 309 | FROM 310 | (SELECT Start_Date FROM Projects WHERE Start_Date NOT IN (SELECT End_Date FROM Projects)) a, 311 | (SELECT End_Date FROM Projects WHERE End_Date NOT IN (SELECT Start_Date FROM Projects)) b 312 | WHERE Start_Date < End_Date 313 | GROUP BY Start_Date 314 | ORDER BY DATEDIFF(End_Date, Start_Date), Start_Date 315 | 316 | ``` 317 | 318 | - []() 319 | ```SQL 320 | ``` 321 | 322 | - []() 323 | ```SQL 324 | ``` 325 | 326 | ## Alternative Queries 327 | - [Draw The Triangle 1](https://www.hackerrank.com/challenges/draw-the-triangle-1) 328 | ```SQL 329 | DECLARE @i INT = 20 330 | WHILE (@i > 0) 331 | BEGIN 332 | PRINT REPLICATE('* ', @i) 333 | SET @i = @i - 1 334 | END 335 | ``` 336 | 337 | - [Draw The Triangle 2](https://www.hackerrank.com/challenges/draw-the-triangle-2) 338 | ```SQL 339 | DECLARE @i INT = 1 340 | WHILE (@i < 21) 341 | BEGIN 342 | PRINT REPLICATE('* ', @i) 343 | SET @i = @i + 1 344 | END 345 | ``` 346 | 347 | - [Print Prime Numbers](https://www.hackerrank.com/challenges/print-prime-numbers) 348 | ```SQL 349 | SELECT GROUP_CONCAT(NUMB SEPARATOR '&') 350 | FROM ( 351 | SELECT @num:=@num+1 as NUMB FROM 352 | information_schema.tables t1, 353 | information_schema.tables t2, 354 | (SELECT @num:=1) tmp 355 | ) tempNum 356 | WHERE NUMB<=1000 AND NOT EXISTS( 357 | SELECT * FROM ( 358 | SELECT @nu:=@nu+1 as NUMA FROM 359 | information_schema.tables t1, 360 | information_schema.tables t2, 361 | (SELECT @nu:=1) tmp1 362 | LIMIT 1000 363 | ) tatata 364 | WHERE FLOOR(NUMB/NUMA)=(NUMB/NUMA) AND NUMA1 365 | ) 366 | 367 | ``` 368 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Srimanta11 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 | -------------------------------------------------------------------------------- /LeetCode/Readme.md: -------------------------------------------------------------------------------- 1 | ## LeetCode SQL Solutions 2 | 3 | 1. [Combine Two Tables](https://leetcode.com/problems/combine-two-tables/) 4 | ```SQL 5 | SELECT Person.FirstName, Person.LastName, Address.City, Address.State 6 | from Person LEFT JOIN Address on Person.PersonId = Address.PersonId; 7 | ``` 8 | 9 | 2. [Second Highest Salary](https://leetcode.com/problems/second-highest-salary/) 10 | ```SQL 11 | SELECT max(Salary) as SecondHighestSalary 12 | FROM Employee 13 | WHERE Salary < (SELECT max(Salary) FROM Employee) 14 | ``` 15 | 16 | 3. [Nth Highest Salary](https://leetcode.com/problems/nth-highest-salary/) 17 | ```SQL 18 | CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 19 | BEGIN 20 | DECLARE M INT; 21 | SET M=N-1; 22 | RETURN ( 23 | SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT M, 1 24 | ); 25 | END 26 | ``` 27 | 28 | 29 | 4. [Employees Earning More Than Their Managers](https://leetcode.com/problems/employees-earning-more-than-their-managers/) 30 | ```SQL 31 | select name as Employee 32 | from Employee as e1 33 | where salary > (select salary from Employee as e2 where e2.id = e1.managerId ) 34 | ``` 35 | 36 | 5. [Duplicate Emails](https://leetcode.com/problems/duplicate-emails/) 37 | ```SQL 38 | select email 39 | from Person 40 | group by email 41 | having count(email) > 1 42 | ``` 43 | 44 | 6. [Customers Who Never Order](https://leetcode.com/problems/customers-who-never-order/) 45 | ```SQL 46 | select name as Customers 47 | from Customers where id NOT in (select customerId from Orders) 48 | ``` 49 | 50 | 7. [Department Highest Salary](https://leetcode.com/problems/department-highest-salary/) 51 | ```SQL 52 | SELECT d.name AS Department, e.name AS Employee, e.salary AS Salary 53 | FROM Employee e, Department d 54 | WHERE e.departmentId = d.id 55 | AND (e.departmentId, e.salary) in 56 | (SELECT DepartmentId, max(Salary) as max FROM Employee GROUP BY DepartmentId) 57 | ``` 58 | 59 | 8. [Department Top Three Salaries](https://leetcode.com/problems/department-top-three-salaries/) 60 | ```SQL 61 | SELECT d.Name AS Department, e.Name AS Employee , e.Salary 62 | FROM Employee AS e, Employee as e1, Department AS d 63 | WHERE e.DepartmentId = d.Id 64 | AND e1.DepartmentId = e.DepartmentId 65 | AND e1.Salary >= e.Salary 66 | GROUP BY e.Id 67 | HAVING COUNT(DISTINCT e1.Salary) <= 3; 68 | ``` 69 | 70 | 9. [Delete Duplicate Emails](https://leetcode.com/problems/delete-duplicate-emails/) 71 | ```SQL 72 | DELETE p1 73 | FROM Person p1, Person p2 74 | WHERE p1.Email = p2.Email AND 75 | p1.Id > p2.Id 76 | ``` 77 | 78 | 10. [Rising Temperature](https://leetcode.com/problems/rising-temperature/) 79 | ```SQL 80 | SELECT wt1.Id 81 | FROM Weather wt1, Weather wt2 82 | WHERE wt1.Temperature > wt2.Temperature AND 83 | TO_DAYS(wt1.recordDate)-TO_DAYS(wt2.recordDate)=1; 84 | ``` 85 | 86 | 11. [Trips and Users](https://leetcode.com/problems/trips-and-users/) 87 | ```SQL 88 | select t.Request_at Day, 89 | ROUND((count(IF(t.status!='completed',TRUE,null))/count(*)),2) as 'Cancellation Rate' 90 | from Trips t where 91 | t.Client_Id in (Select Users_Id from Users where Banned='No') 92 | and t.Driver_Id in (Select Users_Id from Users where Banned='No') 93 | and t.Request_at between '2013-10-01' and '2013-10-03' 94 | group by t.Request_at; 95 | ``` 96 | 97 | 12. [Find Customer Referee](https://leetcode.com/problems/find-customer-referee/) 98 | ```SQL 99 | select name from customer where referee_id <> 2 OR referee_id IS NULL 100 | ``` 101 | 102 | 13. [Customer Placing the Largest Number of Orders](https://leetcode.com/problems/customer-placing-the-largest-number-of-orders/) 103 | ```SQL 104 | select customer_number from orders 105 | group by customer_number 106 | order by count(order_number) desc limit 1; 107 | ``` 108 | 109 | 14. [Big Countries](https://leetcode.com/problems/big-countries/) 110 | ```SQL 111 | select name, population, area from world 112 | where area >= 3000000 or population >= 25000000 113 | ``` 114 | 115 | 15. [Sales Person](https://leetcode.com/problems/sales-person/) 116 | ```SQL 117 | SELECT name from salesperson 118 | where sales_id not in 119 | ( 120 | select sales_id from orders where com_id in 121 | (select com_id from company where name='RED') 122 | ) 123 | ``` 124 | 125 | 16. [Tree Node](https://leetcode.com/problems/tree-node/) 126 | ```SQL 127 | SELECT id, 128 | IF (p_id IS NULL, "Root", 129 | IF (id IN (SELECT p_id FROM Tree), "Inner", "Leaf") 130 | ) AS type 131 | FROM Tree 132 | ``` 133 | 134 | 17. [Swap Salary](https://leetcode.com/problems/swap-salary/) 135 | ```SQL 136 | UPDATE salary SET sex = IF(sex = 'm', 'f', 'm') 137 | ``` 138 | 139 | 18. [Actors and Directors Who Cooperated At Least Three Times](https://leetcode.com/problems/actors-and-directors-who-cooperated-at-least-three-times/) 140 | ```SQL 141 | select actor_id, director_id 142 | from ActorDirector 143 | group by actor_id, director_id 144 | having count(timestamp) > 2 145 | ``` 146 | 147 | 19. [Sales Analysis III](https://leetcode.com/problems/sales-analysis-iii/) 148 | ```SQL 149 | SELECT s.product_id, product_name 150 | FROM Sales s 151 | LEFT JOIN Product p 152 | ON s.product_id = p.product_id 153 | GROUP BY s.product_id 154 | HAVING MIN(sale_date) >= CAST('2019-01-01' AS DATE) AND 155 | MAX(sale_date) <= CAST('2019-03-31' AS DATE) 156 | ``` 157 | 158 | 20. [Game Play Analysis I](https://leetcode.com/problems/game-play-analysis-i/) 159 | ```SQL 160 | select player_id, min(event_date) as first_login 161 | from activity 162 | group by player_id 163 | ``` 164 | 165 | . []() 166 | ```SQL 167 | ``` 168 | 169 | 170 | 171 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SQL/MySQL 2 | 3 | ## Cheatsheets 4 | - [SQL](https://github.com/Sayan3990/SQL/tree/main/Cheatsheet/SQL) 5 | - [MySQL](https://github.com/Sayan3990/SQL/tree/main/Cheatsheet/MySQL) 6 | 7 | ## Practice Questions 8 | - HackerRank [SQL Solutions](https://github.com/Srimanta11/SQL/tree/main/HackerRank) 9 | - LeetCode [SQL Solutions](https://github.com/Srimanta11/SQL/tree/main/LeetCode) 10 | 11 | 12 | ## License 13 | - Distributed under the MIT License. See `LICENSE` for more information. 14 | 15 | ### Hope this will be helpful 16 | #### Thank you for visiting 17 | --------------------------------------------------------------------------------