Select query to retrieve the value of primary key for a specific row in a table - sql

I am struggling to retrieve the value of primary key for a table. We are using MS SQL Server 2005. The database was designed years back by somebody else (he didn't follow the normalization rules at all). He used Key (which is a keyword in sql server) as the column name for primary key of a table. So I cannot use query like this: select key from table_name where column2 = ?
Could anyone help to write a query to get the value of the primary key for a specific row something like this: select primary_key from tbale_name where column2 = ?

Yes you can, simply wrap column names in backticks:
select `key` from `table_name` where `column2` = ?
Alternatively, depending on your DB, you might use square brackets:
select table_name.[key] from table_name where table_name.[column2] = ?
Edit: I see you said "MS SQL". I think that one works with the square brackets. MySQL accepts the backtick syntax.

Related

One select for multiple records by composite key

Such a query as in the title would look like this I guess:
select * from table t where (t.k1='apple' and t.k2='pie') or (t.k1='strawberry' and t.k2='shortcake')
... --10000 more key pairs here
This looks quite verbose to me. Any better alternatives? (Currently using SQLite, might use MYSQL/Oracle.)
You can use for example this on Oracle, i assume that if you use regular concatenate() instead of Oracle's || on other DB, it would work too (as it is simply just a string comparison with the IN list). Note that such query might have suboptimal execution plan.
SELECT *
FROM
TABLE t
WHERE
t.k1||','||t.k2 IN ('apple,pie',
'strawberry,shortcake' );
But if you have your value list stored in other table, Oracle supports also the format below.
SELECT *
FROM
TABLE t
WHERE (t.k1,t.k2) IN ( SELECT x.k1, x.k2 FROM x );
Don't be afraid of verbose syntax. Concatenation tricks can easily mess up the selectivity estimates or even prevent the database from using indexes.
Here is another syntax that may or may not work in your database.
select *
from table t
where (k1, k2) in(
('apple', 'pie')
,('strawberry', 'shortcake')
,('banana', 'split')
,('raspberry', 'vodka')
,('melon', 'shot')
);
A final comment is that if you find yourself wanting to submit 1000 values as filters you should most likely look for a different approach all together :)
select * from table t
where (t.k1+':'+t.k2)
in ('strawberry:shortcake','apple:pie','banana:split','etc:etc')
This will work in most of the cases as it concatenate and finds in as one column
off-course you need to choose a proper separator which will never come in the value of k1 and k2.
for e.g. if k1 and k2 are of type int you can take any character as separator
SELECT * FROM tableName t
WHERE t.k1=( CASE WHEN t.k2=VALUE THEN someValue
WHEN t.k2=otherVALUE THEN someotherValue END)
- SQL FIDDLE

Use result of query in a function (postgres 8.3)

I am trying to do something like this:
select char_length(select text_field from table where key = 1)
This won't work, and I presume, because the return type of a query is a table, not a string or text variable.
Is there a way to specify row,col of the result from a select statement?
edit: I overlooked to mention, that char_length is a function.
When passing the result of a query to a function, simply wrap the query in brackets:
select char_length((select text_field from table where key = 1));
The outer set of brackets is for the function, the inner set converts a query to a result.
This syntax is not specific to postgres - it applies to all SQL servers.
This link shows the above code executing correctly (thanks to #Fahim Parkar for this)
Although, you could re-factor your query to not require this syntax, nevertheless this is how you "pass the result of a query to a function".
select char_length(text_field) from "table" where key = 1
Assuming key is a primary key or unique key the first example below will work. It works only if the sub-query returns only 1 row. The second example will work for 1 or more rows.
select char_length((select text_field from table where key = 1));
select char_length(text_field) from table where key = 1;
It should be
select char_length(text_field) from "table" where key = 1
Also I believe, your table name is not table.

Netezza Sql query

I have a list of tables in a Netezza database and I want to get the name of primary key for each of the tables.
Can anyone provide me the query.
You can use this query.
SELECT * FROM _v_relation_keydata;
There is nothing sort of Primary Key thing in Netezza. If you want to look at the NULL or NOT NULL constraints for your required table you can enter the below commands from your nzsql command line
\d [YOURTABLENAME]
SELECT database
, schema
, constraintname
, relation as tablename
, conseq as seq
, attname as columnname, *
FROM _v_relation_keydata
where contype='p'
and schema='ADMIN'
order by relation, conseq
We do not have primary key concept in Netezza. If you are concerned about Not NULL columns following query will help you.
select * from _v_relation_column where NAME='TABLE_NAME' and ATTNOTNULL='Y';
The key(primary/foreign) concepts is not there in Netezza. But we can create primary keys in Netezza and this is created to sync the model with the outside data reporting tools like Informatica/Microstrategy.
You can look into the system view _v_relation_keydata.

Duplicate value in a postgresql table

I'm trying to modify a table inside my PostgreSQL database, but it says there is duplicate! what is the best way to find a duplicate value inside a table? kinda a select query?
Try Like This
SELECT count(column_name), column_name
from table_name
group by column_name having count(column_name) > 1;
If you try to change a value in a column that is part of the PRIMARY KEY or has a UNIQUE constraint and get this error there, then you should be able to find the conflicting row by
SELECT *
FROM your_table
WHERE conflicting_column = conflicting_value;
If conflicting_value is a character type, put it in single quotes (').
EDIT: To find out which columns are affected by the constraint, check this post.
First of all, determine which fields in your table have to be unique. This may be something marked as a Primary Key, a unique index based on one or more fields or a check constraint, again based on one or more fields.
Once you've done that, look at what you're trying to insert and work out whether it busts any of the unique rules.
And yes, SELECT statements will help you determine what's wrong here. Use those to determine whether you are able to commit the row.

Can we have the table name as "option" in MySQL?

I am very, very new to MYSQL.I tried to create a table named "option".
My SQL Query is :
create table option(
id int not null primary key auto_increment,
choice varchar(30)
)
While executing this query it shows the following error
Error Code : 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'option(
id int not null primary key auto_increment,
choice varchar(30)
)' at line 1
(0 ms taken)
If I try with the table name as "choice" it is working.
can we have the table name as "option" in mysql?
thanks
If you want to have a table name Option, you should be able to, just remember that whenever you use the table in a query, you will have to encase it in ` symbols. Like this.
`option`
The ` key on the top left of your keyboard, with the tilde.
Pick a different name (one that isn't a reserved word in your RDBMS) and save yourself and whoever else might work on it many headaches.
option is a reserved word in Mysql.we can use a reserved word by using the word inside a single quotes.
Better you select the other tablename.Ohterwise maintaining our code will be difficult.
You can use SQL keywords as table names in MySQL if you escape them with back-quotes.
CREATE TABLE `option` (
...
)
It's not normally a good idea to do so, though.
option is a reserved word in MySQL. Save yourself a world of pain and use choice for your table name.
See the MySQL documentation on this. You can do it as follows:
create table `option` (
...
)
Yes you can definitely create a table named option but in every query you will have to use
`option`
instead of plain option. Better improvise a little and create a table named options to save from trouble. Restrain from using mysql reserved words as table name or column name or procedure names.