Is there a difference between 'fetchone()' and 'LIMIT 1' using SQLAlchemy - sqlalchemy

When using SQLAlchemy to retrieve a row from a database, you might use
query = "SELECT some_col FROM some_table"
row = session.execute(query).fetchone()
However, you could also do:
query = "SELECT some_col FROM some_table LIMIT 1"
row = session.execute(query).fetchall()
Is there any reason to prefer one over the other, e.g. better performance?

The first variant works with all DBMS, the second only with those supporting the LIMIT keyword which is not standard. So if you want to tell the database you want to limit the result to just one row, you better use SQLAlchemy core instead of an SQL statement as string. Something like:
row = session.execute(select([some_table.c.some_col]).limit(1)).fetchone()
If you really query just one row with just one column you might consider scalar() instead of fetchone():
value = session.execute(select([some_table.c.some_col]).limit(1)).scalar()

Related

hibernate query for getting the table column count

I am new to learning HIBERNATE and SQL.I want a query for count the number of columns available in the table. Please help me to do this task.
I tried the below query,but i am getting bulk manipulation exception.
Thank you.
Query colQuery = session.createSQLQuery("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema =:'dn' AND table_name=:'tn'");
colQuery.setString("dn", "abc");
colQuery.setString("tn", "store_data");
int count=colQuery.executeUpdate();
I see several problems with your code. First, named parameters in your native query do not take single quotes around them, i.e. use :dn and not :'dn'. Next, you are trying to execute an update on a SELECT query. This is also wrong, because you are not updating any records, and you just need to call colQuery.list() to get back your result set. Finally, I believe you need to use Query#setParameter() to assign values to the parameters. Try using this code:
Query colQuery = session.createSQLQuery("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema=:dn AND table_name=:tn");
colQuery.setParameter("dn", "abc");
colQuery.setParameter("tn", "store_data");
List<Object[]> rows = colQuery.list();
int rowCount = ((Integer) rows.get(0)[0]).intValue();
Note that I accessed the first row of the result set, and the first (and only) column in that first row to get the count.

MySQL: what's the maximum number of arguments allowed within the IN() function for one query? [duplicate]

Say you have the following query:
SELECT * FROM table1 WHERE table1.id IN (1, 2, 3, 4, 5, ..., 999999)
What is a reasonable maximum for the number of items in the IN clause? I'm using Sphinx to generate full-text search results and inserting the IDs into a MySQL query. Is this an acceptable way to do it?
You can also have the IN clause take the results of a query, such as:
SELECT * FROM table1
WHERE table1.id IN
(
SELECT id from table2
)
That way, you don't need to generate a text string with all the possible values.
In mysql, you should be able to put as many values in the IN clause as you want, only constrained by the value of "max_allowed_packet".
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_in
http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_max_allowed_packet
MariaDB (10.3.22 in my case) has a limit of 999 parameters to IN() before it creates a materialized temporary table, resulting in possibly much longer execution times. Depending on your indices. I haven't found a way to control this behaviour. MySQL 5.6.27 does not have this limit, at least not at ~1000 parameters. MySQL 5.7 might very well have the same "feature".
I ended up doing a series of where id = a or id = b ... but it also works fine by using series of where id in(a, b) or id in(c, d) ....
You have to add laravel row query and then add NOT IN condition into this:
$object->whereRaw('where id NOT IN (' . $array_list . ') ');
This will work for my code.
From my experience the maximum values is 1000 values in clause IN ('1',....,'1000'),
I have 1300 value in my excel sheet,I put them all into IN ,MySQL return only 1000 .

In MySQL select query, checking for a string or checking for true in a where clause?

