I have a column that contains Sring data with numbers in them. the format of the number is like (x,xxx).
for example, the number 1555 is stored as 1,555
I want to order the data from the table. I have tried CAST AS
#Query("SELECT * from country_table ORDER BY CAST(cases AS INTEGER)")
fun getAllCountries(): LiveData<List<SingleCountryStats>>
but this doesn't work since the field can not be cast to integer due to the comma in the middle
is there any option to remove the commas then order the results?
If the commas are used consistently, you can use:
order by length(cases), cases
Otherwise, you can remove the commas and convert:
order by cast(replace(cases, ',', '') as int)
Remove the comma and sort the column as a number:
SELECT * from country_table ORDER BY REPLACE(cases, ',', '') + 0
The operator + casts implicitly the string to a number.
Related
Is there a way I can apply the LIKE clause to a result set in SQLite? What I would like to accomplish is the following:
SELECT *
FROM MyTable
WHERE value LIKE
(
SELECT CASE
WHEN prefix IS NOT NULL THEN prefix || '?'
ELSE code END
FROM MyOtherTable
)
Adding the ? to the end of does not allow me to wildcard search by the prefix and the LIKE just ends up functioning like an IN clause.
Is there some way to achieve this, or alternatively a better way to achieve the same result?
Your primary issue is that ? is not a pattern matching character, rather that _ is for pattern matching any single character and % is for pattern matching a sequence of characters.
SQL As Understood By SQLite - expression - The LIKE, GLOB, REGEXP, and MATCH operators
However, you would also encounter issues if myOtherTable has multiple rows.
Consider the following :-
DROP TABLE IF EXISTS MyTable;
DROP TABLE IF EXISTS MyOtherTable;
CREATE TABLE IF NOT EXISTS MyTable (value TEXT);
CREATE TABLE IF NOT EXISTS MyOtherTable (prefix TEXT, code TEXT);
INSERT INTO MyOtherTable VALUES
(null,'mycode'),
('A','myothercode'),
('S',null)
;
INSERT INTO MyTable VALUES
('Something'), -- matched by S%
('A something'), -- matched by A%
('mycode is this'), -- never matched as characters after mycode
('Another'), -- matched by A%
('mycode') -- matched by mycode
;
-- Intermediate
SELECT CASE
WHEN prefix IS NOT NULL THEN prefix || '%'
ELSE code END
FROM MyOtherTable
;
SELECT *
FROM MyTable
WHERE value LIKE
(
SELECT CASE
WHEN prefix IS NOT NULL THEN prefix || '%'
ELSE code END
FROM MyOtherTable
);
The final result would be :-
A single row
mycode
That is only the first result of the subquery is considered.
If (null,'mycode'), is removed or commented out then the result would be :-
Two rows that match the now first A% i.e.
A something
Another
Removing or commenting out the first two (null,'mycode'), and ('A','myothercode'), results in the single row :-
Something
It continues to occur error... what is the problem?
every variables are String.
String insertSQL = "INSERT INTO " + DBHelper.getTableName() + " VALUES (\''"+entry.getKey()+"\'', \''"+images+"\'')";
Error message
INSERT INTO LABELING RESULT VALUES (''Sky'',
''["/storage/emulated/0/DCIM/CandyCam/IMG_20171009_164101723.jpg","/storage/emulated/0/DCIM/Pictail/IMG_20180305_000218777.jpg","/storage/emulated/0/DCIM/Pictail/IMG_20180401_235850170.jpg","/storage/emulated/0/DCIM/Pictail/IMG_20180518_194252232.jpg"]''))
My table has three column : ID(Integer), LABEL(TEXT), IMAGES(TEXT)
Issue 1 you have specified a table name with a space i.e. LABELING RESULT, if this is the table name then you would need to enclose it e.g. [LABELING RESULT].
Issue 2 you have double single quotes when you should only have 1.
Issue 3 you have an extra closing parenthesis.
I believe the following is what you want :-
INSERT INTO [LABELING RESULT] VALUES ('Sky', '["/storage/emulated/0/DCIM/CandyCam/IMG_20171009_164101723.jpg","/storage/emulated/0/DCIM/Pictail/IMG_20180305_000218777.jpg","/storage/emulated/0/DCIM/Pictail/IMG_20180401_235850170.jpg","/storage/emulated/0/DCIM/Pictail/IMG_20180518_194252232.jpg"]'))
Which would (not checked though) be :-
String insertSQL = "INSERT INTO [" + DBHelper.getTableName() + "] VALUES ('"+entry.getKey()+"', '"+images+"')";
That assumes that Sky goes into the LABEL column and the 2 comma separated image paths go into the IMAGES column.
Additional re enclosing (the [ ] ):-
If you want to use a keyword as a name, you need to quote it. There
are four ways of quoting keywords in SQLite:
'keyword' A keyword in single quotes is a string literal.
"keyword" A keyword in double-quotes is an identifier.
[keyword] A keyword enclosed in square brackets is an identifier. This is not
standard SQL. This quoting mechanism is used by MS Access and SQL
Server and is included in SQLite for compatibility.
keyword A keyword enclosed in grave accents (ASCII code 96) is an identifier.
This is not standard SQL. This quoting mechanism is used by MySQL and
is included in SQLite for compatibility.
SQL As Understood By SQLite - SQLite Keywords
as the title states:
I have a select query, which I'm trying to "order by" a field which contains numbers, the thing is this numbers are really strings starting with 0s, so the "order by" is doing this...
...
10
11
12
01
02
03
...
Any thoughts?
EDIT: if I do this: "...ORDER BY (field+1)" I can workaround this, because somehow the string is internally being converted to integer. Is this the a way to "officially" convert it like C's atoi?
You can use CAST http://www.sqlite.org/lang_expr.html#castexpr to cast the expression to an Integer.
sqlite> CREATE TABLE T (value VARCHAR(2));
sqlite> INSERT INTO T (value) VALUES ('10');
sqlite> INSERT INTO T (value) VALUES ('11');
sqlite> INSERT INTO T (value) VALUES ('12');
sqlite> INSERT INTO T (value) VALUES ('01');
sqlite> INSERT INTO T (value) VALUES ('02');
sqlite> INSERT INTO T (value) VALUES ('03');
sqlite> SELECT * FROM T ORDER BY CAST(value AS INTEGER);
01
02
03
10
11
12
sqlite>
if I do this: "...ORDER BY (field+1)" I can workaround this, because somehow the string is internally being converted to integer. Is the a way to "officially" convert it like C's atoi?
Well thats interesting, though I dont know how many DBMS support such an operation so I don't recommend it just in case you ever need to use a different system that doesn't support it, not to mention you are adding an extra operation, which can affect performance, though you also do this ORDER BY (field + 0) Im going to investigate the performance
taken from the sqlite3 docs:
A CAST expression is used to convert the value of to a different storage class in a similar way to the conversion that takes place when a column affinity is applied to a value. Application of a CAST expression is different to application of a column affinity, as with a CAST expression the storage class conversion is forced even if it is lossy and irrreversible.
4.0 Operators
All mathematical operators (+, -, *, /, %, <<, >>, &, and |) cast both operands to the NUMERIC storage class prior to being carried out. The cast is carried through even if it is lossy and irreversible. A NULL operand on a mathematical operator yields a NULL result. An operand on a mathematical operator that does not look in any way numeric and is not NULL is converted to 0 or 0.0.
I was curios so I ran some benchmarks:
>>> setup = """
... import sqlite3
... import timeit
...
... conn = sqlite3.connect(':memory:')
... c = conn.cursor()
... c.execute('CREATE TABLE T (value int)')
... for index in range(4000000, 0, -1):
... _ = c.execute('INSERT INTO T (value) VALUES (%i)' % index)
... conn.commit()
... """
>>>
>>> cast_conv = "result = c.execute('SELECT * FROM T ORDER BY CAST(value AS INTEGER)')"
>>> cast_affinity = "result = c.execute('SELECT * FROM T ORDER BY (value + 0)')"
>>> timeit.Timer(cast_conv, setup).timeit(number = 1)
18.145697116851807
>>> timeit.Timer(cast_affinity, setup).timeit(number = 1)
18.259973049163818
>>>
As we can see its a bit slower though not by much, interesting.
You could use CAST:
ORDER BY CAST(columnname AS INTEGER)
In ListView with cursor loader!
String projection= some string column;
String selection= need to select;
String sort="CAST ("+ YOUR_COLUMN_NAME + " AS INTEGER)";
CursorLoader(getActivity(), Table.CONTENT_URI, projection, selection, selectionArgs, sort);
CONVERT CAST function using order by column value number format in SQL SERVER
SELECT * FROM Table_Name ORDER BY CAST(COLUMNNAME AS INT);
Thanks to Skinnynerd. with Kotlin, CAST worked as follows:
CAST fix the problems of prioritizing 9 over 10 OR 22 over 206.
define global variable to alter later on demand, and then plug it in the query:
var SortOrder:String?=null
to alter the order use:
For descendant:
SortOrder = "CAST(MyNumber AS INTEGER)" + " DESC"
(from highest to lowest)
For ascending:
SortOrder = "CAST(MyNumber AS INTEGER)" + " ASC"
(from lowest to highest)
I've got a database with several columns and a column name and I'm doing the following sqlite statement through OrmLite:
SELECT `name`,`id`,`ita_name`,`setCode`
FROM `MyTable`
WHERE (`name` LIKE ?)
ORDER BY `name` LIMIT 30
everything works fine but if the value of the name column is "Michael*,* Basketball player" and I submit "Michael Basketball player" the query return no results.
I've already tried to use %myQueryText% but with no success.
What can i do to return values from my column ignoring "," ?
SQL LIKE statement is more specific, than you think. The % wildcard matches zero or more characters at the position of the wildcard, so %myQueryText% matches anythingmyQueryText OR myQueryTextanything but not myQuery(comma)text. You need place wildcard at position of comma, see SQL LIKE wildcards.
So you probably want something like
... WHERE (`name` LIKE "Michael%Basketball player") ...
Edit/ Prepare your search pattern in Java, possibly like
String searchPattern = "Michael Basket player";
String preparedPattern = searchPattern.replace(' ', '%');
// outputs pattern "Michael%Basket%player"
Which could match even Michael the best Basketbal and other sports player and if you want to overcome such troubles, you can use REGEXP and prepare search pattern:
String searchPattern = "Michael Basket player";
String preparedPattern = searchPattern.replace(' ', '[,\s]+');
// outputs pattern "Michael[,\s]+Basket[,\s]+player"
and then in SQL query change WHERE statement to
WHERE `name` REGEXP "Michael[,\s]+Basket[,\s]+player"
the [,\s]+ matches either comma or white space and the occurance is one or multiple times, so it matches one space or space and comma or comma and more spaces...
Assume that I have 1234. I want a query to select all columns that match:
1234
01234
001234
0001234
...
How can I do that in SQLite?
You could try to convert the string into a number:
SELECT ... WHERE CAST(Column AS NUMBER) = 1234
However, this also allows leading spaces, or .0 floating-point numbers.
you can use 'like' query
SELECT * FROM table WHERE field like '%1234%'