PostgreSQL is it possible to parameterize the table name used in a query? - sql

In PostgreSQL, is it possible to parameterize the table name used in a query?

Think of parameters as a replacement for scalar values only. Use one parameter in the place where you could use one string literal or numeric literal.
You cannot use parameters for other parts of an SQL query:
Identifiers like table names, column names, etc.
SQL keywords
Expressions
Lists of values, such as in an IN (...) predicate. Each value in the list would need an individual parameter.
All those parts of the SQL query must be fixed by the time the query is parsed during prepare(). If a client library supports "parameters" for identifiers, it's really doing string-interpolation into the SQL query before the query is parsed.

Related

'Where' Query with Rails Arel Table That Matches to an Enum (How to force query as type text)

I am trying to use an arel table to match all instances of a column in my table that match a regular expression. This works easily with strings but when the search field is an enum it does not work.
My code for querying my database is as follows:
res = Test::Table
arel_tbl = res.arel_table["spec_type"].parameterize.underscore.to_sym
res = res.where(arel_tbl.matches("%#NewProd%"))
So with the above code the query works if my "spec_type" column contains values of type string, but in my instance all of the values under that column are enums, so I need to convert them to text to compare against the regular expression.
An example of an ActiveRecord query that works this way can be seen below:
Test::Table.where("spec_type::text like '%NewProd%'")
So this query works because I force spec_type to be of type text which allows my SQL query to call LIKE against the regular expression. How can I get the same sort of functionality with an arel table? I want the arel table because it auto quotes my data.

HIve/Impala Converting String into Lower case before using in hql

I need to convert the name of the table into lower before passing it for the query.
Irrespective of which case in pass the value for parameter $1 i need it to be converted into lower case before executing the below query.
QUERY:
show tables like '$1';
I have tried something like
QUERY
show tables like 'lower($1)';
But this doesn't work.
please help.
Your response would be highly appreciated
Impala identifiers are always case-insensitive. That is, tables named
t1 and T1 always refer to the same table, regardless of quote
characters. Internally, Impala always folds all specified table and
column names to lowercase. This is why the column headers in query
output are always displayed in lowercase.
Impala Documentation
All the below queries will give same result as internally impala converts to lowercase.
show tables like 'test*';
show tables like 'TeSt*';
show tables like 'TEST*';

Determine if substring corresponds to specific code (character types) in SQL

I have a collection of strings and want to filter out those where the last four characters are: (alpha)(alpha)(number)(number).
I know I can make a substring of each of these and separately, but what is the method to determine the types of the characters in the sequence?
This is for SQL in Hive.
You can use regular expressions. Something like:
where col regexp '[a-zA-Z]{2}[0-9]{2}$'

What is the difference between single and double quotes in SQL?

