MariaDB to calculate table reference in select query - sql

I have a quite dumb client application that wants to get information from MariaDB based on a parameter.
This parameter is a string that contains spaces, like 'valid parameter'.
In MariaDB there is a table for each of the possible string values, and the table name is the string value after spaces have been replaced by underscores and a prefix is added. So I can perform the necessary conversion like this:
SELECT CONCAT('prefix_', REPLACE('valid parameter',' ','_'));
Now the result 'prefix_valid_parameter' is the table to query, so actually I need to fire off
SELECT * from CONCAT('prefix_', REPLACE('valid parameter',' ','_'));
but MariaDB responds with
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '('prefix_', REPLACE('valid parameter',' ','_'))' at line 1
I would have expected either the content of table 'prefix_valid_parameter' or an error stating "table 'prefix_valid_parameter' not found". How can I make the table_reference part of my SQL SELECT statement dynamic?

You need to use dynamic SQL:
set #sql = 'select * from [table]';
execute immediate replace(#sql, '[table]',
concat('prefix_', replace('valid parameter', ' ', '_'))
);
I should add that the need to do this perhaps suggests a flaw in your data model. If the tables have the same structure, it is better to put all the rows in a single table.

Related

SQL injection payload after order by in SQL query

Trying to exploit SQL injection for my assignment. Is it possible to execute delete or drop query after order by in select query without using the semicolon in Postgresql?
This is my sample query:
Select *
from table
order by {sql injection payload}
Without using the semicolon in the payload, can we delete data or drop a table?
https://stackoverflow.com/a/6800585
Do we have similar to this Postgrsql?
I tried
Select * from (delete from table_name returning *) a
But getting sql error as 'syntax error at or near from'
Check this document it says we can bypass forbidden character by CHR()
https://book.hacktricks.xyz/pentesting-web/sql-injection/postgresql-injection
DELETE cannot be put inside a subquery. Nor can DELETE be part of a UNION.
So aside from running a second query (that is, separated by a semicolon), there's almost no way you can do what you describe.
You could invoke a stored procedure or function, if you knew of an existing function that performs a DELETE. Example:
Select *
from table
order by {sql injection payload}
After your payload modifies this query:
Select *
from table
order by SomeFunctionThatDeletes()
Another type which works because you can select from a procedure in PostgreSQL:
Select *
from table
order by id
UNION
Select *
from SomeProcedureThatDeletes()
You can't create the function or procedure with SQL injection, so that routine must exist already, and you would need to know its name and how to call it.
DELETE or DROP TABLE are not the only bad things that can happen from SQL injection. It could be a problem if the query returns data that the current user shouldn't have privilege to see. For example, records about a different user's purchases or medical history.
SQL injection can also be accidental instead of malicious. I would even say that most instances of SQL injection result in simple errors instead of data breaches. Those aren't really attacks, but they lead to an unsatisfactory experience for your users.

psql column doesn't exist but it does

I am trying to select a single column in my data table using raw SQL in a postgresql database from the psql command line. I am getting an error message that says the column does not exist. Then it gives me a hint to use the exact column that I referenced in the select statement. Here is the query:
SELECT insider_app_ownershipdocument.transactionDate FROM insider_app_ownershipdocument;
Here is the error message:
ERROR: column insider_app_ownershipdocument.transactiondate does not exist
SELECT insider_app_ownershipdocument.transactionDate FROM in...
HINT: Perhaps you meant to reference the column "insider_app_ownershipdocument.transactionDate".
I have no idea why this is not working.
(Postgres) SQL converts names automatically to lower case although it support case-sensitive names. So
SELECT insider_app_ownershipdocument.transactionDate FROM insider_app_ownershipdocument;
will be aquivalent to:
SELECT insider_app_ownershipdocument.transactiondate FROM insider_app_ownershipdocument;
You should protect the column name with double quotes to avoid this effect:
SELECT insider_app_ownershipdocument."transactionDate" FROM insider_app_ownershipdocument;

How to store the result of select statement into the temporary table in Oracle?

