In SQL this command works ok:
Query
SELECT TOP 20 * FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY t0.ProductId) AS [ROW_NUMBER], *
FROM Product AS [t0]
) AS [t1]
WHERE [t1].[ROW_NUMBER] > 0 * 20;
Now I try the same with SQLite. I know that I must replace TOP with LIMIT, but don't know where to put it.
I always get something like
Error
SQLite error near "(": syntax error" or "SQLite error near "*": syntax error".
And I am not sure that the command [ROW_NUMBER] or ROW_NUMBER() works in SQlite.
Query
SELECT *,
(
SELECT COUNT(*)
FROM Product b
WHERE a.ProductId >= b.ProductId
) AS rnum
FROM Product a LIMIT 20;
Screen Shot
See the documentation:
SELECT *
FROM Product
LIMIT 20
OFFSET 0 -- optional
SQlite doesn't support TOP. That is sql-server syntax. You have to use limit 20 instead.
Related
According to all examples my query should be executing. I am trying to update new column on my table with the last 4 digits of the phone number like so :
UPDATE users
SET users.phone_last_4 = t.lastFour
FROM
(
select substr( phone_number, -4) as lastFour from users
) t;
Also tried this:
UPDATE users
SET users.phone_last_4 = t.lastFour
FROM
(
select substr( phone_number, -4) as lastFour from users
) AS t;
Both fail with same error :
near ".": syntax error: UPDATE users
SET users.
What could I possibly do wrong here?
SQLite does not support joins for the UPDATE statement and also this syntax containing FROM .
In your case I can't see why you need it.
Just do:
UPDATE users
SET phone_last_4 = substr(phone_number, -4)
I am trying to use 'WITH' clause inside PL-SQL block :
Cursor using WITH clause as follows :
CURSOR c_API_MSG
IS
WITH SAMI AS (SELECT * FROM NAGENDRA WHERE STATUS = 'NEW')
SELECT * FROM SAMI WHERE ROWNUM <= TO_NUMBER (10);
Execution :
FOR v_Rec IN c_API_MSG
LOOP
BEGIN
-- My LOGIC
END;
END LOOP;
It is not executing properly. It is not going inside loop. seems like cursor not able to fetch rows & that's why exiting.
Normal sub-query without with clause working fine. With clause working fine on editor.
Is there any limitation of using 'WITH' clause or am I missing something here ?
Observations :
Inside toad editor with below query :
If I Use f9 (normal execute) : 5 rows found (Correct result)
If I use f5 : No rows found (This is I am worried about)
WITH SAMI AS (SELECT * FROM NAGENDRA WHERE STATUS = 'NEW')
SELECT * FROM SAMI WHERE ROWNUM <= TO_NUMBER (10);
Hey Yes PLSQL supports "WITH" clause. Plz see below snippet.
SET sqlbl ON;
SET serveroutput ON;
DECLARE
CURSOR LV_CUR
IS
WITH
TEMP_AV AS
(
SELECT
LEVEL
FROM
DUAL
CONNECT BY LEVEL < 10
)
SELECT
*
FROM
TEMP_AV;
BEGIN
FOR I IN LV_CUR
LOOP
NULL;
dbms_output.put_line(i.level);
END LOOP;
END;
My current query:
select timestamp from messagesTable
where partner_jid='" + lastUserJid + "' AND msg='.roll'
order by timestamp DESC LIMIT 1 OFFSET 1;
This works fine... unless the values don't exist in the database.
If values do not exist in database, then it should Select * messagesTable; or do nothing if possible.
Is there a way to add a check for that within the same query? It has to be the same query unfortunately because I need to execute things through adb shell. I've been trying things out with CASE but I do not really understand much about SQL.
You can just append a second query, with a WHERE filter that checks whether the first query did not return anything:
SELECT *
FROM (SELECT timestamp
FROM messagesTable
WHERE partner_jid = ?
AND msg = '.roll'
ORDER BY timestamp DESC
LIMIT 1 OFFSET 1)
UNION ALL
SELECT -1 -- or "timestamp FROM msgTab", or whatever
WHERE NOT EXISTS (SELECT timestamp
FROM messagesTable
WHERE partner_jid = ?
AND msg = '.roll');
I am having trouble getting a block of pl/sql code to work. In the top of my procedure I get some data from my oracle apex application on what checkboxes are checked. Because the report that contains the checkboxes is generated dynamically I have to loop through the
APEX_APPLICATION.G_F01
list and generate a comma separated string which looks like this
v_list VARCHAR2(255) := (1,3,5,9,10);
I want to then query on that list later and place the v_list on an IN clause like so
SELECT * FROM users
WHERE user_id IN (v_list);
This of course throws an error. My question is what can I convert the v_list to in order to be able to insert it into a IN clause in a query within a pl/sql procedure?
If users is small and user_id doesn't contain commas, you could use:
SELECT * FROM users WHERE ',' || v_list || ',' LIKE '%,'||user_id||',%'
This query is not optimal though because it can't use indexes on user_id.
I advise you to use a pipelined function that returns a table of NUMBER that you can query directly. For example:
CREATE TYPE tab_number IS TABLE OF NUMBER;
/
CREATE OR REPLACE FUNCTION string_to_table_num(p VARCHAR2)
RETURN tab_number
PIPELINED IS
BEGIN
FOR cc IN (SELECT rtrim(regexp_substr(str, '[^,]*,', 1, level), ',') res
FROM (SELECT p || ',' str FROM dual)
CONNECT BY level <= length(str)
- length(replace(str, ',', ''))) LOOP
PIPE ROW(cc.res);
END LOOP;
END;
/
You would then be able to build queries such as:
SELECT *
FROM users
WHERE user_id IN (SELECT *
FROM TABLE(string_to_table_num('1,2,3,4,5'));
You can use XMLTABLE as follows
SELECT * FROM users
WHERE user_id IN (SELECT to_number(column_value) FROM XMLTABLE(v_list));
I have tried to find a solution for that too but never succeeded. You can build the query as a string and then run EXECUTE IMMEDIATE, see http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/dynamic.htm#i14500.
That said, it just occurred to me that the argument of an IN clause can be a sub-select:
SELECT * FROM users
WHERE user_id IN (SELECT something FROM somewhere)
so, is it possible to expose the checkbox values as a stored function? Then you might be able to do something like
SELECT * FROM users
WHERE user_id IN (SELECT my_package.checkbox_func FROM dual)
Personally, i like this approach:
with t as (select 'a,b,c,d,e' str from dual)
--
select val
from t, xmltable('/root/e/text()'
passing xmltype('<root><e>' || replace(t.str,',','</e><e>')|| '</e></root>')
columns val varchar2(10) path '/'
)
Which can be found among other examples in Thread: Split Comma Delimited String Oracle
If you feel like swamping in even more options, visit the OTN plsql forums.
I need to write a query as follows which will be bound to a grid
select top 25 * from ErrTable Order by DateErrorad Desc
However, I need to write this query to return only 25 records at a time, but when a user clicks next it will display the next 25 most recent records from the db.
How could I accomplish this?
You can implement a 'paging' technique using ROW_NUMBER() as detailed in this post: http://www.davidhayden.com/blog/dave/archive/2005/12/30/2652.aspx
Ok, since I don't know what Database Server/engine but basically you will need a range (in your case 25) and a page number (e.g. 0 is first page, 1 for next page of 25 records, etc).
In MySQL, you can do this (using the LIMIT command)....
SELECT * FROM TABLE LIMIT START, RANGE;
Wher TABLE is your table name, START is your start index/range, e.g if you have record 0 - 24, you can set start = 25, to read the next 25 (which is where RANGE comes into play).
This is only available in MySQL, in DB2 it's different though. Find out who your DB server/engine handles pagination.
In DB2:
SELECT * FROM TABLE FETCH FIRST N ROW ONLY;
Where N is a numeric value.
Edit For MSSQL, you can see another related post:
How to implement LIMIT with Microsoft SQL Server?
Here's an article that shows Paging in ASP.NET.
In MySQL you can do that with LIMIT, in MSSQL i don't know if that works.
SELECT * FROM table LIMIT 10
or
SELECT * FROM table LIMIT 0, 10
This will display the first 10 results from the database.
SELECT * FROM table LIMIT 5, 5
This will show records 6 to 10
Assuming you're using SQL Server (based on the ASP.NET tag):
declare #offset int
set #offset = 25
select * from (
select *, row_number() over (order by DateErrorad desc) as i from ErrTable
) a
where i <= #offset + 25 and i > #offset
I would highly recommend you use an ORM, though. I love LINQ-to-SQL (it's a perfect complement to ASP.NET), and with that you could do this as:
var rows = Errors.Skip(offset).Take(25);
You can use the LIMIT command to pick entries in a given range. However, I'm not sure if all engines support it, so a more general solution (albeit less efficient, I reckon), is...
SELECT TOP 25 *
FROM YOURTABLE
WHERE IDCOL NOT IN (SELECT TOP 25 * FROM YOURTABLE)
Sorry for the loose definition, I'm leaving and can't answer in more detail.
I guess it depends on your DBMS, the following LINQ2SQL-query
(table DatabaseLogs from AdventureWorks)
using (DataClasses1DataContext context = new DataClasses1DataContext())
{
context.Log = Console.Out;
var qq3 = context.DatabaseLogs.Skip(20).Take(10).ToList();
}
generates the following query for MSSQL
SELECT [t1].[DatabaseLogID], [t1].[PostTime], [t1].[DatabaseUser], [t1].[Event], [t1].[Schema] AS [Schema], [t1].[Object], [t1].[TSQL], [t1].[XmlEvent]
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY [t0].[DatabaseLogID], [t0].[PostTime], [t0].[DatabaseUser], [t0].[Event], [t0].[Schema], [t0].[Object], [t0].[TSQL]) AS [ROW_NUMBER], [t0].[DatabaseLogID], [t0].[PostTime], [t0].[DatabaseUser], [t0].[Event], [t0].[Schema], [t0].[Object], [t0].[TSQL], [t0].[XmlEvent]
FROM [dbo].[DatabaseLog] AS [t0]
) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN #p0 + 1 AND #p0 + #p1
ORDER BY [t1].[ROW_NUMBER]
-- #p0: Input Int (Size = -1; Prec = 0; Scale = 0) [20]
-- #p1: Input Int (Size = -1; Prec = 0; Scale = 0) [10]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1
by creating a stored procedure and passing your range
create procedure dbo.SelectWindow
#start int, #end int
as
begin
select *
from
(
select
*,
row_number() (order by ID) as Row
from dbo.table
) a
where Row between #start and #end
end
go