Learn SQL With Rails 4 - Single Table Queries

Question Click to View Answer

Create a rails application called single_table_queries.

$ rails new single_table_queries

Create an Article model with a title attribute (string datatype). Create the articles table in the database.

$ rails g model Article title:string
$ rake db:migrate

What SQL is generated to create the articles table in the database.

CREATE TABLE "articles" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255), "created_at" datetime, "updated_at" datetime);

Only mark this answer as correct if you can write this entire SQL statement flawlessly.

What SQL does the following code generate?

Article.create(title: "blah blah blah")
INSERT INTO "articles" ("created_at", "title", "updated_at")
VALUES (?, ?, ?)  [["created_at", "2014-06-27 18:25:38.638132"], ["title", "blah blah blah"], ["updated_at", "2014-06-27 18:25:38.638132"]]

Update the seed file, so it creates 100 articles with 8 character random strings as the title.

# db/seeds.rb
def random_string(n)
  ('a'..'z').to_a.shuffle[0..n-1].join
end

100.times do
  str = random_string(8)
  Article.create!(title: str)
end

# command line
$ rake db:seed

What SQL does the following code generate?

Article.find(1)
SELECT  "articles".* FROM "articles"  WHERE "articles"."id" = ? LIMIT 1  [["id", 1]]

What SQL does the following code generate?

Article.all
SELECT "articles".* FROM "articles"

What SQL does the following code generate?

Article.first
SELECT  "articles".* FROM "articles"   ORDER BY "articles"."id" ASC LIMIT 1

What SQL does the following code generate?

Article.last(5)
SELECT  "articles".* FROM "articles"   ORDER BY "articles"."id" DESC LIMIT 5

Write an ActiveRecord query to fetch all articles with a title that starts with the letter 'b'. What is the SQL generated by this query.

# ActiveRecord query
Article.where("title LIKE ?", "b%")
-- SQL query
SELECT "articles".* FROM "articles"  WHERE (title LIKE 'b%')

Write an ActiveRecord query to fetch all articles with a title that's 8 characters long. What is the SQL generated by this query.

# ActiveRecord query
Article.where("length(title) = 8")
-- SQL query
SELECT "articles".* FROM "articles"  WHERE (length(title) = 8)