SQL statement to get largest ID from database column - sql

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

Related

Get the greatest value in a nvarchar column

I'm developing a database with SQL Server 2012 SP2.
I have a table with a NVARCHAR(20) column, and it will have numbers: "000001", "000002", etc.
I need to get the greatest value in that column and convert it to int. How can I do it?
I have found that I can convert a nvarchar to int with this sql sentence:
SELECT CAST(YourVarcharCol AS INT) FROM Table
But I don't know how can I get the max value in that column because the numbers are nvarchar.
UPDATE:
By the way, this column is NVARCHAR because I need to store text on it. I'm testing my solution and I need to store ONLY numbers to test it.
If your numbers are padded like in the example given and all have the same width, you can just sort them alphanumerically and then cast the max-value to INT or BIGINT (depending on your numbers range).
If there are very many rows it was much faster, especially if there is an index on this column...
Something like
SELECT TOP 1 * FROM YourTable
ORDER BY NumberColumn DESC
or, if you need the max-value only:
SELECT MAX(NumberColumn) FROM YourTable
If you have to deal with negative numbers or differently padded numbers you have to cast them first
SELECT TOP 1 * FROM YourTable
ORDER BY CAST(NumberColumn AS INT) DESC
or
SELECT MAX(CAST(NumberColumn AS INT)) FROM YourTable
Please note:
If you've got very many rows, the second might get rather slow. Read about sargable
If your NumberColumn might include invalid values, you have to check, Read about ISNUMERIC().
The best solution - in any case - was to use an indexed numeric column to store these values
Try this one...
I think MAX is enough.
SELECT max(CAST(YourVarcharCol AS INT)) FROM Table
Try this
SELECT MAX(t.Y) from (SELECT CAST(YourVarcharCol AS INT) as Y FROM Table) t
You should try this on finding the highest value:
SELECT MAX(CAST(YourVarcharCol AS INT)) AS FROM Table
If all the data follow the same padding and formatting pattern, a simple max(col) would do.
However, if not, you have to cast the values to int first. Searching on a columns cast to some other datatype will not use an index, if there's any, but will scan the whole table instead. It may or may not be OK for you, depending on requirements and number of rows in the table. If performance is what you need, then create a calculated column as try_cast( col as int), and create an index on it.
Note that you should not use cast, but try_cast instead, to guard against values that can't be cast (if you use a datatype to store something which is essencially of another datatype, it always opens up a possibility for errors).
Of couse, if you can change the original column's type to int, it would be the best.
This will return max int value
SELECT MAX(IIF(ISNUMERIC(YourVarcharCol) = 1, YourVarcharCol, '0') * 1) FROM Table
You can use like this
select max(cast(ColumnName AS INT ))from TableName

Why does this oracle query return null? (avg on number field)

I'm pulling my hair out this morning, as I'm trying to select a simple average from a single field from a table in an Oracle database. My table has 31 rows, the column in question is called AGE and I just want an average. The column is of type "number" and there are no nulls in it.
SELECT AVG(AGE)
FROM COLLECTIONS.CUSTOMERS
This query always returns null. I have also tried:
SELECT SUM(AGE)/COUNT(AGE)
FROM COLLECTIONS.CUSTOMERS
with the same result. Any help is greatly appreciated!
I have tried creating a sample table with single column (age). I kept data type int and number both and getting expected result:
INTEGER : Demo
NUMBER : Demo
NUMBER (with same datatype as OP): Demo

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

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.

sql query for retrieving default or sorted values

im trying to figure out how to write a sql query for this:
I have a database which contains a column X. X has datetime values if set by a function otherwise it has a default value which looks something like this 0001-01-01.00.00.00.000000
What I am interested in doing is writing sql that will retrieve all the rows of X sorted by latest datetime values.
I thought this would be the answer
Select * from Some_Table st where st.Dbname = "blah" order_by st.x desc
but then I was thinking what happens to the default values? how do they affect the sorting
Any ideas if this is the way to go?
Ordering by date desc will work fine. Why not make the column nullable so you don't need a default? Also it sounds like you only want the latest single record so you may want to consider using SELECT TOP 1 * FROM blah ORDER BY date 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;