Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL obtaining the last two digits of integer

Tags:

sql

postgresql

I need to obtain the last two digits of an integer. Each element placed in the tables comes as a full year ie. YYYY and I only want the last two digits, so that all the fields show

YEAR
----
09
00
89

where the initialy field was

YEAR
----
2009
2000
1989

EDIT: I get a complaint saying,

HINT: No function matches the given name and argument types. You might need to add explicit type casts.

when i try

select right(cast(year as char),2) from subjects;

like image 347
SNpn Avatar asked Apr 18 '12 08:04

SNpn


People also ask

How do I get the last two digits of a number in SQL?

To check the last two digits are numbers in column, you can use the following script. Here RIGHT(your_column,2) will return the last two digits from the string.

How do I get last 3 digits in SQL?

It could be this using the SUBSTR function in MySQL: SELECT `name` FROM `students` WHERE `marks` > 75 ORDER BY SUBSTR(`name`, -3), ID ASC; SUBSTR(name, -3) will select the last three characters in the name column of the student table.

How do I get the last number in SQL?

We can use the ORDER BY statement and LIMT clause to extract the last data. The basic idea is to sort the sort the table in descending order and then we will limit the number of rows to 1. In this way, we will get the output as the last row of the table. And then we can select the entry which we want to retrieve.


2 Answers

Postgres has borrowed (or inherited) the modulus operator from C:

SET search_path='tmp';

CREATE TABLE lutser ( year integer);

INSERT INTO lutser (year)
        SELECT generate_series(1991,2012)
    ;

SELECT year
    , year / 100 as c2
    , year % 100 AS y2
    FROM lutser
    ;

Result:

CREATE TABLE
INSERT 0 22
 year | c2 | y2 
------+----+----
 1991 | 19 | 91
 1992 | 19 | 92
 1993 | 19 | 93
 1994 | 19 | 94
 1995 | 19 | 95
 1996 | 19 | 96
 1997 | 19 | 97
 1998 | 19 | 98
 1999 | 19 | 99
 2000 | 20 |  0
 2001 | 20 |  1
 2002 | 20 |  2
 2003 | 20 |  3
 2004 | 20 |  4
 2005 | 20 |  5
 2006 | 20 |  6
 2007 | 20 |  7
 2008 | 20 |  8
 2009 | 20 |  9
 2010 | 20 | 10
 2011 | 20 | 11
 2012 | 20 | 12
(22 rows)
like image 113
wildplasser Avatar answered Oct 04 '22 00:10

wildplasser


select substring(CAST(2012 as CHAR(4)), 3, 2)
like image 39
juergen d Avatar answered Oct 03 '22 23:10

juergen d