Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more concise way to check if PGResult is empty?

I'm using the pg gem to talk to PostgreSQL from Ruby. Is there a better way to check if there are no results than using res.ntuples == 0?

conn = PGconn.connect config

cmd = "select * from labels inner join labels_mail using(label_id) " + 
  "where labels_mail.mail_id = $1 and labels.name = $2"

res = conn.exec(cmd, [mail_id, mailbox])

if res.ntuples == 0  #  <=== is there a better way to check this?
  cmd = "insert into labels_mail (mail_id, label_id) values ($1, $2)"
  conn.exec(cmd, [mail_id, label_id(mailbox)])
end
like image 321
dan Avatar asked Apr 19 '11 17:04

dan


People also ask

Is null or empty PostgreSQL?

The PostgreSQL NULL is the term used to represent a missing value. A NULL value in a table is a value in a field that appears to be blank. A field with a NULL value is a field with no value. It is very important to understand that a NULL value is different from a zero value or a field that contains spaces.

How do I check for null in PostgreSQL?

Example - With SELECT StatementSELECT * FROM employees WHERE first_number IS NULL; This PostgreSQL IS NULL example will return all records from the employees table where the first_name contains a NULL value.

What is NVL in PostgreSQL?

The NVL function returns the first of its arguments that isn't null. NVL evaluates the first expression. If that expression evaluates to NULL , NVL returns the second expression. NVL(expr1, expr2) The return type is the same as the argument types.

Is not equal in Postgres?

Note. <> is the standard SQL notation for “not equal”. !=


1 Answers

ntuples, a typo? It is faster and concise to use zero? than == 0

if res.num_tuples.zero?
like image 58
sawa Avatar answered Nov 13 '22 11:11

sawa