Advertisement
Guest User

Untitled

a guest
Mar 1st, 2019
713
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 34.42 KB | None | 0 0
  1. mysql-ctl start /* c9 command for start */
  2. mysql-ctl cli /* c9 command for cli */
  3. mysql-ctl stop /* c9 command for stop */
  4.  
  5. show databases;
  6. create database db_name; /* make a new database */
  7. use db_name; /* use the database */
  8. SELECT database(); /* check which database is used/active */
  9. drop database db_name; /* delete the database */
  10.  
  11.  
  12. CREATE TABLE tablename /* make a new table */
  13. (
  14. column_name data_type,
  15. column_name data_type
  16. );
  17.  
  18. CREATE TABLE cats /* make a new table called cats */
  19. (
  20. name VARCHAR(100),
  21. age INT
  22. );
  23. show tables; /* show table currently used */
  24. show columns from cats; /* show columns from cats in table format */
  25. DESC cats; /* show(or describe) columns from cats in table format */
  26. DROP TABLE cats; /* delete the table */
  27.  
  28. INSERT INTO cats(name, age)
  29. VALUES ('Jetson', 7);
  30. /* or */
  31. INSERT INTO cats(age, name) VALUES (12, 'Victoria');
  32. /* or */
  33. INSERT INTO cats(name, age)
  34. VALUES ('Charlie', 10),
  35. ('Sadie', 3),
  36. ('Lazy Bear', 1);
  37. SELECT * FROM cats; /* view the values from the table called cats in table format */
  38.  
  39.  
  40. CREATE TABLE people (first_name VARCHAR(20), last_name VARCHAR(20), age INT);
  41. INSERT INTO people (age, first_name, last_name) VALUES (13, 'Tina', 'Belcher');
  42. SELECT * FROM people;
  43.  
  44. INSERT INTO people (first_name, last_name, age)
  45. VALUES ('Linda', 'Belcher', 45),
  46. ('Phillip', 'Frond', 38),
  47. ('Calvin', 'Fischoeder', 70);
  48.  
  49. SHOW WARNINGS; /* if there's a warning, will show the warnings */
  50.  
  51. CREATE TABLE cats2 (name VARCHAR(100) NOT NULL, age INT NOT NULL); /* requires values or data */
  52. INSERT INTO cats2(name) VALUES('Texas'); /* no age will produce warning and value 0 for age */
  53. INSERT INTO cats2(age) VALUES(7); /* no name will produce warning and '' empty string for name */
  54.  
  55. CREATE TABLE cats3 (name VARCHAR(100) DEFAULT 'unnamed', age INT DEFAULT 99);
  56.  
  57. /* Primary Key - when for example name and age have same values but supposedly they are diff
  58. users with similar values ... KEY can identify which is which! (Unique Identifier of a row) */
  59. CREATE TABLE unique_cats (cat_id INT NOT NULL, name VARCHAR(100), age INT,
  60. PRIMARY KEY (cat_id));
  61.  
  62. INSERT INTO unique_cats(cat_id, name, age) VALUES (1, "Fred", 23);
  63. SELECT * FROM unique_cats;
  64. INSERT INTO unique_cats(cat_id, name, age) VALUES (2, "Louise", 3);
  65.  
  66. CREATE TABLE cats4 (cat_id INT NOT NULL AUTO_INCREMENT, name VARCHAR(100), age INT, PRIMARY KEY(cat_id));
  67.  
  68. CREATE TABLE employees2(
  69. emp_id INT NOT NULL AUTO_INCREMENT
  70. , last_name VARCHAR(50) NOT NULL
  71. , first_name VARCHAR(50) NOT NULL
  72. , middle_name VARCHAR(50)
  73. , age INT NOT NULL
  74. , current_status VARCHAR(50) NOT NULL DEFAULT 'Employed',
  75. Primary KEY (emp_id));
  76.  
  77. /* CRUD - Create Read Update Delete */
  78.  
  79. CREATE TABLE cats(
  80. cat_id INT NOT NULL AUTO_INCREMENT,
  81. name VARCHAR(100),
  82. breed VARCHAR(100),
  83. age INT,
  84. PRIMARY Key (cat_id)
  85. );
  86.  
  87. INSERT INTO cats(name,breed, age)
  88. VALUES ('Ringo', 'Tabby', 4),
  89. ('Cindy', 'Maine Coon', 10),
  90. ('Dumbledore', 'Main Coon', 11),
  91. ('Egg', 'Persian', 4),
  92. ('Misty', 'Tabby', 13),
  93. ('George Michael', 'Ragdoll', 9),
  94. ('Jackson', 'Sphynx', 7);
  95.  
  96. SELECT * FROM cats WHERE age=4;
  97. SELECT * FROM cats WHERE name='egG'; /* by default NOT CASE SENSITIVE so will get 1 query */
  98. SELECT cat_id FROM cats;
  99. SELECT name, breed FROM cats;
  100. SELECT name, age FROM cats WHERE breed='Tabby';
  101. SELECT cat_id, age FROM cats WHERE cat_id=age;
  102. SELECT * FROM cats WHERE cat_id=age;
  103.  
  104. SELECT cat_id as ID, name FROM cats; /* Alias for cat_id is ID */
  105.  
  106. UPDATE cats SET breed = 'Shorthair' WHERE breed='Tabby';
  107. UPDATE cats SET age=14 WHERE name='Misty';
  108.  
  109. UPDATE cats SET name='Jack' WHERE name='Jackson';
  110. UPDATE cats SET breed='British Shorthair' WHERE name='Ringo';
  111. UPDATE cats SET breed='Main Coon' WHERE breed='Maine Coon';
  112. SELECT * FROM cats WHERE breed='Main Coon';
  113. UPDATE cats SET age=12 WHERE breed='Main Coon';
  114.  
  115. DELETE FROM cats WHERE name='Egg';
  116. DELETE FROM cats; /* DONT DO THIS AS IT WILL DELETE ALL THE CATS! */
  117.  
  118. /* Delete all 4 year old cats */
  119. Select * From cats where age = 4;
  120. DELETE FROM cats where age = 4;
  121. SELECT * FROM cats;
  122.  
  123. DELETE FROM cats where cat_id=age;
  124.  
  125.  
  126.  
  127. /* Running SQL Files */
  128. mysql-ctl cli
  129. use db_name;
  130. source filename.sql; /* Where filename.sql contains codes to create a table */
  131. DESC tablename;
  132.  
  133. SELECT CONCAT(author_fname, ' ', author_lname) AS 'Full Name' FROM books;
  134. /* or */
  135. SELECT author_fname AS first, author_lname AS last,
  136. CONCAT(author_fname, ' ', author_lname) AS 'Full Name' FROM books;
  137. /* or */
  138. SELECT CONCAT_WS(' - ', title, author_fname, author_lname) FROM books;
  139. SELECT SUBSTRING('Hello World', 1, 4); /* Passes Hell - from char 1 to 4 */
  140. SELECT SUBSTRING('Hello World, 7'); /* Passes World -starts at 7th char*/
  141. SELECT SUBSTRING('Hello World, -3'); /* Passes rld -starts from last char and 3 chars*/
  142. SELECT title FROM books;
  143. SELECT SUBSTRING("Where I'm Calling From: Selected Stories", 1, 10);
  144. SELECT SUBSTRING(title, 1, 10) FROM books;
  145. SELECT SUBSTRING(title, 1, 10) AS 'short title' FROM books;
  146. SELECT SUBSTR(title, 1, 10) AS 'short title' FROM books;
  147. SELECT CONCAT
  148. (
  149. SUBSTRING(title, 1, 10),
  150. '...'
  151. ) AS 'short title'
  152. FROM books;
  153. source book_code.sql
  154.  
  155. /* replacing is CASE SENSITIVE! */
  156. SELECT REPLACE('Hello World', 'l', '7'); /* result is He770 Wor7d */
  157. SELECT REPLACE('cheese bread coffee milk', ' ', ' and ');
  158. SELECT REPLACE(title,'e', '3') AS 'funkytitle' FROM books;
  159.  
  160. SELECT
  161. SUBSTRING(REPLACE(title, 'e', '3'), 1, 10) AS 'weird string'
  162. FROM books;
  163.  
  164. SELECT REVERSE('Hello World'); -- dlroW olleH
  165. SELECT CONCAT(author_fname, REVERSE(author_fname)) FROM books;
  166.  
  167. SELECT CHAR_LENGTH('Hello World');
  168. SELECT author_lname, CHAR_LENGTH(author_lname) AS 'length' FROM books;
  169. SELECT CONCAT(author_lname, ' is ', CHAR_LENGTH(author_lname), ' characters long') FROM books;
  170.  
  171. SELECT UPPER('Hello World'); -- HELLO WORLD
  172. SELECT LOWER('Hello World'); -- hello world
  173. SELECT CONCAT('MY FAVORITE BOOK IS ', UPPER(title)) FROM books;
  174. SELECT CONCAT('MY FAVORITE BOOK IS ', LOWER(title)) FROM books;
  175. SELECT UPPER(CONCAT(author_fname, ' ', author_lname)) AS "full name in caps"
  176. FROM books;
  177.  
  178. INSERT INTO books
  179. (title, author_fname, author_lname, released_year, stock_quantity, pages)
  180. VALUES ('10% Happier', 'Dan', 'Harris', 2014, 29, 256),
  181. ('fake_book', 'Freida', 'Harris', 2001, 287, 428),
  182. ('Lincoln In The Bardo', 'George', 'Saunders', 2017, 1000, 367);
  183.  
  184. SELECT DISTINCT author_lname FROM books;
  185. SELECT DISTINCT released_year FROM books;
  186. SELECT DISTINCT CONCAT(author_fname,' ',author_lname) FROM books;
  187. SELECT DISTINCT author_fname,author_lname FROM books;
  188.  
  189. SELECT author_lname FROM books ORDER BY author_lname;
  190. SELECT title FROM books ORDER BY title DESC; -- where DESC is descending not describe
  191. SELECT title FROM books ORDER BY title; --ascending DEFAULT
  192. SELECT title, released_year, pages FROM books ORDER BY released_year;
  193. SELECT title, pages FROM books ORDER BY released_year;
  194. SELECT title, author_fname, author_lname FROM books ORDER BY 2;
  195. SELECT author_fname, author_lname FROM books ORDER BY author_lname, author_fname;
  196.  
  197. SELECT title, released_year FROM books ORDER BY released_year DESC LIMIT 14; -- where DESC is descending not describe
  198. SELECT title, released_year FROM books ORDER BY released_year DESC LIMIT 5;
  199. SELECT title, released_year FROM books ORDER BY released_year DESC LIMIT 1,3;
  200. SELECT title, released_year FROM books ORDER BY released_year DESC LIMIT 10,1;
  201. SELECT * FROM tbl LIMIT 95,18446744073709551615;
  202.  
  203. SELECT title, author_fname FROM books WHERE author_fname LIKE '%da%';
  204. SELECT title, author_fname FROM books WHERE author_fname LIKE 'da%';
  205.  
  206. SELECT title, stock_quantity FROM books WHERE stock_quantity LIKE '__'; -- 2 underscores will pull ##
  207. -- if searching for actual % or _, use \%
  208. SELECT title FROM books WHERE title LIKE '%\%%'; -- query shows the book with title *10% Happier*
  209.  
  210. -- Select using Range
  211. SELECT * from books WHERE released_year BETWEEN 2000 AND 2018;
  212.  
  213. SELECT COUNT(*) FROM books;
  214. SELECT COUNT(DISTINCT author_fname, author_lname) FROM books; -- count how many unique authors
  215.  
  216. -- how many titles contain 'the'?
  217. SELECT COUNT(*) FROM books WHERE title LIKE '%the%';
  218. -- to manually check:
  219. SELECT title FROM books WHERE title LIKE '%the%';
  220.  
  221.  
  222. -- GROUP BY
  223. SELECT title, author_lname FROM books;
  224. SELECT title, author_lname FROM books GROUP BY author_lname;
  225. SELECT author_lname, COUNT(*) FROM books GROUP BY author_lname;
  226. SELECT CONCAT(author_lname, ' ', author_fname), COUNT(*) FROM books GROUP BY CONCAT(author_lname, ' ', author_fname);
  227. -- or
  228. SELECT author_fname, author_lname, COUNT(*) FROM books GROUP BY author_lname,author_fname;
  229.  
  230. SELECT released_year, COUNT(*) FROM books GROUP BY released_year;
  231. -- or
  232. SELECT CONCAT('In ', released_year, ' ', COUNT(*), ' book(s) released') AS '# of Books Released by Year' FROM books GROUP BY released_year;
  233.  
  234.  
  235. -- Min and Max
  236. --Find the minimum released Year
  237. SELECT MIN(released_year) FROM books;
  238. --Find the maximum released Year
  239. SELECT MAX(released_year) FROM books;
  240. -- Find book with minimum pages and show the title of the book
  241. /* WRONG WAY */ SELECT MIN(pages), title FROM books; /* WRONG WRONG WRONG */
  242. SELECT * FROM books WHERE pages = (SELECT MIN(pages) FROM books); /* 1st RIGHT WAY */
  243. SELECT title, pages FROM books WHERE pages = (SELECT MIN(pages) FROM books); /* 2nd RIGHT WAY */
  244. SELECT * FROM books WHERE pages = 176; /*3rd RIGHT WAY */
  245. SELECT title,pages FROM books ORDER BY pages ASC LIMIT 1; /*4th RIGHT WAY, FASTEST WAY!!! */
  246. --
  247. -- Find the year each author published their first book
  248. SELECT author_fname, author_lname, MIN(released_year) FROM books
  249. GROUP BY author_lname,author_fname;
  250. --
  251. SELECT title, MAX(released_year) FROM books
  252. GROUP BY author_lname,author_fname;
  253. --
  254. -- Find the longest page count for each author
  255. SELECT author_fname, author_lname, MAX(pages) FROM books
  256. GROUP BY author_lname,author_fname;
  257. -- or
  258. SELECT CONCAT(author_fname, ' ', author_lname) AS author,
  259. MAX(pages) AS 'longest book'
  260. FROM books
  261. GROUP BY author_lname, author_fname;
  262.  
  263. -- sum
  264. SELECT Sum(pages) FROM books;
  265. SELECT SUM(released_year) FROM books;
  266. --
  267. -- sum all pages each author has written
  268. SELECT SUM(pages), author_fname, author_lname FROM books
  269. GROUP BY author_lname, author_fname;
  270.  
  271. --average
  272. -- Calcualate the average released_year across all books
  273. SELECT AVG(released_year) FROM books;
  274. --
  275. -- Calculate the average stock quantity for books released in the same Year
  276. SELECT AVG(stock_quantity) FROM books GROUP BY released_year;
  277. SELECT AVG(stock_quantity), released_year FROM books GROUP BY released_year;
  278. SELECT author_fname, author_lname, AVG(pages) FROM books GROUP BY author_lname,author_fname;
  279.  
  280. -- EXERCISES --
  281. -- Print the # of books in the databases
  282. SELECT COUNT(*) FROM books;
  283. -- Print out how many books were released in each year
  284. SELECT released_year, COUNT(*) FROM books GROUP BY released_year;
  285. -- Print out the total number of books in stock_quantity
  286. SELECT SUM(stock_quantity) FROM books;
  287. -- Find the average released_year for each author
  288. SELECT CONCAT(author_fname,' ',author_lname) AS 'AUTHOR',AVG(released_year) AS 'Average Release Year' FROM books GROUP BY author_lname,author_fname;
  289. -- Find the fullname of the author who wrote the longest book title.
  290. SELECT CONCAT(author_fname,' ',author_lname) AS 'AUTHOR', title FROM books ORDER BY LENGTH(TITLE) DESC LIMIT 1;
  291. -- Find the fullname of the author who wrote the longest book (most pages).
  292. SELECT CONCAT(author_fname,' ',author_lname) AS 'AUTHOR', title,pages FROM books WHERE pages = (SELECT MAX(pages) FROM books);
  293. -- or
  294. SELECT CONCAT(author_fname, ' ', author_lname) AS 'AUTHOR', title, pages FROM books ORDER BY pages DESC LIMIT 1;
  295. -- print data with released_year-descending, #books, and average pages
  296. SELECT released_year AS 'year', COUNT(*), AVG(pages) FROM books GROUP by released_year;
  297.  
  298. --CHAR-- has a fixed Length.
  299. CREATE TABLE dogs (name CHAR(5), breed VARCHAR(10));
  300. INSERT INTO dogs (name, breed) VALUES ('bob', 'beagle');
  301. INSERT INTO dogs (name, breed) VALUES ('robby', 'corgi');
  302. INSERT INTO dogs (name, breed) VALUES ('Princess Jane', 'Retriever');
  303. SELECT * FROM dogs;
  304. INSERT INTO dogs (name, breed) VALUES ('Princess Jane', 'Retrievesadfdsafdasfsafr');
  305. SELECT * FROM dogs;
  306.  
  307. -- DECIMAL
  308. CREATE TABLE items (price DECIMAL(5,2));
  309. INSERT INTO items(price) VALUES(7);
  310. INSERT INTO items(price) VALUES(7987654);
  311. INSERT INTO items(price) VALUES(34.88);
  312. INSERT INTO items(price) VALUES(298.9999);
  313. INSERT INTO items(price) VALUES(1.9999);
  314. SELECT * FROM items;
  315.  
  316. CREATE TABLE thingies (price FLOAT);
  317. INSERT INTO thingies(price) VALUES (88.45);
  318. INSERT INTO thingies(price) VALUES (8877.45);
  319. INSERT INTO thingies(price) VALUES (8877665544.45);
  320. SELECT * FROM thingies;
  321.  
  322. -- DATE: YYYY-MM-DD
  323. -- TIME: HH:MM:SS
  324. -- DATETIME: YYYY--MM-DD HH:MM:SS
  325. CREATE TABLE people (name VARCHAR(100), birthdate DATE, birthtime TIME, birthdt DATETIME);
  326. INSERT INTO people (name, birthdate, birthtime, birthdt)
  327. VALUES('Padma', '1983-11-11', '10:07:35', '1983-11-11 10:07:35');
  328. INSERT INTO people (name, birthdate, birthtime, birthdt)
  329. VALUES('Larry', '1943-12-25', '04:10:42', '1943-12-25 04:10:42');
  330. SELECT * FROM people;
  331.  
  332. -- CURDATE() gives current date, CURTIME() gives current time, NOW() -- FYI: the now is current datetime
  333. INSERT INTO people (name, birthdate, birthtime, birthdt) VALUES('Toaster', CURDATE(), CURTIME(), NOW());
  334. SELECT * FROM people;
  335.  
  336. -- DAY(), DAYNAME(), DAYOFWEEK(), DAYOFYEAR(), MONTHNAME(), YEAR(), MINUTE(), ETC.
  337. SELECT DATE_FORMAT(NOW(), '%W %M %D %Y'); -- Check MYSQL documentation for more symbol representations
  338. SELECT CONCAT(MONTHNAME(birthdate), ' ', DAY(birthdate), ' ', YEAR(birthdate)) FROM people;
  339. SELECT DATE_FORMAT(birthdt, 'Was born on a %W') FROM people;
  340. SELECT DATE_FORMAT(birthdt, '%m/%d/%Y') FROM people;
  341. SELECT DATE_FORMAT(birthdt, '%m/%d/%Y at %h:%i') FROM people;
  342.  
  343. -- DATEDIFF(), DATE_ADD, +/-
  344. SELECT name, birthdate, DATEDIFF(NOW(), birthdate) FROM people;
  345. SELECT birthdt, DATE_ADD(birthdt, INTERVAL 3 QUARTER, INTERVAL 2 SECOND) FROM people;
  346. --
  347. SELECT * FROM people;
  348. SELECT DATEDIFF(NOW(), birthdate) FROM people;
  349. SELECT name, birthdate, DATEDIFF(NOW(), birthdate) FROM people;
  350. SELECT birthdt FROM people;
  351. SELECT birthdt, DATE_ADD(birthdt, INTERVAL 1 MONTH) FROM people;
  352. SELECT birthdt, DATE_ADD(birthdt, INTERVAL 10 SECOND) FROM people;
  353. SELECT birthdt, DATE_ADD(birthdt, INTERVAL 3 QUARTER) FROM people;
  354. SELECT birthdt, birthdt + INTERVAL 1 MONTH FROM people;
  355. SELECT birthdt, birthdt - INTERVAL 5 MONTH FROM people;
  356. SELECT birthdt, birthdt + INTERVAL 15 MONTH + INTERVAL 10 HOUR FROM people;
  357.  
  358. --TIMESTAMP
  359. CREATE TABLE comments (
  360. content VARCHAR(100),
  361. created_at TIMESTAMP DEFAULT NOW()
  362. );
  363. INSERT INTO comments (content) VALUES('lol what a funny article');
  364. INSERT INTO comments (content) VALUES('I found this offensive');
  365. INSERT INTO comments (content) VALUES('Ifasfsadfsadfsad');
  366. SELECT * FROM comments ORDER BY created_at DESC;
  367. CREATE TABLE comments2 (
  368. content VARCHAR(100),
  369. changed_at TIMESTAMP DEFAULT NOW() ON UPDATE CURRENT_TIMESTAMP
  370. );
  371. INSERT INTO comments2 (content) VALUES('dasdasdasd');
  372. INSERT INTO comments2 (content) VALUES('lololololo');
  373. INSERT INTO comments2 (content) VALUES('I LIKE CATS AND DOGS');
  374. UPDATE comments2 SET content='THIS IS NOT GIBBERISH' WHERE content='dasdasdasd';
  375. SELECT * FROM comments2;
  376. SELECT * FROM comments2 ORDER BY changed_at;
  377. CREATE TABLE comments2 (
  378. content VARCHAR(100),
  379. changed_at TIMESTAMP DEFAULT NOW() ON UPDATE NOW()
  380. );
  381.  
  382.  
  383.  
  384. --EXERCISES
  385. --1. WHAT'S A GOOD USE CASE FOR CHAR?
  386. --//ANSWER - Any with fixed length such as passwords, abbreviation of US country, etc.
  387. --2. CREATE TABLE inventory(item_name ________, price ___________, quantity__________); -- price is always < 1,000,000
  388. CREATE TABLE inventory (item_name VARCHAR(25), price DECIMAL(8,2), quantity INT); -- decimal comes up to max 999,999.99 choose DECIMAL over FLOAT because it is more precise.
  389. --3. WHAT'S THE DIFFERENCE BETWEEN DATETIME AND TIMESTAMP?
  390. --//ANSWER - TIMESTAMP HAS A SMALLER RANGE BEFORE AND AFTER PRESENT TIME TIME STAMP FROM YEAR (1970-2038) AND DATETIME IS FROM YEAR (1000-9999)
  391. --// also, DATETIME Takes twice the memorysize than TIMESTAMP
  392. --//TIMESTAMP is usually used for when creating metadata when something is created, other purpose we use DATETIME
  393. --4. Print Out The Current Time
  394. SELECT CURTIME();
  395. --5. Print Out The Current Date (but not time)
  396. SELECT CURDATE();
  397. --6. Print Out The Current Day Of The Week (the number)
  398. SELECT DAYOFWEEK(NOW());
  399. --7. Print Out The Current Day Of The Week (the day name)
  400. SELECT DAYNAME(NOW());
  401. --8. Print Out the current day and time using this format: mm/dd/YYYY
  402. SELECT DATE_FORMAT(NOW(), '%m/%d/%Y');
  403. --9. Print Out the current day and time using this format: January 2nd at 3:15 and April 1st at 10:18
  404. SELECT DATE_FORMAT(NOW(), '%M %D at %h:%s');
  405. --10. Create a tweets table that stores: a. The Tweet content(limit 140 chars) b. A Username(limit to 20 chars) c. Time it was created_at
  406. CREATE TABLE tweets(content VARCHAR(140), username VARCHAR(20), created_at TIMESTAMP DEFAULT NOW());
  407.  
  408. --LOGICAL OPERATORS
  409. --
  410. -- != (Not Equal) ie. select books that were not released in 2017
  411. SELECT title FROM books WHERE released_year != 2017;
  412. --
  413. -- NOT LIKE ie. Select books with titles that don't start with 'W'
  414. SELECT title FROM books WHERE title NOT LIKE 'W%';
  415. --
  416. -- > (Greater Than) ie. Select books released after the year 2000;
  417. SELECT * FROM books WHERE released_year > 2000;
  418. --
  419. -- >= (Greater than or equal to) ie. Select books released from year 2000 and up;
  420. SELECT * FROM books WHERE released_year >= 2000;
  421. -- another sample: any books that have 100 stock or more will be on sale;
  422. SELECT title, stock_quantity FROM books WHERE stock_quantity >= 100;
  423. --
  424. SELECT 99 > 1 -- produces 1 for boolean true;
  425. SELECT 99 > 567 -- produces 0 for boolean false;
  426. 100 > 5 -- true
  427. -15 > 15 -- false
  428. 9 > -10 -- true
  429. 1 > 1 -- false
  430. 'a' > 'b' -- false
  431. 'A' > 'a' -- false
  432. 'A' >= 'a' -- true
  433. SELECT title, author_lname FROM books WHERE author_lname = 'Eggers';
  434. SELECT title, author_lname FROM books WHERE author_lname = 'eggers';
  435. SELECT title, author_lname FROM books WHERE author_lname = 'eGGers';
  436. --
  437. -- < (less than) ie. Select books released before the year 2000;
  438. SELECT * FROM books WHERE released_year < 2000 ORDER BY released_year;
  439. -- <= (less than or equal to) ie. Select books released before and during the year 2000;
  440. SELECT * FROM books WHERE released_year <= 2000 ORDER BY released_year;
  441. SELECT 3 < -10; -- false
  442. SELECT -10 < -9; -- true
  443. SELECT 42 <= 42; -- true
  444. SELECT 'h' < 'p'; -- true
  445. SELECT 'Q' <= 'q'; -- true
  446. --
  447. -- && (same with AND) ie. SELECT books written by Dave Eggers, and published after the year 2010;
  448. SELECT * FROM books WHERE author_lname = 'Eggers' && released_year > 2010;
  449. --or--
  450. SELECT * FROM books WHERE author_lname = 'Eggers' AND released_year > 2010;
  451. --SELECT books written by Dave Eggers, and published after the year 2010, and title contains 'novel':
  452. SELECT * FROM books WHERE author_lname = 'Eggers' && released_year > 2010 && title LIKE '%novel%';
  453. --
  454. -- ││ (OR)
  455. SELECT * FROM books WHERE author_lname = 'Eggers' ││ released_year > 2010;
  456. --
  457. -- BETWEEN
  458. SELECT title, released_year FROM books WHERE released_year BETWEEN 2004 and 2015;
  459. --
  460. -- NOT BETWEEN
  461. SELECT title, released_year FROM books WHERE released_year NOT BETWEEN 2004 and 2015;
  462. --
  463. -- (CASTING)
  464. SELECT CAST('2017-05-02' AS DATETIME);
  465. show databases;
  466. use new_testing_db;
  467. SELECT name, birthdt FROM people WHERE birthdt BETWEEN '1980-01-01' AND '2000-01-01';
  468. SELECT
  469. name,
  470. birthdt
  471. FROM people
  472. WHERE
  473. birthdt BETWEEN CAST('1980-01-01' AS DATETIME)
  474. AND CAST('2000-01-01' AS DATETIME);
  475. ----
  476. --
  477. -- IN
  478. SELECT title, author_lname FROM books WHERE author_lname IN('Carver', 'Lahiri', 'Smith'); --similar to select authors with last name of Carver OR Lahiri OR Smith.
  479. --
  480. -- NOT IN
  481. SELECT title, released_year FROM books WHERE released_year >= 2000 && released_year NOT IN(2000,2002,2004,2006,2008,2010,2012,2014,2016) ORDER BY released_year;
  482. --
  483. -- % (Modulo - remainder operator) ie. divide by 2 is even.
  484. SELECT title, released_year FROM books WHERE released_year >= 2000 && released_year % 2 = 0 ORDER BY released_year;
  485. --
  486. --
  487. -- CASE STATEMENTS
  488. SELECT title, released_year,
  489. CASE
  490. WHEN released_year >= 2000 THEN 'Modern Lit'
  491. ELSE '20th Century Lit'
  492. END AS GENRE
  493. FROM books;
  494. --
  495. --ANOTHER CASE example
  496. SELECT title, stock_quantity,
  497. CASE
  498. WHEN stock_quantity BETWEEN 0 AND 50 THEN '*'
  499. WHEN stock_quantity BETWEEN 51 AND 100 THEN '**'
  500. ELSE '***'
  501. END AS STOCK
  502. FROM books;
  503. -- another way which is shorter...
  504. SELECT title, stock_quantity,
  505. CASE
  506. WHEN stock_quantity <= 50 THEN '*'
  507. WHEN stock_quantity <= 100 THEN '**'
  508. ELSE '***'
  509. END AS STOCK
  510. FROM books;
  511.  
  512. --etc
  513. ALTER TABLE Customers
  514. ADD Email varchar(255);
  515.  
  516. ALTER TABLE table_name
  517. DROP COLUMN column_name;
  518.  
  519. ALTER TABLE table_name
  520. MODIFY column_name datatype;
  521.  
  522. -- delete a row entry --
  523. DELETE FROM table_name WHERE condition;
  524.  
  525. DELETE FROM books WHERE title = NULL; --WRONG WAY--
  526. DELETE FROM books WHERE title IS NULL; -- RIGHT WAY--
  527.  
  528. --
  529. -- LOGIC EXERCISES --
  530. -- 1. EVALUATE THE FOLLOWING... SELECT 10 != 10 (ANSWER: 0); --- SELECT 15 > 14 && 99 -5 <= 94 (ANSWER: 1); --- SELECT 1 IN (5,3) ││ 9 BETWEEN 8 AND 10 (ANSWER: 1);
  531. -- 2. Select all books written before 1980 (non inclusive)
  532. SELECT title, released_year FROM books WHERE released_year < 1980 ORDER BY released_year;
  533. -- 3. Select all books written by Eggers or Chabon.
  534. SELECT title, author_lname, released_year FROM books WHERE author_lname = 'Eggers' OR author_lname = 'Chabon';
  535. --or--
  536. SELECT title, author_lname, released_year FROM books WHERE author_lname IN ('Eggers', 'Chabon') ORDER BY author_lname; --better way!
  537. -- 4. Select all books written by Lahiri, published after 2000.
  538. SELECT title, author_lname, released_year FROM books WHERE author_lname = 'Lahiri' && released_year > 2000 ORDER BY released_year;
  539. -- 5. Select all books with page counts between 100 and 200.
  540. SELECT title, pages FROM books WHERE pages BETWEEN 100 and 200 ORDER BY pages;
  541. -- or --
  542. SELECT title, pages FROM books WHERE pages >= 100 && pages <=200;
  543. -- 6. Select all books where author_lname starts with a 'C' or an 'S'
  544. SELECT title, author_lname FROM books WHERE author_lname LIKE 'C%' OR author_lname LIKE 'S%' ORDER BY author_lname;
  545. -- or--
  546. SELECT title, author_lname FROM books WHERE SUBSTR(author_lname,1,1) = 'C' OR SUBSTR(author_lname,1,1) = 'S';
  547. --or--
  548. SELECT title, author_lname FROM books WHERE SUBSTR(author_lname,1,1) IN ('C','S');
  549. -- 7. If title contains 'stories' then Short Stories .... Just Kids -and- A Heartbreaking Work then Memoir ... Everything else is a novel
  550. SELECT title,author_lname,
  551. CASE
  552. WHEN title LIKE '%stories%' THEN 'Short Stories'
  553. WHEN title LIKE '%Just Kids%' OR title LIKE '%A Heartbreaking Work%' THEN 'Memoir'
  554. ELSE 'Novel'
  555. END AS TYPE
  556. FROM books;
  557. -- 8. Bonus title, author_lname COUNT books for each author_lname (mind singular and plural book vs books)
  558. SELECT title, CONCAT(author_fname,author_lname),
  559. CASE
  560. WHEN COUNT(*) <= 1 THEN CONCAT(COUNT(*), ' book')
  561. ELSE CONCAT(COUNT(*), ' books')
  562. END AS COUNT
  563. FROM books GROUP BY author_lname,author_fname;
  564.  
  565. -- JOINS --
  566. -- relationship basics:
  567. --1 to many: ie. Customers & Orders
  568. -- We Want to Store...
  569. -- 1. A customer's first and last Name
  570. -- 2. A customer's Email
  571. -- 3. The date of purchase
  572. -- 4. The price of the order
  573. -- ****** PRIMARY KEY, FOREIGN KEY
  574. -- Creating the customers and orders tables
  575. CREATE TABLE customers(
  576. id INT AUTO_INCREMENT PRIMARY KEY,
  577. first_name VARCHAR(100),
  578. last_name VARCHAR(100),
  579. email VARCHAR(100)
  580. );
  581. CREATE TABLE orders(
  582. id INT AUTO_INCREMENT PRIMARY KEY,
  583. order_date DATE,
  584. amount DECIMAL(8,2),
  585. customer_id INT,
  586. FOREIGN KEY(customer_id) REFERENCES customers(id)
  587. );
  588. -- Inserting some customers and orders
  589. INSERT INTO customers (first_name, last_name, email)
  590. VALUES ('Boy', 'George', 'george@gmail.com'),
  591. ('George', 'Michael', 'gm@gmail.com'),
  592. ('David', 'Bowie', 'david@gmail.com'),
  593. ('Blue', 'Steele', 'blue@gmail.com'),
  594. ('Bette', 'Davis', 'bette@aol.com');
  595. INSERT INTO orders (order_date, amount, customer_id)
  596. VALUES ('2016/02/10', 99.99, 1),
  597. ('2017/11/11', 35.50, 1),
  598. ('2014/12/12', 800.67, 2),
  599. ('2015/01/03', 12.50, 2),
  600. ('1999/04/11', 450.25, 5);
  601. -- This INSERT fails because of our fk constraint. No user with id: 98
  602. INSERT INTO orders (order_date, amount, customer_id)
  603. VALUES ('2016/06/06', 33.67, 98);
  604.  
  605.  
  606. - Finding Orders Placed By George: 2 Step Process
  607. SELECT id FROM customers WHERE last_name='George';
  608. SELECT * FROM orders WHERE customer_id = 1;
  609. -- Finding Orders Placed By George: Using a subquery
  610. SELECT * FROM orders WHERE customer_id =
  611. (
  612. SELECT id FROM customers
  613. WHERE last_name='George'
  614. );
  615. -- Cross Join Craziness a BIG NO NO
  616. SELECT * FROM customers, orders; -- WRONG WAY, NOT RECOMMENDED!
  617.  
  618. -- CROSS JOIN (OK WAY) - IMPLICIT INNER JOIN
  619. SELECT * FROM customers,orders WHERE customers.id = orders.customer_id;
  620. SELECT first_name, last_name, order_date, amount FROM customers,orders WHERE customers.id = orders.customer_id;
  621.  
  622. -- EXPLICIT INNER Join ( THE RIGHT WAY - PREFERRED WAY)
  623. SELECT * FROM customers
  624. JOIN orders
  625. ON customers.id = orders.customer_id;
  626. -- or
  627. SELECT first_name, last_name, order_date, amount FROM customers
  628. JOIN orders
  629. ON customers.id = orders.customer_id;
  630.  
  631. --ARBITRARY JOIN - DON'T DO THIS!!!! - doesnt make sense since customer id and order id is NOT the same! (but customer id = order customer_id )
  632. SELECT * FROM customers
  633. JOIN orders ON customers.id = orders.id;
  634.  
  635. -- Getting Fancier
  636. SELECT first_name, last_name, order_date, amount FROM customers
  637. JOIN orders
  638. ON customers.id = orders.customer_id
  639. ORDER BY amount;
  640.  
  641. SELECT first_name, last_name, sum(amount) AS total_spent
  642. FROM customers
  643. JOIN orders
  644. ON customers.id = orders.customer_id
  645. GROUP BY orders.customer_id
  646. ORDER BY total_spent DESC;
  647.  
  648. -- LEFT JOIN
  649. SELECT * FROM customers
  650. LEFT JOIN orders
  651. ON customers.id = orders.customer_id;
  652.  
  653. SELECT first_name, last_name, IFNULL(SUM(amount), 0) AS total_spent
  654. FROM customers
  655. LEFT JOIN orders
  656. ON customers.id = orders.customer_id
  657. GROUP BY customers.id
  658. ORDER BY total_spent;
  659.  
  660. -- RIGHT JOIN
  661. SELECT * FROM customers
  662. RIGHT JOIN orders
  663. ON customers.id = orders.customer_id;
  664.  
  665. -- to delete both tables use:
  666. DROP TABLE orders, customers;
  667.  
  668. INSERT INTO orders (order_date, amount, customer_id) VALUES
  669. ('2017/11/05',23.45, 45),
  670. (CURDATE(), 777.77, 109);
  671. -- will have ERROR because of Foreight Key Constraint!
  672.  
  673. SELECT
  674. IFNULL(first_name,'MISSING') AS first,
  675. IFNULL(last_name,'USER') as last,
  676. order_date,
  677. amount,
  678. SUM(amount)
  679. FROM customers
  680. RIGHT JOIN orders
  681. ON customers.id = orders.customer_id
  682. GROUP BY first_name, last_name;
  683.  
  684. -- ON DELETE CASCADE
  685. CREATE TABLE customers(
  686. id INT AUTO_INCREMENT PRIMARY KEY,
  687. first_name VARCHAR(100),
  688. last_name VARCHAR(100),
  689. email VARCHAR(100)
  690. );
  691.  
  692. CREATE TABLE orders(
  693. id INT AUTO_INCREMENT PRIMARY KEY,
  694. order_date DATE,
  695. amount DECIMAL(8,2),
  696. customer_id INT,
  697. FOREIGN KEY(customer_id)
  698. REFERENCES customers(id)
  699. ON DELETE CASCADE
  700. );
  701.  
  702. INSERT INTO customers (first_name, last_name, email)
  703. VALUES ('Boy', 'George', 'george@gmail.com'),
  704. ('George', 'Michael', 'gm@gmail.com'),
  705. ('David', 'Bowie', 'david@gmail.com'),
  706. ('Blue', 'Steele', 'blue@gmail.com'),
  707. ('Bette', 'Davis', 'bette@aol.com');
  708.  
  709. INSERT INTO orders (order_date, amount, customer_id)
  710. VALUES ('2016/02/10', 99.99, 1),
  711. ('2017/11/11', 35.50, 1),
  712. ('2014/12/12', 800.67, 2),
  713. ('2015/01/03', 12.50, 2),
  714. ('1999/04/11', 450.25, 5);
  715.  
  716. -- MANY TO MANY
  717. CREATE TABLE reviewers (
  718. id INT AUTO_INCREMENT PRIMARY KEY,
  719. first_name VARCHAR(100),
  720. last_name VARCHAR(100)
  721. );
  722.  
  723. CREATE TABLE series (
  724. id INT AUTO_INCREMENT PRIMARY KEY,
  725. title VARCHAR(100),
  726. released_year YEAR(4),
  727. genre VARCHAR(100)
  728. );
  729.  
  730. CREATE TABLE reviews(
  731. id INT AUTO_INCREMENT PRIMARY KEY,
  732. rating DECIMAL(2,1),
  733. series_id INT,
  734. reviewer_id INT,
  735. FOREIGN KEY (series_id) REFERENCES series(id),
  736. FOREIGN KEY (reviewer_id) REFERENCES reviewers(id)
  737. );
  738.  
  739. INSERT INTO series (title, released_year, genre) VALUES
  740. ('Archer', 2009, 'Animation'),
  741. ('Arrested Development', 2003, 'Comedy'),
  742. ("Bob's Burgers", 2011, 'Animation'),
  743. ('Bojack Horseman', 2014, 'Animation'),
  744. ("Breaking Bad", 2008, 'Drama'),
  745. ('Curb Your Enthusiasm', 2000, 'Comedy'),
  746. ("Fargo", 2014, 'Drama'),
  747. ('Freaks and Geeks', 1999, 'Comedy'),
  748. ('General Hospital', 1963, 'Drama'),
  749. ('Halt and Catch Fire', 2014, 'Drama'),
  750. ('Malcolm In The Middle', 2000, 'Comedy'),
  751. ('Pushing Daisies', 2007, 'Comedy'),
  752. ('Seinfeld', 1989, 'Comedy'),
  753. ('Stranger Things', 2016, 'Drama');
  754.  
  755.  
  756. INSERT INTO reviewers (first_name, last_name) VALUES
  757. ('Thomas', 'Stoneman'),
  758. ('Wyatt', 'Skaggs'),
  759. ('Kimbra', 'Masters'),
  760. ('Domingo', 'Cortes'),
  761. ('Colt', 'Steele'),
  762. ('Pinkie', 'Petit'),
  763. ('Marlon', 'Crafford');
  764.  
  765. INSERT INTO reviews(series_id, reviewer_id, rating) VALUES
  766. (1,1,8.0),(1,2,7.5),(1,3,8.5),(1,4,7.7),(1,5,8.9),
  767. (2,1,8.1),(2,4,6.0),(2,3,8.0),(2,6,8.4),(2,5,9.9),
  768. (3,1,7.0),(3,6,7.5),(3,4,8.0),(3,3,7.1),(3,5,8.0),
  769. (4,1,7.5),(4,3,7.8),(4,4,8.3),(4,2,7.6),(4,5,8.5),
  770. (5,1,9.5),(5,3,9.0),(5,4,9.1),(5,2,9.3),(5,5,9.9),
  771. (6,2,6.5),(6,3,7.8),(6,4,8.8),(6,2,8.4),(6,5,9.1),
  772. (7,2,9.1),(7,5,9.7),
  773. (8,4,8.5),(8,2,7.8),(8,6,8.8),(8,5,9.3),
  774. (9,2,5.5),(9,3,6.8),(9,4,5.8),(9,6,4.3),(9,5,4.5),
  775. (10,5,9.9),
  776. (13,3,8.0),(13,4,7.2),
  777. (14,2,8.5),(14,3,8.9),(14,4,8.9);
  778.  
  779. --Challenge1
  780. SELECT * FROM series
  781. JOIN reviews
  782. ON series.id = reviews.series_id;
  783.  
  784. --Challenge2
  785. SELECT title, AVG(rating) AS avg_rating
  786. FROM series
  787. JOIN reviews
  788. ON series.id = reviews.series_id
  789. GROUP BY series.id
  790. ORDER BY avg_rating DESC
  791. ;
  792.  
  793. -- challenge 3
  794. SELECT
  795. first_name,last_name,rating
  796. FROM reviewers
  797. JOIN reviews
  798. ON reviews.id = reviews.reviewer_id;
  799.  
  800. -- Challenge 4 - Unreviewed series_id
  801. SELECT title,rating
  802. FROM series
  803. LEFT JOIN reviews
  804. ON series.id = reviews.series_id;
  805.  
  806. -- Challenge 5 genre avg ratings
  807. SELECT genre, ROUND( AVG(rating), 2)
  808. AS avg_rating FROM series
  809. JOIN reviews
  810. ON series.id=reviews.series_id
  811. GROUP BY genre;
  812.  
  813. -- Challenge 6 - Reviewer Stats
  814. -- firstname,lastname,count(howmanyreviews),min(review),max(review), avg(review), status(active if count>=1)
  815. SELECT
  816. first_name,
  817. last_name,
  818. COUNT(rating) AS count,
  819. IFNULL(MIN(rating),0) AS min,
  820. IFNULL(MAX(rating),0) AS max,
  821. IFNULL(AVG(rating),0) AS avg,
  822. CASE
  823. WHEN COUNT(rating) >= 1
  824. THEN 'Active'
  825. ELSE 'Inactive'
  826. END as status
  827. FROM reviewers
  828. LEFT JOIN reviews
  829. ON reviewers.id = reviews.reviewer_id
  830. GROUP BY reviewers.id
  831. ORDER BY count DESC
  832. ;
  833. -- OR
  834. SELECT first_name,
  835. last_name,
  836. Count(rating) AS COUNT,
  837. Ifnull(Min(rating), 0) AS MIN,
  838. Ifnull(Max(rating), 0) AS MAX,
  839. Round(Ifnull(Avg(rating), 0), 2) AS AVG,
  840. IF(Count(rating) > 0, 'ACTIVE', 'INACTIVE') AS STATUS
  841. FROM reviewers
  842. LEFT JOIN reviews
  843. ON reviewers.id = reviews.reviewer_id
  844. GROUP BY reviewers.id;
  845.  
  846. -- challenge 7
  847. -- title, rating, reviewer
  848. SELECT
  849. title,
  850. rating,
  851. CONCAT(first_name, ' ',last_name) AS reviewer
  852. FROM reviewers
  853. JOIN reviews
  854. ON reviewers.id = reviews.reviewer_id
  855. JOIN series
  856. ON series.id =reviews.series_id
  857. ORDER BY title
  858. ;
  859.  
  860. -- Schema Design
  861. -- USERS, PHOTOS, COMMENTS, LIKES, HASHTAGS, FOLLOWERS/FOLLOWEES
  862.  
  863.  
  864. CREATE DATABASE ig_clone;
  865. USE ig_clone;
  866.  
  867. CREATE TABLE users(
  868. id INT AUTO_INCREMENT PRIMARY KEY,
  869. username VARCHAR(255) UNIQUE NOT NULL,
  870. created_at TIMESTAMP DEFAULT NOW()
  871. );
  872.  
  873. INSERT INTO users (username) VALUES
  874. ('BlueTheCat'),
  875. ('CharlieBrown'),
  876. ('ColtSteele');
  877.  
  878. CREATE TABLE photos(
  879. id INT AUTO_INCREMENT PRIMARY KEY,
  880. image_url VARCHAR(255) NOT NULL,
  881. user_id INTEGER NOT NULL,
  882. created_at TIMESTAMP DEFAULT NOW(),
  883. FOREIGN KEY(user_id) REFERENCES users(id)
  884. );
  885.  
  886. INSERT INTO photos(image_url,user_id) VALUES
  887. ('/ldkfewg23', 1),
  888. ('/dfghrtte', 2),
  889. ('/sdfu56', 2);
  890.  
  891. CREATE TABLE comments(
  892. id INT AUTO_INCREMENT PRIMARY KEY,
  893. comment_text VARCHAR(255) NOT NULL,
  894. user_id INT NOT NULL,
  895. photo_id INT NOT NULL,
  896. created_at TIMESTAMP DEFAULT NOW(),
  897. FOREIGN KEY (user_id) REFERENCES users(id),
  898. FOREIGN KEY (photo_id) REFERENCES photos(id)
  899. );
  900.  
  901. INSERT INTO comments (comment_text, user_id, photo_id) VALUES
  902. ('Meow', 1, 2),
  903. ('Amazing Shot!', 3, 2),
  904. ('I <3 This',2,1);
  905.  
  906. CREATE TABLE likes(
  907. user_id INT NOT NULL,
  908. photo_id INT NOT NULL,
  909. created_at TIMESTAMP DEFAULT NOW(),
  910. FOREIGN KEY (user_id) REFERENCES users(id),
  911. FOREIGN KEY (photo_id) REFERENCES photos(id),
  912. PRIMARY KEY (user_id,photo_id) -- can only do 1 like per uniqe user to a photo.
  913. );
  914.  
  915. INSERT INTO likes(user_id, photo_id) VALUES
  916. (1,1),
  917. (2,1),
  918. (1,2),
  919. (1,3),
  920. (3,3);
  921.  
  922. -- find out how many likes per photo
  923. SELECT image_url, count(likes.user_id) AS number_of_likes FROM photos
  924. JOIN likes
  925. ON likes.photo_id = photos.id
  926. JOIN users
  927. ON users.id = likes.user_id
  928. GROUP BY image_url
  929. ORDER BY number_of_likes DESC;
  930.  
  931. -- RELATIONSHIP TROUBLES
  932. CREATE TABLE follows(
  933. follower_id INT NOT NULL,
  934. followee_id INT NOT NULL,
  935. created_at TIMESTAMP DEFAULT NOW(),
  936. FOREIGN KEY (follower_id) REFERENCES users(id),
  937. FOREIGN KEY (followee_id) REFERENCES users(id),
  938. PRIMARY KEY(follower_id, followee_id)
  939. );
  940.  
  941. INSERT INTO follows(follower_id, followee_id) VALUES
  942. (1,2),
  943. (1,3),
  944. (3,1),
  945. (2,3);
  946.  
  947.  
  948. CREATE TABLE tags (
  949. id INTEGER AUTO_INCREMENT PRIMARY KEY,
  950. tag_name VARCHAR(255) UNIQUE,
  951. created_at TIMESTAMP DEFAULT NOW()
  952. );
  953.  
  954. CREATE TABLE photo_tags(
  955. photo_id INT NOT NULL,
  956. tag_id INT NOT NULL,
  957. FOREIGN KEY (photo_id) REFERENCES photos(id),
  958. FOREIGN KEY (tag_id) REFERENCES tags(id),
  959. PRIMARY KEY(photo_id, tag_id)
  960. );
  961.  
  962. INSERT INTO tags(tag_name) VALUES
  963. ('adorable'),
  964. ('cute'),
  965. ('sunrise');
  966.  
  967. INSERT INTO photo_tags (photo_id,tag_id) VALUES
  968. (1,1),
  969. (1,2),
  970. (2,3),
  971. (3,2);
  972.  
  973. -- refer to igclone.sql for dataset
  974.  
  975. -- 1. Find the 5 Oldest Users.
  976. SELECT * FROM users
  977. ORDER BY created_at
  978. LIMIT 5;
  979.  
  980. -- 2. Most Popular Registration Date
  981. SELECT
  982. DAYNAME(created_at) AS day,
  983. COUNT(*) AS total
  984. FROM users
  985. GROUP BY day
  986. ORDER BY total DESC
  987. LIMIT 2;
  988.  
  989. -- 3. Find the users who have never posted a photo.
  990. SELECT
  991. username
  992. FROM users
  993. LEFT JOIN photos
  994. ON photos.user_id = users.id
  995. WHERE photos.id IS NULL ;
  996.  
  997. -- 4. Identify most popular photo (and user who created it)
  998. SELECT
  999. username,
  1000. photos.id,
  1001. photos.image_url,
  1002. COUNT(*) AS total
  1003. FROM photos
  1004. JOIN likes
  1005. ON likes.photo_id = photos.id
  1006. JOIN users
  1007. ON photos.user_id = users.id
  1008. GROUP BY photos.id
  1009. ORDER BY total DESC
  1010. LIMIT 1
  1011. ;
  1012.  
  1013. -- 5. Calcuate avg number of photos per user
  1014. SELECT (SELECT COUNT(*) FROM photos) / (SELECT COUNT(*) FROM users) AS avg;
  1015.  
  1016. -- 6. What are the top 5 most commonly used hashtags?
  1017. SELECT
  1018. tags.tag_name,
  1019. COUNT(*) as total
  1020. FROM photo_tags
  1021. JOIN tags
  1022. ON tags.id = photo_tags.tag_id
  1023. GROUP BY tags.id
  1024. ORDER BY total DESC
  1025. LIMIT 5;
  1026.  
  1027.  
  1028. -- 6. Find users who have liked every single photo on the site (bots!)
  1029. SELECT
  1030. username,
  1031. COUNT(*) AS num_likes
  1032. FROM users
  1033. JOIN likes
  1034. ON likes.user_id = users.id
  1035. GROUP BY likes.user_id
  1036. HAVING num_likes = (SELECT COUNT(*) FROM photos);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement