similar to last() in sql, what can i use in derby database? - sql

Select Last(column_name) from table_name will return the last value in the column in standard SQL. What is a similar query that will work in derby to fetch the last value in the column?
Please find the sample table below: 'secondcol' is the column name in the table.
secondcol
33
45
78
Select Last(secondcol) from table_name in sql will return 78 as output. If i want to get similar output in javadb/derby database, how can i query it? I don't want to change any order in the column values.

To select last row in table is little bit different then it is in pure SQL:
SQL:
SELECT * FROM tableName ORDER BY id DESC LIMIT 1;
DERBY:
SELECT * FROM tablename ORDER BY id DESC FETCH FIRST ROW ONLY;
Have a nice day ;)

Is there some unique key on the table where you could form the question as "give me the secondcol value on the row with the max key value"? If so, there is a technique that will work in any database engine - the idea is to concatenate the key plus any desired result data, perform a min/max, then extract the result data.
See here and here.

Related

SQL query put nth match in new column

I am using SQL in Microsoft access. The table may contain more than one value for a bar code. I want to a query that returns one row with each unique bar code and columns for each of the first 5 values. Right now, I have a query returning the last value or the first value with min or max. How can I show the second result in the next column? or the nth result in that column? This is in Access but any other SQL help would be appreciated.
Current table:
Current query:
SELECT table.barcode, MIN(table.value)
FROM table
GROUP BY table.barcode
Current output:
Goal query output:
You can use aggregation:
SELECT table.barcode,
MIN(table.value),
IIF(MIN(table.value) = MAX(table.value), MAX(table.VALUE), NULL)
FROM table
GROUP BY table.barcode

How do I select a value in a key:value pair within a list in a column using SQL?

In a table called payouts, there is a column stripeResponseData where the data is in the following structure:
{"id":"tr_1BlSHbGQXLV7RqqnHJffUVO0","object":"transfer","amount":39415,"amount_reversed":0,"balance_transaction":"txn_1BlSHbGQXfV7AqqnGi2o7UiY","created":1516239215,"currency":"usd","description":null,"destination":"acct_1BWWAmAzms5xPfV9","destination_payment":"py_1BlSHbAzms5xkfV91RHAOrno","livemode":true,"metadata":{},"reversals":{"object":"list","data":[],"has_more":false,"total_count":0,"url":"/v1/transfers/tr_1BlSHbYQXLV7AqqnHJffUVO0/reversals"},"reversed":false,"source_transaction":null,"source_type":"card","transfer_group":null}
Within my SQL SELECT statement, I want to return only the value of the key "destination". How do I write my SQL query?
My desired result of the query:
SELECT "stripeResponseData" FROM payouts [...]
(where I don't know how to write [...]) should look like the following (assume we have 3 rows with different values on "destination"):
acct_1BWWAmAzms5xPfV9
acct_1AY0phDc9pCDpLR8
acct_1AwG3VL7DXxftOaS
How do I extract that value from the list within the stripeResponseData column?
See this sqlfiddle. This query will fetch the ID from stripResponseData where the id is a specific id (Probably not very useful, but does show you how to select and query):
SELECT data->>'id' FROM stripeResponseData WHERE data #> '{"id":"tr_1BlSHbGQXLV7RqqnHJffUVO0"}';
Because you mentioned your data was a string, you need to to type conversions to query/use it correctly. See this sqlfiddle:
SELECT data::jsonb->>'id' FROM stripeResponseData WHERE data::jsonb #> '{"id":"tr_1BlSHbGQXLV7RqqnHJffUVO0"}';
Per your edit, you can simply query destination in almost the exact same way. This will get all the id's from stripeResponseData where destination = acct_1BWWAmAzms5xPfV9:
SELECT data::jsonb->>'id' FROM stripeResponseData WHERE data::jsonb #> '{"destination":"acct_1BWWAmAzms5xPfV9"}';

SQL Server 2012 - Pagination without Order Clause

I found best approach for pagination in SQL Server 2012 is OFFSET FETCH Clause
SELECT First Name + ' ' + Last Name
FROM Employees
ORDER BY First Name OFFSET 10 ROWS;
It works fine.
Now in my case, my software generate SQL Server table dynamically and I just know table name.
I don't know columns name in dynamically generated table.
Now in this case how this pagination works ? because I don't know which column should be used with ORDER BY clause with OFFSET Fetch clause..
any alternative solution?
Thanks
You can order by column index if that helps:
SELECT First Name + ' ' + Last Name
FROM Employees
ORDER BY 1 OFFSET 10 ROWS;
This will order by the first column. If the ordering column is stored on the UI (controlled by users), then you need to store the column index on the UI and pass that to SQL Server to use in the ordering.
If you simply want to order by the order the records are added to the table, you will need a primary key, identity column. Make sure that is the first column on the table and use ORDER BY 1.
As #Tanner mentioned in his answer, in order to use his answer you have to put identity column as the first column of your query, if you can do that, use his answer, but if you can not, use (SELECT NULL) instead of 1, e.g:
SELECT First Name + ' ' + Last Name
FROM Employees
ORDER BY (SELECT NULL) OFFSET 10 ROWS;

SQL statement to get largest ID from database column

I have an ID column which it supposed to set to auto-increment but I forgot to set in when creating the database. Let's say the ID is from 1 - 20. I used the select Max() Sql statement to get the largest ID:
SELECT MAX(id) FROM Table_Name;
It supposed to return me 20. However, it returns me 9. I also realized that the id column in database is jumbled up. It starts from 1,2 then skips to 9,10 - 20 then back to 3 - 8. And 8 appears to be the last row and I think that's where the 9 comes from. My id in database is varchar() data type.
So, is there any way to amend my Sql statement to get the largest id in a list of sorted id?
Thanks in advance.
The issue is likely that the ID column is a varchar field, so 9 is greater than 10.
select max(convert(int, id)) from Table
Your column is a character type, not a numeric type, which explains everything you're seeing.
Try casting it to numeric:
select max(cast(id as signed)) from table
You haven't said which database you are using, so the syntax may vary to achieve the cast - consult online docs for your database.
Try this:
SELECT TOP 1 Id FROM Table ORDER BY Convert(INT, id) DESC

Retrieve the maximum length of a VARCHAR column in SQL Server

I want to find the longest VARCHAR in a specific column of a SQL Server table.
Here's an example:
ID = INT IDENTITY
DESC = VARCHAR(5000)
ID | Desc
---|-----
1 | a
2 | aaa
3 | aa
What's the SQL to return 3? Since the longest value is 3 characters?
Use the built-in functions for length and max on the description column:
SELECT MAX(LEN(DESC)) FROM table_name;
Note that if your table is very large, there can be performance issues.
For MySQL, it's LENGTH, not LEN:
SELECT MAX(LENGTH(Desc)) FROM table_name
Watch out!! If there's spaces they will not be considered by the LEN method in T-SQL. Don't let this trick you and use
select max(datalength(Desc)) from table_name
For Oracle, it is also LENGTH instead of LEN
SELECT MAX(LENGTH(Desc)) FROM table_name
Also, DESC is a reserved word. Although many reserved words will still work for column names in many circumstances it is bad practice to do so, and can cause issues in some circumstances. They are reserved for a reason.
If the word Desc was just being used as an example, it should be noted that not everyone will realize that, but many will realize that it is a reserved word for Descending. Personally, I started off by using this, and then trying to figure out where the column name went because all I had were reserved words. It didn't take long to figure it out, but keep that in mind when deciding on what to substitute for your actual column name.
Gives the Max Count of record in table
select max(len(Description))from Table_Name
Gives Record Having Greater Count
select Description from Table_Name group by Description having max(len(Description)) >27
Hope helps someone.
For SQL server (SSMS)
Option 1:
-- This returns number of characters
select MAX(LEN(ColumnName)) from table_name
Option 2:
-- This returns the number of bytes
select MAX(DATALENGTH(ColumnName)) from table_name
If you're using VARCHAR, use DATALENGTH. More details
SELECT TOP 1 column_name, LEN(column_name) AS Lenght FROM table_name ORDER BY LEN(column_name) DESC
Many times you want to identify the row that has that column with the longest length, especially if you are troubleshooting to find out why the length of a column on a row in a table is so much longer than any other row, for instance. This query will give you the option to list an identifier on the row in order to identify which row it is.
select ID, [description], len([description]) as descriptionlength
FROM [database1].[dbo].[table1]
where len([description]) =
(select max(len([description]))
FROM [database1].[dbo].[table1]
SELECT MAX(LEN(Desc)) as MaxLen FROM table
select * from table name from where length( column name) =(select MAX(Length(column name) from table name);
I am using subquery its 100 % work try this.
For IBM Db2 its LENGTH, not LEN:
SELECT MAX(LENGTH(Desc)) FROM table_name;