SELECT CONCAT alternative in PostgreSQL - mysql

How can I write the following MySQL query in PostgreSQL syntax:
SELECT CONCAT(REPEAT(" ", (COUNT(parent.name) - 1)), cat.name) AS name
Thanks in advance!

The error here is that PostgreSQL doesn't allow double quotes " for literal strings (as per the SQL standard). You'll need to use single quotes '.
You also need to cast (COUNT(parent.name) - 1) to an integer, either using ::int (specific to Postgre) or CAST(... AS int).
Note that this may raise an integer out of range error if (COUNT(parent.name) - 1) is superior to 2147483647.
SELECT CONCAT(REPEAT(' ', (COUNT(parent.name) - 1)::int), cat.name) AS name
Note that you can also use || for string concatenation :
SELECT REPEAT(' ', (COUNT(parent.name) - 1)::int) || cat.name AS name

SELECT REPEAT(" ", (COUNT(parent.name) - 1)) || cat.name AS name
SQLFIDDLE

Related

DBD::mysql::st execute failed: Unknown column

When I do the query below from a mysql console it works fine but when I wrap into perl/DBI I get:
DBD::mysql::st execute failed: Unknown column 'AR_email' in 'field list'
Here is the query:
my $q = "SELECT SUBSTRING(AR_email, LOCATE('#', AR_email) + 1) AS domain
FROM carrier
WHERE AR_email IS NOT NULL
AND SUBSTRING(AR_email, LOCATE('#', AR_email) + 1) =?";
my $sth=$dbh->prepare($q);
$sth->execute($domain);
Any idea how I can fix this?
The problem here is unintented string interpolation.
You are using double quotes (") when assigning the query string to $q, but it contains an arobas (#), which is interpolated.
So $q actually ends up containing:
SELECT SUBSTRING(AR_email, LOCATE(', AR_email) + 1) AS domain
FROM carrier
WHERE AR_email IS NOT NULL
AND SUBSTRING(AR_email, LOCATE(', AR_email) + 1) =?
If you were running this under use warnings, you would get this message:
Possible unintended interpolation of #' in string
One way to solve this is to define the query as a litteral string, for example:
my $q = q/SELECT SUBSTRING(AR_email, LOCATE('#', AR_email) + 1) AS domain
FROM carrier
WHERE AR_email IS NOT NULL
AND SUBSTRING(AR_email, LOCATE('#', AR_email) + 1) =?/;
Moral of the story:
use double quotes only when you do want string interpolation
always use strict; use warnings;

MySQL: Extract regexp value from query

I would need to get value from given regexp.
For example:
> :"postalCode";s:4:"3150";
Is there any way I can extract 3150, from this part of column value. Column value stored serialized objects, so postalCode variable can be null type, that way I should check if positive integer follows ;s:POSITIVE_INT:"postalCodeValue
Use SUBSTRING_INDEX:
SELECT
SUBSTRING(SUBSTRING_INDEX(col, '"', -2), 1,
INSTR(SUBSTRING_INDEX(col, '"', -2), '"') - 1) AS num
FROM yourTable;
This query will extract the last quoted number in your string.
Demo
avoiding regexp you could use some string function eg:
SELECT LENGTH(':"postalCode";s:4:"3150"') - LOCATE(':', REVERSE(':"postalCode";s:4:"3150"'))+1
from dual ;
or
SELECT LENGTH(col_name) - LOCATE(':', REVERSE(col_name))+1
from my_table ;
It also work with 2 times SUBSTRING_INDEX
SELECT
SUBSTRING_INDEX (SUBSTRING_INDEX( ':"postalCode";s:4:"3150";', '"',-2) , '"', 1);

Reversing string in SQL

I got an sql question. I have a table containing a column named title that store a string like this in all raws.
"Prenom - Nom (85)".
I would like to know if there is a way in sql to change that string like this :
"Nom - Prenom"
It means, I would like to reverse it and then delete the " (85).
Thank you in advance.
Yes:
select concat(substring_index(left(col, length(col) - instr(reverse(col), ' ')), ' - ', -1),
' - ',
substring_index(col, ' - ', 1)
)
This assume that you want something a bit more general than getting rid of the '(85)'; it removes the final word.
Ugly as hell and almost certainly won't work for all of your cases. But this works for the example you have posted:
select concat(
substring_index(substring_index("Prenom - Nom (85)"," (",1)," - ",-1),
" - ",
substring_index(substring_index("Prenom - Nom (85)"," (",1)," - ",1)
);

How to format int to price format in SQL?

I select the price 1000000 and I need to format it to $1,000,000. How can I do that in SQL?
To format with commas, you can use CONVERT with a style of 1:
declare #money money = 1000000
select '$' + convert(varchar, #money, 1)
will produce $1,000,000.00
If you want to remove the last 3 characters:
select '$' + left(convert(varchar, #money, 1), charindex('.', convert(varchar, #money, 1)) - 1)
and if you want to round rather than truncate:
select '$' + left(convert(varchar, #money + $0.50, 1), charindex('.', convert(varchar, #money, 1)) - 1)
Creating Function:
CREATE FUNCTION [dbo].[f_FormatMoneyValue]
(
#MoneyValue money
)
RETURNS VARCHAR(50)
AS
BEGIN
RETURN cast(#MoneyValue as numeric(36,2))
END
Using in Select Query:
Select dbo.f_FormatMoneyValue(isnull(SalesPrice,0))SalesPrice from SalesOrder
Output:
100.00
Formatting Money Value with '$' sign:
CREATE FUNCTION [dbo].[f_FormatMoneyWithDollar]
(
#MoneyValue money
)
RETURNS VARCHAR(50)
AS
BEGIN
RETURN '$' + convert(varchar, #MoneyValue, 1)
END
Output:
$100.00
Note: The above sample is for the money field. You can modify this function according to your needs
Hope this helps you..! :D
SELECT FORMAT(price, 'C2', 'en-us')
The SQL Server money datatype is just decimal(10, 4). To my knowledge there is no datatype that will present the way you want.
Adding the dollar sign and commas is something that should belong in the application logic, but if you really must do it through a database object consider adding the dollar sign, and commas every three characters (after the decimal point). In other words, you'll have to convert the int to varchar and do string manipulation.
It depends, however, there's no simple way to do it in standard SQL specs(SQL-92, SQL-2003, etc.).
For PostgreSQL PL/pgSQL and Oracle PL/SQL, you can use to_char to format numbers:
select to_char(1234567.123, 'FM$999,999,999.99')
Which gives output:
$1,234,567.12
See: http://www.postgresql.org/docs/7/static/functions2976.htm

Search for text between delimiters in MySQL

I am trying to extract a certain part of a column that is between delimiters.
e.g. find foo in the following
test 'esf :foo: bar
So in the above I'd want to return foo, but all the regexp functions only return true|false,
is there a way to do this in MySQL
Here ya go, bud:
SELECT
SUBSTR(column,
LOCATE(':',column)+1,
(CHAR_LENGTH(column) - LOCATE(':',REVERSE(column)) - LOCATE(':',column)))
FROM table
Yea, no clue why you're doing this, but this will do the trick.
By performing a LOCATE, we can find the first ':'. To find the last ':', there's no reverse LOCATE, so we have to do it manually by performing a LOCATE(':', REVERSE(column)).
With the index of the first ':', the number of chars from the last ':' to the end of the string, and the CHAR_LENGTH (don't use LENGTH() for this), we can use a little math to discover the length of the string between the two instances of ':'.
This way we can peform a SUBSTR and dynamically pluck out the characters between the two ':'.
Again, it's gross, but to each his own.
This should work if the two delimiters only appear twice in your column. I am doing something similar...
substring_index(substring_index(column,':',-2),':',1)
A combination of LOCATE and MID would probably do the trick.
If the value "test 'esf :foo: bar" was in the field fooField:
MID( fooField, LOCATE('foo', fooField), 3);
I don't know if you have this kind of authority, but if you have to do queries like this it might be time to renormalize your tables, and have these values in a lookup table.
With only one set of delimeters, the following should work:
SUBSTR(
SUBSTR(fooField,LOCATE(':',fooField)+1),
1,
LOCATE(':',SUBSTR(fooField,LOCATE(':',fooField)+1))-1
)
mid(col,
locate('?m=',col) + char_length('?m='),
locate('&o=',col) - locate('?m=',col) - char_length('?m=')
)
A bit compact form by replacing char_length(.) with the number 3
mid(col, locate('?m=',col) + 3, locate('&o=',col) - locate('?m=',col) - 3)
the patterns I have used are '?m=' and '&o'.
select mid(col from locate(':',col) + 1 for
locate(':',col,locate(':',col)+1)-locate(':',col) - 1 )
from table where col rlike ':.*:';
If you know the position you want to extract from as opposed to what the data itself is:
$colNumber = 2; //2nd position
$sql = "REPLACE(SUBSTRING(SUBSTRING_INDEX(fooField, ':', $colNumber),
LENGTH(SUBSTRING_INDEX(fooField,
':',
$colNumber - 1)) + 1)";
This is what I am extracting from (mainly colon ':' as delimiter but some exceptions), as column theline255 in table loaddata255:
23856.409:0023:trace:message:SPY_EnterMessage (0x2003a) L"{#32769}" [0081] WM_NCCREATE sent from self wp=00000000 lp=0023f0b0
This is the MySql code (It quickly did what I want, and is straight forward):
select
time('2000-01-01 00:00:00' + interval substring_index(theline255, '.', 1) second) as hhmmss
, substring_index(substring_index(theline255, ':', 1), '.', -1) as logMilli
, substring_index(substring_index(theline255, ':', 2), ':', -1) as logTid
, substring_index(substring_index(theline255, ':', 3), ':', -1) as logType
, substring_index(substring_index(theline255, ':', 4), ':', -1) as logArea
, substring_index(substring_index(theline255, ' ', 1), ':', -1) as logFunction
, substring(theline255, length(substring_index(theline255, ' ', 1)) + 2) as logText
from loaddata255
and this is the result:
# LogTime, LogTimeMilli, LogTid, LogType, LogArea, LogFunction, LogText
'06:37:36', '409', '0023', 'trace', 'message', 'SPY_EnterMessage', '(0x2003a) L\"{#32769}\" [0081] WM_NCCREATE sent from self wp=00000000 lp=0023f0b0'
This one looks elegant to me. Strip all after n-th separator, rotate string, strip everything after 1. separator, rotate back.
select
reverse(
substring_index(
reverse(substring_index(str,separator,substrindex)),
separator,
1)
);
For example:
select
reverse(
substring_index(
reverse(substring_index('www.mysql.com','.',2)),
'.',
1
)
);
you can use the substring / locate function in 1 command
here is a mice tutorial:
http://infofreund.de/mysql-select-substring-2-different-delimiters/
The command as describes their should look for u:
**SELECT substr(text,Locate(' :', text )+2,Locate(': ', text )-(Locate(' :', text )+2)) FROM testtable**
where text is the textfield which contains "test 'esf :foo: bar"
So foo can be fooooo or fo - the length doesnt matter :).