How can we fetch top 3 data value from database - sqlite

There is three field in my data base id(primary key),name, salary
I want fetch top 3 salary from the database.

Use LIMIT to get top 3 after ordering, as such:
SELECT *
FROM myTable
ORDER BY salary DESC
LIMIT 3;

SELECT * FROM your_table ORDER BY id DESC;

SELECT [column(s)]
FROM [table]
ORDER BY [column(s)] [ASC, DESC];
For more information check here:
http://www.sqlite.org/lang_select.html

SQL has an ORDER BY clause that allows you do order the result set by any column/columns, ascending and descending.
For your particular question:
SELECT Id, Name
FROM myTable
ORDER BY Id DESC;
See this SO question (SQLite - sorting a table).

Related

Retrieve sorted data based on one numeric column in SQLITE

I have a table like attached image in SQLITE database.
I am trying to retrieve sorted data based on SUM(freight) column. For this i have used the below query.
SELECT ShipCountry
FROM CountryDetails
GROUP BY ShipCountry
ORDER BY SUM(freight) ASC
When i run this i am getting result like below.
If i run the below query i am getting result like below. It's fine.
SELECT ShipCountry, ShipCity
FROM CountryDetails
GROUP BY ShipCountry, ShipCity
ORDER BY SUM(Freight), ShipCity ASC
Instead of this i need a result like below. In order by clause SUM(Freight) should consider only ShipCountry. It should not consider both ShipCountry and ShipCity. My Expected result is
How to achieve this result through SQLITE query?
in SQL we can achieve like below query.
Select ShipCountry, ShipCity from Countrydetails group by ShipCountry, ShipCity Order by SUM(SUM(freight)) over(partition by ShipCountry), Shipcity Asc.
We need equivalent query like this in Sqlite.
Use a subquery to find the frieght sum for each country, then order using only this country level sum:
SELECT
cd1.ShipCountry,
cd1.ShipCity
FROM Countrydetails cd1
INNER JOIN
(
SELECT ShipCountry, SUM(freight) AS freight_sum
FROM Countrydetails
GROUP BY ShipCountry
) cd2
ON cd1.ShipCountry = cd2.ShipCountry
ORDER BY
cd1.freight_sum,
cd1.ShipCountry, -- needed in case two countries happen to have the same sum
cd1.ShipCity
We could add another sort level for the frieght of each city, to order within a given country. But your expected output does not imply that you want this.

Sort order for sqlite index

There is sort order when creating index for sqlite.
https://sqlite.org/lang_createindex.html
Each column name or expression can be followed by one of the "ASC" or "DESC" keywords to indicate sort order.
So, there are three options: no-sort, ASC, DESC when creating index. Where is info about how I should use them? I cant find it.
I guess, if I use ASC or DESC in queries, I should add them to index. But should I add them both if they are both in different queries? Or should I just don't set sort order and it will select it itself?
What is a general rule for it?
SQLite can scan an index in both directions. For an index on a single column, this means it can be used to sort in both ASC and DESC order.
Reference:
The Idx1 index is scanned from top to bottom (or from bottom to top if "ORDER BY fruit DESC" is used) in order to find the rowids for each item in order by fruit.
But for an index on more than one column, there are more than two directions that one might wish to sort the data. For instance, on a two column index, one might wish to sort via ASC, ASC; ASC, DESC; DESC, DESC; or DESC, ASC order.
If the index was created in ASC, ASC order, then sorting by ASC, ASC or DESC, DESC will be able to fully use the index. But sorting by ASC, DESC and DESC, ASC will not be possible solely using the index. That is why the index order may be specified.
For more info: https://use-the-index-luke.com/sql/sorting-grouping/order-by-asc-desc-nulls-last
SQLite can step through an index in both directions, so in general, the index order does not matter.

Improve sqlite query Where field in to exists

Here's my simplified working query:
select fields, sum(otherFields)
from table1
where table1.field1 in (Select table2.field1
from table2
where table1.id=table2.id
order by table2.date desc limit 100)
group by fields
As you can see, I need from table1 only the rows that are in table2 but these ones filtered by last newer 100.
The query takes a bit too long, so I've tried to replace the in with exists
select fields, sum(otherFields)
from table1
where exists (Select table2.field1
from table 2
where table1.id=table2.id
and table1.field=table2.fields
order by table2.date desc limit 100)
group by fields
While this would work for queries that don't use limit in my case it does not work properly.
So, how can I properly filter the result from table1 in relation with only a limited number of rows from table2?

SQLite: SELECT from grouped and ordered result

I'm new to SQL(ite), so i'm sorry if there is a simple answer i just were to stupid to find the right search terms for.
I got 2 tables: 1 for user information and another holding points a user achieved. It's a simple one to many relation (a user can achieve points multiple times).
table1 contains "userID" and "Username" ...
table2 contains "userID" and "Amount" ...
Now i wanted to get a highscore rank for a given username.
To get the highscore i did:
SELECT Username, SUM(Amount) AS total FROM table2 JOIN table1 USING (userID) GROUP BY Username ORDER BY total DESC
How could i select a single Username and get its position from the grouped and ordered result? I have no idea how a subselect would've to look like for my goal. Is it even possible in a single query?
You cannot calculate the position of the user without referencing the other data. SQLite does not have a ranking function which would be ideal for your user case, nor does it have a row number feature that would serve as an acceptable substitute.
I suppose the closest you could get would be to drop this data into a temp table that has an incrementing ID, but I think you'd get very messy there.
It's best to handle this within the application. Get all the users and calculate rank. Cache individual user results as necessary.
Without knowing anything more about the operating context of the app/DB it's hard to provide a more specific recommendation.
For a specific user, this query gets the total amount:
SELECT SUM(Amount)
FROM Table2
WHERE userID = ?
You have to count how many other users have a higher amount than that single user:
SELECT COUNT(*)
FROM table1
WHERE (SELECT SUM(Amount)
FROM Table2
WHERE userID = table1.userID)
>=
(SELECT SUM(Amount)
FROM Table2
WHERE userID = ?);

How to read the last record in SQLite table?

Is there a way to read the value of the last record inserted in an SQLite table without going through the previous records ?
I ask this question for performance reasons.
There is a function named sqlite3_last_insert_rowid() which will return the integer key for the most recent insert operation. http://www.sqlite.org/c3ref/last_insert_rowid.html
This only helps if you know the last insert happened on the table you care about.
If you need the last row on a table, regardless of wehter the last insert was on this table or not, you will have to use a SQL query
SELECT * FROM mytable WHERE ROWID IN ( SELECT max( ROWID ) FROM mytable );
When you sort the records by ID, in reverse order, the last record will be returned first.
(Because of the implicit index on the autoincrementing column, this is efficient.)
If you aren't interested in any other records, use LIMIT:
SELECT *
FROM MyTable
ORDER BY _id DESC
LIMIT 1

Resources