So after googling this simple question, I could have not find an answer anywhere. I only have very basic database knowledge, and I need a query in Oracle to properly select a row given a table name and a primary key. Most examples I have found all find rows based of a row number or rowID (is that the same as primary key?).
Any help on this would be greatly appreciated.
Do you have the primary key column and the value you want to query? Where or what exactly did you search for? This is a very basic SELECT statement in any relational database:
SELECT *
FROM table_name
WHERE primary_key_column = primary_key_value
Unless, of course, I didn't understand the question.
A primary key is a unique identifier for a row in a table. Each row will have a primary key that is different from all other rows. This key can be one value, such as a rowID, or it can be a composite value (multiple columns used as a primary key because there may not be a need for an extra column only to store a rowID).
#tilley31 above shows a great example of how to search for a specific row in a table. If the primary key was composite;
SELECT *
FROM table_name
WHERE primary_key_column1 = primary_key_value1
AND primary_key_column2 = primary_key_value2
ROWID is a pseudocolumn that returns the address of a row and is usually unique, exception being where more than one table is stored in a same cluster then those tables rows can share the same rowid. ROWID is implicitly given by the oracle to rows.
Primary key uniquely identifies a row at a table level and is created by the user who created the table.
Getting the ROWID of a Row
SELECT ROWID,FIELDNAME FROM ABC;
Getting the PRIMARY Key of a table
SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME='YOUR_TABLENAME'
AND CONSTRAINT_TYPE='P';
I guess you are intent to dynamically choose table and where clauses in query (?)
If this is what you want to do then answer is No. Its not possible just through query. You could achieve it through pl/sql. and if you must have this as a query consider using a table function like below -
SELECT * FROM TABLE(func('TABLE_NAME','WHERE_CONDITION'))
Check out this link: https://oracle-base.com/articles/misc/pipelined-table-functions
Again this requires you to have preset output columns (COLUMN1, COLUMN2 etc). You will not be able to select exact column names from table.
Overall this is going to be messy.
Related
I have multiple tables with a unique column name for each of their primary key such as: DeviceName, DeviceNumber, SwitchNumber, Etc.
There is another table which serves as an audit trail containing the changes from all tables, it lists the table name and the primary key value for each respective table as a reference i.e.
Table#2
TableName, InstanceNumber
I would like to use the information in table #2 to pull the respective records from each table in 'TableName' by referencing the 'InstanceNumber' attribute as the PK for each respective table without having to manually create a reference for each table's column name.
Is there a way I can do this? That is, create a query that references a 'general' column name to a table that points to the primary key column?
Select * from (TableName) where (PrimaryKeyColumn) = (InstanceNumber);
You can only do this using dynamic SQL -- in PL/SQL, that would be execute immediate.
Why not? Here is one reason. All the columns returned by a query need to be known when the query is compiled. That is, before any data is read. You are requesting a set of columns that depends on the table that is in the data. So, the columns are NOT known and the query cannot be compiled.
I have a SQL server table on which I insert account wise data. Same account number should not be repeated on the same day but can be repeated if the date changes.
The customer retrieves the data based on the date and account number.
In short the date + account number is unique and should not be duplicate.
As both are different fields should I concatenate both and create a third field as primary key or there is option of having a primary key on the merge value.
Please guide with the optimum way.
You can create a composite primary key. When you create the table, you can do this sort of thing in SQL Server;
CREATE TABLE TableName (
Field1 varchar(20),
Field2 INT,
PRIMARY KEY (Field1, Field2))
Take a look at this question which helps with each flavour of SQL
How can I define a composite primary key in SQL?
PLEASE HAVE A LOOK, IT WILL CLEAR MOST OF THE DOUBTS !
We can state 2 or more columns combined as a primary key.
In that case every column included in primary key will be called : Composite Key
And mind you Composite keys can never be null !!
Now, first let me show you how to make 2 or more columns as primary key.
create table table_name ( col1 type, col2 type, primary key(col1, col2));
The benefit is :
col1 has value (X) and col2 has value (Y) then no other row can have col1 as (X) and col2 as (Y).
col1, col2 must have some values, they can't be null !!
HOPE THIS HELPS !
Not at all. Just use a primary key constraint:
alter table t add constraint pk_accountnumber_date primary key (accountnumber, date)
You can also include this in the create table statement.
I might suggest, however, that you use an auto-incrementing/identity/serial primary key -- a unique number for each row. Then declare the account number/date combination as a unique key. I prefer such synthetic primary keys for several reasons:
They make it easy to refer to a row in foreign key relationships.
They show the insert order into the table, so you can readily see the last inserted rows.
They make it simple to identify a single row for updates and deletes.
They hide the "id" information of the row from referring tables and applications.
The alternative is to have a PK which is an autoincrementing number and then put a unique unique index on the natural key. In this way uniqueness is preserved but you have the fastest possible joining to any child tables. If the table will not ever have child tables, the composite PK is a good idea. If there will be many child tables, this is could be a better choice.
I have two SQL databases with the same schema. Both have different Data but are using the same primary keys. I want to add the Data from one database to the second one, but all solution I found just update the rows with the same primary keys and dont attach them at the end.
Anyone has a solution?
If your primary key column is an ID field that uses an auto-incrementing sequence (if not, then how would you choose a different primary key for overlapping records anyway?), you should just be able to insert the records from the first schema, excluding the ID in your select query.
For example:
Table Schema:
ID INT(10)
Name VARCHAR(20)
Desc TEXT
SQL
INSERT INTO schema2.table (Name, Desc)
SELECT Name, Desc
FROM schema1.table
I am trying to add a new unique index on one of my database tables in SQL Server 2008. This is an existing table and the column where I want the unique index already has some duplicate values.
Can I set up a unique index for that column? If so, how?
You can't set this column up with a UNIQUE index if the table already has duplicate values, unless you remove the records containing the duplicate values for that column. This goes to the definition of UNIQUE.
First you are gonna need to delete the duplicate values on your column and then you can create a unique index on it. So lets assume your table has 2 columns, id and column1. To delete duplicate values you need to choose one, it can be random or with some order. So it would be like this:
WITH CTE AS
(
SELECT *, ROW_NUMBER() OVER(PARTITION BY column1 ORDER BY Id) Corr
FROM YourTable
)
DELETE FROM CTE
WHERE Corr > 1
CREATE UNIQUE INDEX I_Unique ON YourTable(Column1)
No as the name suggest, Unique Index which says key has to be unique. So you cant
See this
If the column already has duplicate values then I would recommend you create a unique composite key instead.
e.g.
So, to handle that issue with this table design, you need to create a unique constraint on the table CustomerID/ProductID columns:
create unique index cust_products_unique on CustomerProducts (CustomerID, ProductID)
So that in essence a combination of fields ensures that the index is unique.
Regards
May not have been true in SQL Server 2008, however you can use Management Studio to do this in later versions such as 2014.
Right click your table
Choose Design
Expand "Identity Specification" and set (is Identity) to Yes
Save
This seems simple enough: I want to duplicate a row in a SQLite table:
INSERT INTO table SELECT * FROM table WHERE rowId=5;
If there were no explicit unique column declarations, the statement would work, but the table's first column is declared rowID INTEGER NOT NULL PRIMARY KEY. Is there any way to create a simple statement like the one above that works without knowing the schema of the table (aside from the first column)?
This can be done using * syntax without having to know the schema of the table (other than the name of the primary key). The trick is to create a temporary table using the "CREATE TABLE AS" syntax.
In this example I assume that there is an existing, populated, table called "src" with an INTEGER PRIMARY KEY called "id", as well as several other columns. To duplicate the rows of "src", use the following SQL in SQLite3:
CREATE TEMPORARY TABLE tmp AS SELECT * FROM src;
UPDATE tmp SET id = NULL;
INSERT INTO src SELECT * FROM tmp;
DROP TABLE tmp;
The above example duplicates all rows of the table "src". To only duplicate a desired row, simply add a WHERE clause to the first line. This example works because the table "tmp" has no primary key constraint, but "src" does. Inserting NULL primary keys into src causes them to be given auto-generated values.
From the sqlite documentation: http://www.sqlite.org/lang_createtable.html
A "CREATE TABLE ... AS SELECT" statement creates and populates a database table based on the results of a SELECT statement. A table created using CREATE TABLE AS has no PRIMARY KEY and no constraints of any kind.
If you want to get really fancy, you can add a trigger that updates a third table which maps old primary keys to newly generated primary keys.
No. You need to know the schema of the table to write the insert statement properly.
You need to be able to write the statement in the form of:
insert into Table (column1, column2, column3)
select column1, column2, column3
from OtherTable
where rowId = 5
Well, since I was unable to do this the way I wanted, I resorted to using the implicit row id, which handily enough has the same name as the rowId column I defined explicitly, so now I can use the query I had in the question, and it will insert all the data with a new rowId. To keep the rest of the program working, I just changed SELECT * FROM table to SELECT rowId,* FROM table and everything's fine.
Absolutely no way to do this. Primary Key declaration implies this field is unique. You can't have a non unique PK. There is no way to create a row with existing PK in the same table.