SQL Select top 100 columns be specific column names or indices - sql

This works to select top 100 columns, but it gives me all of the columns
select top 100 * from dw.test
This works, but it gives me endless rows,
select Slot, ID from dw.test
I need to select top 100 rows that only show these two columns Slot, ID
I cannot get it to work no matter how I try to combine them,
Please help create this query. Thank you

try it
select TOP(100) Slot, ID from dw.test ORDER BY Slot, ID DESC

It's not clear to me which RDBMS is being used, but one of the following should work:
SELECT TOP(100) Slot, ID FROM dw.test;
Limit instead?
SELECT Slot, ID FROM dw.test LIMIT 100;

Related

How to list items and count(*) in PostgreSQL

I'm not sure if it's even possible. Let's say, I have a table A having 100 records. I want to select top five records and also return a total number of elements in this table in one query. How can I do this?
You can add the count as an additional column using window functions:
select a.*, count(*) over () as records_in_table
from a
order by <whatever> -- however you define "top five"
fetch first 5 rows only;

Fetch No oF Rows that can be returned by select query

I'm trying to fetch data and showing in a table with pagination. so I use limit and offset for that but I also need to show no of rows that can be fetched from that query. Is there any way to get that.
I tried
resultset.last() and getRow()
select count(*) from(query) myNewTable;
These two cases i'm getting correct answer but is it correct way to do this. Performance is a concern
We can get the limited records using below code,
First, we need to set how many records we want like below,
var limit = 10;
After that sent this limit to the below statement
WITH
Temp AS(
SELECT
ROW_NUMBER() OVER( primayKey DESC ) AS RowNumber,
*
FROM
myNewTable
),
Temp2 AS(
SELECT COUNT(*) AS TotalCount FROM Temp
)
SELECT TOP limit * FROM Temp, Temp2 WHERE RowNumber > :offset order by RowNumber
This is run in both MSSQL and MySQL
There is no easy way of doing this.
1. As you found out, it usually boils down to executing 2 queries:
Executing SELECT with limit and offset in order to fetch the data that you need.
Executing a COUNT(*) in order to count the total number of pages.
This approach might work for tables that don't have a lot of rows, or when you filter the data (int the COUNT and SELECT queries) on a column that is indexed.
2. If your table is large, but the data that you need to show represents smaller percentage of the data from the table and the data shares a common trait (for example, the data in all of your pages is created on a single day) you can use partitioning. Executing COUNT and SELECT on a single partition will be way more faster than executing them on the whole table.
3. You can create another table which will store the value of the COUNT query.
For example, lets say that your big_table table looks like this:
id | user_id | timestamp_column | text_column | another_text_column
Now, your SELECT query looks like this:
SELECT * FROM big_table WHERE user_id = 4 ORDER BY timestamp_column LIMIT 20 OFFSET 20;
And your count query:
SELECT COUNT(*) FROM table WHERE user_id = 4;
You could create a count_table that will have the following format:
user_id | count
Once you fill this table with the current data in the system, you will create a trigger which will update this table on every insert or update of the big_table.
This way, the count query will be really fast, because it will be executed on the count_table, for example:
SELECT count FROM count_table WHERE user_id = 4
The drawback of this approach is that the insert in the big_table will be slower, since the trigger will fire and update the count_table on every insert.
This are the approaches that you can try but in the end it all depends on the size and type of your data.

How to use max function with select top in sql

I have a table, lets call it TempAccount, with a column named AccountID. It contains numbers from 1,2,3...and so on.
My requirement is that I should select the maximum value from the top 10 AccountIDs.
I know I can do it by creating a temp table and inserting the top 10 values in it and then select the maximum value out of that table. But I was hoping if there is any direct query I can use to achieve this.
Something like MAX(SELECT TOP 10 AccountID FROM TempAccount)
What is the best way I can achieve this?
Note: I am using SQL Server 2012
You can use CTE query. Example:
WITH CTEQuery (AccountId) AS (
SELECT TOP 10 AccountId
FROM TempAccount
ORDER BY AccountId
)
SELECT MAX(AccountId)
FROM CTEQuery
Do the TOP 10 in a derived table, then use MAX on its result. Something like:
select max(dt.col1)
from
(
select top 10 col1
from table
where ...
order by ...
) dt

Get items before and after an item - SQL Query