Consider the following table:
SELECT id, Bill_Freq, Paid_From, Paid_To, Paid_Dt, rev_code FROM psr_20160708091408;
The requirement is to fetch the row which has rev_code populated with the string **SUM**.
I've also noticed that for every row with rev_code populated as **SUM** its Bill_Freq won't be either null or zero.
So I wrote two queries to fetch the row with the lowest id
Query based on string check in where clause:
select
min(id) as head_id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where rev_code = "**SUM**";
Query based on true condition:
select
min(id) as head_id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where bill_freq;
I haven't seen anyone use the second type, would like to know its reliability and circumstance of failure.
If by "second type" you mean a where clause with no explicit condition, then there is a good reason why you do not see it.
The SQL standard -- and most databases -- require explicit conditions in the where. MySQL allows the shorthand that you use but it really means:
where not billing_freq <=> 0
or equivalently:
where billing_freq <> 0 or billing_freq is null
(The <=> is the null-safe comparison operator.
The more important issue with your query is the min(). I presume that you actually want this:
select p.*
from psr_20160708091408 p
where rev_code = '**SUM**'
order by id
limit 1;
Also, you should use single quotes as string delimiters. That is the ANSI standard and there is rarely any reason to use double quotes.
Actually you can use the second type of query, but as your requirement is based on rev_code, it is always good to have condition with rev_code, because of 2 reasons
Bill_Freq having no NUlls or Zeros might be assumption based on current data
Even if it is true, in future, your application logic might change and it might have a scenario having NULL or zero, which will break your logic in future.
So my suggestion is to use first query with Rev_code
Please try to use below query
select
id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where rev_code = "**SUM**" ORDER BY ASC LIMIT 0,1;
Thanks.
The requirement says it itself.
The requirement is to fetch the row which has rev_code populated with
the string '**SUM**'
In the scenario that bill_freq IS NOT NULL and rev_code is populated with
the string '**SUM**' then your logic will obviously fail.
Go for
where rev_code = "**SUM**";

mysql get column name when column value matches constraint

I'm trying to get column names from a table. I want to supply the row id and I want only the column names for which the value of that column for the specific row (identified by the id) is "true" (my table has a bunch of boolean fields).
I want something like:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME.value = true
AND TABLE_THE_COLUMN_IS_FROM.id = "some_id"
Where .value would be variable, basically checking each column to see if it were true.
I know I can just get the row's values and iterate through, returning only those with value true, but I wanted to see if there is a way to do it all in one step. Thanks in advance to anyone who knows!
There is no means in one query to dynamically scan through the table's schema and inspect its values. The best way to achieve what you want is the one you suggested: query for the row client-side and then cycle through the columns searching for the values you seek. The other alternative is to query for the table schema using the INFORMATION SCHEMA views client-side, build a SQL statement with a where clause that looks for a True value in all the boolean columns, execute that and inspect the results.
This is probably going to be rather ugly no matter how you cut it, but here's one option:
select columns.column_name
from bool_table
inner join information_schema.columns
on columns.table_schema = 'your_db'
and columns.table_name = 'bool_table'
and ((columns.column_name = 'bool_1' and bool_table.bool_1 = 1)
or (columns.column_name = 'bool_2' and bool_table.bool_2 = 1))
where bool_table.id = 25
You could also potentially query information_schema.columns to dynamically generate the list of column statements so that you could dynamically generate the query, and even execute it in a stored proc using dynamic sql in mysql.

Can i execute query in iif function

I want to know can i run a query in iif function used in ms access database. My case
Select field1,(iif(3<4,'Select * from tbl1','select * from tbl2')) from tblmain
I am facing syntax error when i try to executed query like that whats the problem
What you're trying to achieve isn't clear from your sample query.
You can use IIF functions in Access queries, for example:
SELECT IIF([SomeField]<15, "Smaller than 15", "Greater than!") As Whatever
FROM myTable
You can use subselects in Access as well, for example (example shamelessly stolen from http://allenbrowne.com/subquery-01.html):
SELECT MeterReading.ID, MeterReading.ReadDate, MeterReading.MeterValue,
(SELECT TOP 1 Dupe.MeterValue
FROM MeterReading AS Dupe
WHERE Dupe.AddressID = MeterReading.AddressID
AND Dupe.ReadDate < MeterReading.ReadDate
ORDER BY Dupe.ReadDate DESC, Dupe.ID) AS PriorValue
FROM MeterReading;
Note that the specified subselect query must be guaranteed to return a single record - either by specifying TOP 1 or using an aggregate function - and must link back to the parent query in the WHERE clause.
You can't use an IIF statement the way you're trying to in your question, however, even if your subselect was valid, which it is not.
Two options to suggest, although it is less than clear to me what you're trying to achieve here. First, you might want to consider doing it in VBA instead. Something like:
const query1 As String = "Select * from tbl1"
const query2 As String = "select * from tbl2"
Dim recset as DAO.Recordset
set recset = CurrentDB.OpenRecordset(iif(3<4, query1, query2))
Alternatively, if both tbl1 and tbl2 had the same fields you could do something like this:
SELECT * FROM tbl1 WHERE 3<4
UNION ALL
SELECT * FROM tbl2 WHERE NOT (3<4)
If you replace 3<4 by whatever actual condition you're checking for, you'll only get back records from one or the other or query, never both. However, my suspicion is that if you need to do this, your database may have design issues - I can think of many questionable scenarios where this would be needed, and few valid ones, although I'm sure they exist.