We can write select column1,column2 into #temp from tableName in SQL Server. But I am unable to write the same query in an Oracle database.
I want to store the result of select/insert/delete/update or any result set into a local temporary table in oracle database. How I can do this?
I am executing below query in my Oracle sql developer tool:
select * into #temp
from bmi;
but I am getting the error as follow please help to find this error.
when I execute the same query in Microsoft SQL Server it get executed & #temp table get created which is not present in the database but it can hold the data for that particular session. so i want same scenario in ORACLE database.
ORA-00911: invalid character
00911. 00000 - "invalid character"
*Cause: identifiers may not start with any ASCII character other than
letters and numbers. $#_ are also allowed after the first
character. Identifiers enclosed by doublequotes may contain
any character other than a doublequote. Alternative quotes
(q'#...#') cannot use spaces, tabs, or carriage returns as
delimiters. For all other contexts, consult the SQL Language
Reference Manual.
*Action:
Error at Line: 1 Column: 15
I want to store the result of select/insert/delete/update or any result set into a local temporary table in oracle database,How I can Do This?
You can't. Oracle doesn't have local temporary tables, it doesn't work like that. But it doesn't need to. Oracle has a very different internal model from SQL Server which means a lot of SQL Server practices are unnecessary in Oracle. (To be fair SQL Server has neat things which Oracle doesn't, like ANSI 92 Joins for DML.)
The key insight is: you don't want to store the result of select/insert/delete/update or any result set into a local temporary table. That is something you had to do in T-SQL to achieve the end goal of implementing some business logic. But what you actually wanted to do in SQL Server and what you want to do in Oracle is write some code which delivers value to your organisation.
So, with that mindset in place, what do you need to do?
If you want to loop round a result set then perhaps a Cursor Loop is what you're looking for?
for rec in ( select * from some_table
where the_date = date '2018-02-01' )
loop
...
If you want to work on some data prior to inserting it into a data then perhaps you should use a PL/SQL collection:
type l_recs is table of some_table%rowtype;
But maybe you just need to understand Oracle's Transaction Management model. A lot of things are possible in pure SQL without any need for procedural framework.
Create temporary table :
create global temporary table
results_temp (column1, column2)
on commit preserve rows;
and then insert to it from your table:
insert into results_temp (column1, column2 )
SELECT column1,column2
FROM source_table
create global temporary table temp_table_name
on commit preserve rows as select column1,column2,columnN from your_table;

Error show when update using phpmyadmin

When I update a column using phpmyadmin in database with following query
UPDATE members
SET `refered` = (SELECT COUNT (*)
FROM `user_details`
WHERE `user_details.sponser`=`members.username`
)
It show a error message like this
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '*) FROM `user_details` WHERE `user_details.sponser`=`members.username`)' at line 1
What may be reason?
Error is in
COUNT (*)
-----^
Remove the space between COUNT and (*).
Try the below query
UPDATE members SET refered = (SELECT COUNT(*) FROM user_details
WHERE user_details.sponser=members.username)
Does the Select query returns any result. If so what is the result. Looks like all your query is inside '' single quotes that you are using it should be removed. Single quotes need to be removed for example .
UPDATE members
SET refered = (SELECT COUNT (*)
FROM user_details
WHERE user_details.sponser=members.username
)
-- there is not single quotes in the query above. please remove it from yours.
Part of your problem, or maybe the whole problem, is the WHERE clause. You've used backticks for the table name, which is correct (or, at least, it's optional in this case; it's needed if your database name or table name has a MySQL reserved name or is otherwise ambiguous). The problem, though, is that the dot separating the database from the table needs to be outside the backticks. So your WHERE clause should look like this instead:
WHERE `user_details`.`sponser`=`members`.`username`

returning emptystring if columnn name not exists

I have a very simple select statement like
SELECT Column-Name
FROM Object
WHERE ID = 123
where the Column-Name is dynamically generated. Is there a possibility to get an empty string if column not exists?
This is a huge hack for SQL Server
SQL is batch based: when submitted to the database engine, the whole batch is parse and a plan compiled. If a column or object does not exist, you'll get an error.
You can test the metadata to see if it exists (COLUMNPROPERTY) then use EXEC to have the SELECT in an separate batch
IF COLUMNPROPERTY(OBJECT_ID('Object'), 'Column-Name', 'ColumnID') IS NOT NULL
EXEC ('SELECT Column-Name FROM Object WHERE ID = 123')
ELSE
SELECT '' AS Column-Name;
Personally, I'd never expect this to be in production code or running on my database servers.
Why not do a desc object or something similar and validate if the column name exists before firing the query?
Otherwise you will end up doing funny things to work around the sql error