I am new to SQL, so I need your help on a query. Basically I have a Database of ZipCodes and I want to get 3 items before the selected ZipCode and 3 items after. The Query that I came up with is pretty bad...
WITH numberedlogtable AS
(
SELECT *
FROM dbo.US
)
SELECT *
FROM numberedlogtable
WHERE ZipCode IN (SELECT ZipCode+i
FROM numberedlogtable
CROSS JOIN (SELECT -1 AS i UNION ALL SELECT 0 UNION ALL SELECT 1) n
WHERE ZipCode='91803')
I picked up a sample Query from somewhere and successfully converted it for my use. The only problem is that this Query returns current item and the next item. Instead, it should returns previous 3 items, current item, and next three items.
Using a common table expression (the WITH part) producing a numbered sequence:
WITH NumberedZipCodes AS
(SELECT SELECT ROW_NUMBER() OVER (ORDER BY ZipCode) AS RowNumber, *
FROM ZipCodes)
SELECT * From NumberedZipCodes
WHERE RowNumber BETWEEN
(SELECT RowNumber FROM NumberedZipCodes WHERE ZipCode=91803) - 3
AND (SELECT RowNumber FROM NumberedPerson WHERE ZipCode=91803) + 3
Normally in SQL there is no such concept as the previous or next items in a match. Actually, unless an order by clause is specified the rows are returned in any order that the sql engine find suitable. To make a query like this, an order has to be applied and index numbers generated. That's done in NumberedZipCodes. The second part is just a query to get the data out of it.
To have the query run efficiently, make sure that there is an index on the ZipCode column.
"Before" and "after" only have meaning in the context of ordering. Assuming you wish to order by ZIP code, selecting the desired ZIP code and 2 rows after it could be done like this:
SELECT TOP(3) *
FROM numberedlogtable
WHERE ZipCode >= '91803'
ORDER BY ZipCode
Selecting 3 rows before:
SELECT TOP(3) *
FROM numberedlogtable
WHERE ZipCode < '91803'
ORDER BY ZipCode DESC
Put UNION ALL between these two queries to make it one, if that's what you wish.
You can play with it in the SQL Fiddle.
3 items before the selected ZipCode and 3 items afte
SQL is set based, it has no defined order UNLESS YOU DEFINE ONE (with order by).
Now, lets not get into the more complex stuff - FURST you have to create an order asking for the central item, then in a second query you can ask for the other 6. Sorry, no other way. x+3 would be doable with a Top 4 statement and a filter etc. - but the 3 before will definitely require a second query.
All assume you creata query / view that has
* THe zipCodes in a defined order
* a row number once you filter it, used to define (a) the "current line" as well as filter for all with smaller lines.
But you need an order manually first.

Most efficient way to select 1st and last element, SQLite?

What is the most efficient way to select the first and last element only, from a column in SQLite?
The first and last element from a row?
SELECT column1, columnN
FROM mytable;
I think you must mean the first and last element from a column:
SELECT MIN(column1) AS First,
MAX(column1) AS Last
FROM mytable;
See http://www.sqlite.org/lang_aggfunc.html for MIN() and MAX().
I'm using First and Last as column aliases.
if it's just one column:
SELECT min(column) as first, max(column) as last FROM table
if you want to select whole row:
SELECT 'first',* FROM table ORDER BY column DESC LIMIT 1
UNION
SELECT 'last',* FROM table ORDER BY column ASC LIMIT 1
The most efficient way would be to know what those fields were called and simply select them.
SELECT `first_field`, `last_field` FROM `table`;
Probably like this:
SELECT dbo.Table.FirstCol, dbo.Table.LastCol FROM Table
You get minor efficiency enhancements from specifying the table name and schema.
First: MIN() and MAX() on a text column gives AAAA and TTTT results which are not the first and last entries in my test table. They are the minimum and maximum values as mentioned.
I tried this (with .stats on) on my table which has over 94 million records:
select * from
(select col1 from mitable limit 1)
union
select * from
(select col1 from mitable limit 1 offset
(select count(0) from mitable) -1);
But it uses up a lot of virtual machine steps (281,624,718).
Then this which is much more straightforward (which works if the table was created without WITHOUT ROWID) [sql keywords are in capitals]:
SELECT col1 FROM mitable
WHERE ROWID = (SELECT MIN(ROWID) FROM mitable)
OR ROWID = (SELECT MAX(ROWID) FROM mitable);
That ran with 55 virtual machine steps on the same table and produced the same answer.
min()/max() approach is wrong. It is only correct, if the values are ascending only. I needed something liket this for currency rates, which are random raising and falling.
This is my solution:
select st.*
from stats_ticker st,
(
select min(rowid) as first, max(rowid) as last --here is magic part 1
from stats_ticker
-- next line is just a filter I need in my case.
-- if you want first/last of the whole table leave it out.
where timeutc between datetime('now', '-1 days') and datetime('now')
) firstlast
WHERE
st.rowid = firstlast.first --and these two rows do magic part 2
OR st.rowid = firstlast.last
ORDER BY st.rowid;
magic part 1: the subselect results in a single row with the columns first,last containing rowid's.
magic part 2 easy to filter on those two rowid's.
This is the best solution I've come up so far. Hope you like it.
We can do that by the help of Sql Aggregate function, like Max and Min. These are the two aggregate function which help you to get last and first element from data table .
Select max (column_name ), min(column name) from table name
Max will give you the max value means last value and min will give you the min value means it will give you the First value, from the specific table.