What is the difference between single quotes and double quotes in SQL?
Single quotes are used to indicate the beginning and end of a string in SQL. Double quotes generally aren't used in SQL, but that can vary from database to database.
Stick to using single quotes.
That's the primary use anyway. You can use single quotes for a column alias — where you want the column name you reference in your application code to be something other than what the column is actually called in the database. For example: PRODUCT.id would be more readable as product_id, so you use either of the following:
SELECT PRODUCT.id AS product_id
SELECT PRODUCT.id 'product_id'
Either works in Oracle, SQL Server, MySQL… but I know some have said that the TOAD IDE seems to give some grief when using the single quotes approach.
You do have to use single quotes when the column alias includes a space character, e.g., product id, but it's not recommended practice for a column alias to be more than one word.
A simple rule for us to remember what to use in which case:
[S]ingle quotes are for [S]trings Literals (date literals are also strings);
[D]ouble quotes are for [D]atabase Identifiers;
Examples:
INSERT INTO "USERS" ("LOGIN", "PASSWORD", "DT_BIRTH") VALUES ('EDUARDO', '12345678', '1980-09-06');
In MySQL and MariaDB, the ` (backtick) symbol is the same as the " symbol. And note that you can't use " for literal strings when your SQL_MODE has ANSI_QUOTES enabled.
Single quotes delimit a string constant or a date/time constant.
Double quotes delimit identifiers for e.g. table names or column names. This is generally only necessary when your identifier doesn't fit the rules for simple identifiers.
See also:
Do different databases use different name quote?
You can make MySQL use double-quotes per the ANSI standard:
SET GLOBAL SQL_MODE=ANSI_QUOTES
You can make Microsoft SQL Server use double-quotes per the ANSI standard:
SET QUOTED_IDENTIFIER ON
In ANSI SQL, double quotes quote object names (e.g. tables) which allows them to contain characters not otherwise permitted, or be the same as reserved words (Avoid this, really).
Single quotes are for strings.
However, MySQL is oblivious to the standard (unless its SQL_MODE is changed) and allows them to be used interchangably for strings.
Moreover, Sybase and Microsoft also use square brackets for identifier quoting.
So it's a bit vendor specific.
Other databases such as Postgres and IBM actually adhere to the ansi standard :)
I use this mnemonic:
Single quotes are for strings (one thing)
Double quotes are for tables names and column names (two things)
This is not 100% correct according to the specs, but this mnemonic helps me (human being).
Two Things To Remember :
Single Qutoes(') : String Or Text
select * from employees where room_name = 'RobinCapRed';
where RobinCapRed is a string or a text.
Double Quotes(") : Column Names or Table Names
select "first_name" from "employees";
where first_Name is a column name from employees table
The difference lies in their usage. The single quotes are mostly used to refer a string in WHERE, HAVING and also in some built-in SQL functions like CONCAT, STRPOS, POSITION etc.
When you want to use an alias that has space in between then you can use double quotes to refer to that alias.
For example
(select account_id,count(*) "count of" from orders group by 1)sub
Here is a subquery from an orders table having account_id as Foreign key that I am aggregating to know how many orders each account placed. Here I have given one column any random name as "count of" for sake of purpose.
Now let's write an outer query to display the rows where "count of" is greater than 20.
select "count of" from
(select account_id,count(*) "count of" from orders group by 1)sub where "count of" >20;
You can apply the same case to Common Table expressions also.

How to parse a string and create rows in SQL (postgres)

I have a single database field that contains a start date, end date, and exclusions in the form
available DD/MONTH/YYYY [to DD/MONTH/YYYY]?[, exclude WORD [, WORD]*]?
Meaning it always starts with "available DD/MONTH/YYYY", optionally has a single "to DD/MONTH/YYYY", and optionally has an exclude clause that is a comma separated list of strings. Think regular expression meanings for + , *, and ?
I have been tasked with extracting the data out so we will now have a "startdate" column, "enddate" column, and a new table that will contain the exclusions. It will need to fill the startdate and enddate columns with the values parsed from the availability string. It will also need to create multiple records in the new exclusion table, one for each of the comma separate values after the 'exclude' key word in the availability string.
Is this a migration I can do in SQL only (postgres 8.4)?
This is against postgres 8.4.
Update: With the help of a co-worker we now have a sql script that has as it's results sql to perform the insert statements based on the parsing of the exclusions. It uses a bunch of case statements and string manipulation within the sql to generate the results. I then send the output to a file and execute that file to perform the inserts. I am doing the same for the start and end date columns.
It's not 100% sql, but a simple .bat or .sh file that runs the first .sql file, then the generated one is all that is needed to get it to go.
Thanks for the input.
You can probably do that with a combination of the regexp functions ( and the to_date() or to_timestamp() functions.
But it may be easier to just mangle the text in a function in say pl/perl. That'll get you access to the full manipulation functions in perl, while keeping the work inside the database as seems to be your specification.
why single SQL?
Write simple script in Ruby/Python/Basic to read data from the source, parse it, and put into destination database.
Or it is so big?