Skip to content

Instantly share code, notes, and snippets.

@RedSoxFan22
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RedSoxFan22/51aa674e2b10c48122e7 to your computer and use it in GitHub Desktop.
Save RedSoxFan22/51aa674e2b10c48122e7 to your computer and use it in GitHub Desktop.
SQL the langauge we use to get information out of normalized date structures
Select clause tells you which
From clause tells you which
Where clause dictates which row you get back out
Answer.where(question_id=3).map &:response
Select * = select all is equivalent to .select(:response), but with the last one use and id otherwise you get back all the items, even if there are millions
Find all authors with an email of Shakespeare.email.com
SELECT *
FROM authors
WHERE email = "Shakespeare.email.com"
IN RAILS: Author.where(email:"shakespeare.email.com")
Find 3 most recent answer
SELECT *
FROM answers
ORDER BY created_at DESC
LIMIT 3;
IN RAILS: Answer.order(created_at: :desc).limit(3)
Find author who was created most recently
SELECT *
FROM authors
ORDER BY created_at DESC;
LIMIT 1
IN RAILS:
11:20...Find the number of answers for each question_id(group): You can't select something you're not grouping by. You can put aliases in fields.
SELECT count(id) AS number_of_answers (when you use count, it doesn't matter what is in parens)
FROM answers AS a
GROUP BY question_id
IN RAILS: Answer.group(:question_id).select("count(id) AS number_of_answers").first
Find the last time question of each type was created(group)
SELECT max(created_at), question_type
FROM questions
GROUP BY question_type
Find the number (count) of each type of question in the database
SELECT count(id) AS question_tyoe
FROM questions
GROUP question_type
IN RAILS: question.group(:question_type).select("count(id) AS num, question_type")
the more you can cosolidate things down into a singular database call, the fatser it will run
read about JOIN clause
indices
making records in seeds 12:07
to add indices 12:09
ALWAYS PUT INDICES ON THE FOREIGN KEYS, then use your judgement about how users use the system to put foreign keys on other things.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment