I have table as follow ::
id || name || Desg || Sal || deptId
1 ||ajay ||MD ||999 ||1
2 ||Kaushal ||Engg ||100 ||2
3 ||Vidhi ||HR ||5000 ||3
4 ||Sonu ||SSP ||200 ||1
5 ||Jay ||Asst Manager ||120 ||3
6 ||Uvi ||Utra ||450 ||5
id is primary column. This is just one table with name person.
I want to get the values of primary key column (here id).
My java method will receives the table name & where clause and will return the ArrayList of values of primary Column. Now the problem is that based on table name it should be decided which column is primary column. Is there any query which can give values ::
<<Part of Query to get values of primary column key>> where sal > 150 & deptId != 1 (Where clause that method will receive)
Database metadata can be extracted from the INFORMATION_SCHEMA tables, as documented here.
I think the table you'd be looking at would be columns:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '<<your schema name>>'
AND TABLE_NAME = '<<your table name>>'
AND COLUMN_KEY = 'PRI'
although that's only for a simplistic case.
For proper index analysis, the statistics table can be consulted. From (somewhat vague) memory, the index name or type can be used to figure out if the index is a primary key index.
Once you have the primary key column name, you can simply construct another query based on that.
In other words (untested):
String prim_colm = getPrimaryKeyColumn (tableName);
String newQuery = "select " + prim_colm + " from " + tableName";
then execute newQuery.
To answer the second part of your question
<<Part of Query to get values of primary column key>>
use...
SELECT <column name> FROM <table name> WHERE....
Where <column name>/<table name> comes from where ever you decide to work it out. Querying database meta data or just using a switch.
Related
Consider a table :
ID COUNTRY_CODE
1 ab-cd-ef
2 gh-ef
3 cd-ab-pq-xy
And I need an sql query that selects the records which contain a specific country code.
The traditional LIKE approach works, of course:
select ID from TableName where COUNTRY_CODE like '%cd%';
The concern here is, this query would run over millions of records, thus increasing the cost of total operation. Due to the cost issues, nested tables is not an option here.
Note : The query can be parameterized with Java, if needed.
Is there any cost-effective way to handle such searchable columns?
Do not store lists as delimited strings. Either create a separate table:
CREATE TABLE TableName ( id NUMBER PRIMARY KEY );
CREATE TABLE TableName__Country_Codes(
id NUMBER REFERENCES table_name ( id ),
country_code CHAR(2),
PRIMARY KEY ( id, country_code )
);
Then you could use
SELECT ID
FROM TableName__Country_codes
WHERE 'cd' = COUNTRY_CODE;
Or use a nested table:
CREATE TYPE Char2List IS TABLE OF CHAR(2)
/
CREATE TABLE TableName(
ID NUMBER PRIMARY KEY,
Country_Code Char2List
) NESTED TABLE Country_code STORE AS Table_Name__Country_Codes;
Then you could use
SELECT ID
FROM TableName
WHERE 'cd' MEMBER OF COUNTRY_CODE;
If you have to use a delimited string then your query should include the delimiters in the search expression:
SELECT ID
FROM TableName
WHERE '-' || COUNTRY_CODE || '-' like '%-cd-%';
Otherwise, if you have longer list elements then %cd% could match cd or cda or bbcdbb.
I have an SQLite database. I am trying to insert values (users_id, lessoninfo_id) in table bookmarks, only if both do not exist before in a row.
INSERT INTO bookmarks(users_id,lessoninfo_id)
VALUES(
(SELECT _id FROM Users WHERE User='"+$('#user_lesson').html()+"'),
(SELECT _id FROM lessoninfo
WHERE Lesson="+lesson_no+" AND cast(starttime AS int)="+Math.floor(result_set.rows.item(markerCount-1).starttime)+")
WHERE NOT EXISTS (
SELECT users_id,lessoninfo_id from bookmarks
WHERE users_id=(SELECT _id FROM Users
WHERE User='"+$('#user_lesson').html()+"') AND lessoninfo_id=(
SELECT _id FROM lessoninfo
WHERE Lesson="+lesson_no+")))
This gives an error saying:
db error near where syntax.
If you never want to have duplicates, you should declare this as a table constraint:
CREATE TABLE bookmarks(
users_id INTEGER,
lessoninfo_id INTEGER,
UNIQUE(users_id, lessoninfo_id)
);
(A primary key over both columns would have the same effect.)
It is then possible to tell the database that you want to silently ignore records that would violate such a constraint:
INSERT OR IGNORE INTO bookmarks(users_id, lessoninfo_id) VALUES(123, 456)
If you have a table called memos that has two columns id and text you should be able to do like this:
INSERT INTO memos(id,text)
SELECT 5, 'text to insert'
WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');
If a record already contains a row where text is equal to 'text to insert' and id is equal to 5, then the insert operation will be ignored.
I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.
I would advice that you instead design your table so that no duplicates are allowed as explained in #CLs answer below.
For a unique column, use this:
INSERT OR REPLACE INTO tableName (...) values(...);
For more information, see: sqlite.org/lang_insert
insert into bookmarks (users_id, lessoninfo_id)
select 1, 167
EXCEPT
select user_id, lessoninfo_id
from bookmarks
where user_id=1
and lessoninfo_id=167;
This is the fastest way.
For some other SQL engines, you can use a Dummy table containing 1 record.
e.g:
select 1, 167 from ONE_RECORD_DUMMY_TABLE
I am wanting to insert some data into a MySQL table, these are the columns:
uuid | id_1 | id_41
the "id_1" and "id_41" could be anything, all I know is the primary key (uuid) and I am wanting to be able to insert into the table while only knowing the uuid column value as I am doing this so far:
PreparedStatement newPlayer = "INSERT INTO `test` values(?);";
newPlayer.setString(1, event.getPlayer().getUniqueId().toString());
But when I test it, it doesn't add to the table and does not produce any errors. I also know that all of the other values have a default value of 0
If you want to add a row without all columns included, you need to specify the column's name
INSERT INTO `test` (`uuid`) values(?);
Simple tell to insert the column you want insert eg for uuid
INSERT INTO `test` ( `uuid`) values(?);
This is my code with 1 FK.
here's the columns
([PK]charityRoomID, charityRoomStatus, [FK]charityWardID)
INSERT INTO tbl_addcharityroom1 (charityRoomStatus, charityWardID)
VALUES ('"+jTextField10aw.getText() +"', (
select charityWardID
from tbl_addcharityward
where diseaseCategory='"+ jComboBox1.getSelectedItem().toString() +"'))";
Now, I added a new column(RateID) which is another FK, but i don't know the correct statement for multiple FK. here's the columns
([PK]charityWardID, charityRoomStatus, [FK]charityWardID, [FK]rateID)
I am using netbeans & mySQL
A FK is just a constraint on a database column. It basically means that your column content must map to a specified column when you insert data.
So, if your insert statement specifies a value that exist in the ID column of your Rate table, everything will be allright. Otherwise, an exception will occur.
Basically you just need to do this, replacing "yourRateIdValue" by an Id that actually exist in your Rate table:
"INSERT INTO tbl_addcharityroom1 (charityRoomStatus, charityWardID, rateID)
VALUES ('" + jTextField10aw.getText() + "', (
select charityWardID
from tbl_addcharityward
where diseaseCategory='"+ jComboBox1.getSelectedItem().toString() +"'), yourRateIdValue)";
You can also replace the "yourRateIdValue" by a select statement, as you did for the "charityWardID" column
I have a table named books with bookID, bookName, count , orderCount
i'd like to write an sql query that will update all books.orderCount to books.orderCount+1.
How shall i do that using executeQuery("UPDATE books...."); ?
I'm having troubles with the syntax.
I've tried to search info on the net however most articles are about INSERT or DELETE commands and the only article that was related suggested to retrieve orderCount to Java, update it and then write it back to SQL. if possible i prefer to avoid it as it may cause serious problems (Locks on records are not needed for this task so i can not use them to avoid problems)
this should be pretty straight forward,
UPDATE books
SET orderCount = orderCount + 1
If it's about a primary key:
Also, you can AUTO INCREMENT.
CREATE TABLE Persons
(
P_Id int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)
To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:
ALTER TABLE Persons AUTO_INCREMENT=100
To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column (a unique value will be added automatically):
INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen')