SQL Flashcards

1
Q

Retrieving a Single Object

A

Client.find this is the same as

SELECT * FROM clients WHERE (clients.id = 10) LIMIT 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

what is the difference between Client.take and Client.find

A

client = Client.take The take method retrieves a record without any implicit ordering.
SELECT * FROM clients LIMIT 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

what does Client.first return? what would Client.first(3) return?

A

The first method finds the first record ordered by primary key (default)
SELECT * FROM clients ORDER BY clients.id ASC LIMIT 1
the value passed in returns that number of results

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Client.find_by first_name: ‘Lifo’

A

is the same as:
Client.where(first_name: ‘Lifo’).take and in SQL
SELECT * FROM clients WHERE (clients.first_name = ‘Lifo’) LIMIT 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Client.where(“orders_count = ?”, params[:orders]) why the question mark?

A

Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, Client.where(“first_name LIKE ‘%#{params[:first_name]}%’”) is not safe.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Order.select(“date(created_at) as ordered_date, sum(price) as total_price”).group(“date(created_at)”)

A

And this will give you a single Order object for each date where there are orders in the database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

how to do joins in active record?

A

You can just supply the raw SQL specifying the JOIN clause to joins:
Author.joins(“INNER JOIN posts ON posts.author_id = authors.id AND posts.published = ‘t’”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

hw to join multiple records?

A

Article.joins(:category, :comments) which is:
SELECT articles.* FROM articles
INNER JOIN categories ON categories.id = articles.category_id
INNER JOIN comments ON comments.article_id = articles.id

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

when do we join?

A

A simple joins statement lets you return records that have an associated record.
for example Category.joins(:products)
This query returns all categories that have products. It will return a category for every match it finds, which means there can be many duplicates. https://www.learneroo.com/modules/137/nodes/768

How well did you know this?
1
Not at all
2
3
4
5
Perfectly