Union columns from different tables - sqlite

Assuming I have 2 tables:
Persons: ID, Name
Pets: PName
I want to select all the IDs from Persons and assign each one with a different PName or NULL if there are more IDs.
Basically it looks like a simple select query from Persons and then somehow append a select query from Pets but I'm not sure how to do that. I tried to use JOIN and UNION but none of them gave me exactly what I wanted.

Create temporary tables for IDs and names:
CREATE TEMP TABLE t1(ID) AS SELECT ID FROM Persons;
CREATE TEMP TABLE t2(PName) AS SELECT PName FROM Pets;
Then use the rowid to join them:
SELECT t1.ID, t2.PName
FROM t1 LEFT JOIN t2 ON t1.rowid = t2.rowid;

Related

Find offset in table with order and where clause

Consider the following schema and table:
CREATE TABLE IF NOT EXISTS `names` (
`id` INTEGER,
`name` TEXT,
PRIMARY KEY(`id`)
);
INSERT INTO `names` VALUES (1,'zulu');
INSERT INTO `names` VALUES (2,'bene');
INSERT INTO `names` VALUES (3,'flip');
INSERT INTO `names` VALUES (4,'rossB');
INSERT INTO `names` VALUES (5,'albert');
INSERT INTO `names` VALUES (6,'zuse');
INSERT INTO `names` VALUES (7,'rossA');
INSERT INTO `names` VALUES (8,'juss');
I access this table with the following query:
SELECT *
FROM names
ORDER BY name
LIMIT 10
OFFSET 4;
Where offset 4 is used because it's the rowid (in the ordered list) to the first occurance of 'R%' names. This returns:
1="7" "rossA"
2="4" "rossB"
3="1" "zulu"
4="6" "zuse"
My question is, is there an SQL statement which can return the OFFSET value (in the R case above its 4) given a starting first letter please? (I don't really want to resort to stepping() through results, counting rows, until first 'R%' is reached!)
I've tried the following without success:
SELECT MIN(ROWID)
FROM
(
SELECT *
FROM names
ORDER BY name
)
WHERE name LIKE 'R%'
It always returns single row of NULL data.
As background, this table is a phone book list and I want to provide subset of results (from main table) back to caller, starting at a initial letter offset.
Just count the rows before the string of interest:
select count(*) from names where name < 'r';
The following has a number of options. Basically your issues is that the sub-query doesn't return the roiwd hencne NULL as the minimum. However, there is no need to use the rowid directly as the id column is an alias of the rowid, so that could be used:-
SELECT name, id, MIN(rowid), min(id) -- shows how rowid and id are the same
FROM
(
SELECT rowid, * -- returns rowid from the subquery so min(rowid) now works
FROM names
ORDER BY name
)
WHERE name LIKE 'R%' ORDER BY id ASC LIMIT 1 -- Will effectivley do the same (no need for the sub-query)
Extra columns added for demonstration.
As such your query could be :-
SELECT min(rowid) FROM names where name LIKE 'R%';
Or :-
SELECT min(id) FROM names where name LIKE 'R%';
You could also use :-
SELECT id FROM names WHERE name LIKE 'R%' ORDER BY id ASC LIMIT 1;
Or :-
SELECT rowid FROM names WHERE name LIKE 'R%' ORDER BY id ASC LIMIT 1;

SQL Query - adding output to SELECT statement

I have written an SQL query which amalgamates data from two separate tables with the following query:
SELECT * FROM table 1
UNION ALL
SELECT * FROM table 2
ORDER BY column 1
What I'd like to be able to do is to add a column or 'stamp' in a newly created column which details the table which each text entry originally came from. So my output would have a column which detailed the table which each row was originally from.
Essentially, the tables I have are made up of large quantities of numeric data and are hard to distinguish upon completing the Union command.
Thanks for any help.
Regards,
CJW.
You can select a scalar value from your selects, but you need to specify columns instead of *:
SELECT col1, col2, 'TABLE1' FROM table 1
UNION ALL
SELECT col1, col2, 'TABLE2' FROM table 2 ORDER BY column 1
You can simply add any expression(s) anywhere in the SELECT clause:
SELECT *, 1 AS SourceTable FROM Table1
UNION ALL
SELECT *, 2 AS SourceTable FROM Table2
ORDER BY Column1;

SQLite 3 - Return multiple SELECT with JOIN results to one row

I have 5 SELECTs with a JOIN in each that individually return the data I'm querying without any issue. They are:
SELECT table1.typeName FROM table1 JOIN table6 ON table1.OwnerID = table6.OwnerID;
SELECT table2.typeName FROM table2 JOIN table6 ON table2.typeID = table6.typeID;
SELECT table3.itemName FROM table3 JOIN table6 ON table3.itemID = table6.moonID;
SELECT table4.name FROM table4 JOIN table6 ON table4.state = table6.state;
SELECT Timestamp FROM table6;
What I have been trying to do is take all of these SELECTs and return all the data on one row.
The closest thing I tried was a subquery? that went like this:
SELECT
(SELECT table1.typeName FROM table1 JOIN table6 ON table1.OwnerID = table6.OwnerID),
(SELECT table2.typeName FROM table2 JOIN table6 ON table2.typeID = table6.typeID),
(SELECT table3.itemName FROM table3 JOIN table6 ON table3.itemID = table6.moonID),
(SELECT table4.name FROM table4 JOIN table6 ON table4.state = table6.state),
(SELECT Timestamp FROM table6);
It worked, but it only returned the first row. So I tried doing UNION ALL with them. It worked, but it would return all the data sequentially.
Some columns in table6 have duplicate data and some columns don't.
Is there any way I can return the data on one row?
EDIT: #Makoto. I'll go a few more steps back.
We have data from a server that dumps data into columns on table6 of the database. The data in the columns are numeric/alphanumeric code and don't mean anything to the end user.
Now, the other tables have columns with the same numeric/alphanumeric codes AND another column with a description.
So, I want to select columns on table6, have it look up the descriptions on the other tables and return the descriptions, like (based on the information in table6)
typeName|typeName|itemName|name|Timestamp
Once the data gets returned like that, I can use Python to create a readable message that is automatically sent to a feed.
Based on my limited knowledge, I thought that something like the SELECT with JOIN commands I put together would achieve this goal, but I can't figure it out. I suspect I'm going down the wrong path.

SQLite - sorting question

I am using the following query to display database rows in an alphabetical order:
SELECT word_id FROM table1 ORDER BY word ASC
But I want to get values from table2, where I don't have column "word" and to sort it by column "word" which is in table1.
I want something like this:
SELECT word_id FROM table2 ORDER BY table1.word ASC
Thank you in advance.
You must connect the two tables with a join:
SELECT t2.word_id
FROM table2 t2
, table1 t1
WHERE t2.word_id = t1.word_id -- this is the join
ORDER BY t1.word ASC

How to know if a row doesn't exist?

I have the following query:
SELECT rowid FROM table1 ORDER BY RANDOM() LIMIT 1
And as well I have another table (table3). In that table I have columns table1_id and table2_id. table1_id is a link to a row in table1 and table2_id is a link to a row in another table.
I want in my query to get only those results that are defined in table3. Only those that have table1 rowid in their table1_id column. There may not be any columns at all referring to a certain table1 rowid so in this case I don't want to receive them.
How can I achieve this goal?
Update: I tried the following query, which doesn't work:
SELECT rowid FROM table1
WHERE rowid IN (SELECT table1_id FROM table3 WHERE table1_id = table1.rowid)
ORDER BY RANDOM() LIMIT 1
SELECT rowid FROM table1
WHERE rowid IN ( SELECT DISTINCT table1_id FROM table3 )
ORDER BY RANDOM() LIMIT 1;
This query means "choose at random a row from table1 which has an entry in table3".
Every row in table1 equal likelihood of being selected (DISTINCT) as long as it is referenced at least once in table3.
If you are trying to get more than one result, then you should remove the "ORDER BY RANDOM() LIMIT 1" clause.
Assuming you want to select more than just a rowid, you need to SELECT from a JOIN between the tables you're interested in. SQLite doesn't have the full set of standard JOIN functionality, so you'll need to re-work your query so it can use a LEFT OUTER JOIN.
SELECT table1.rowid, table1.other_field
FROM table3
LEFT OUTER JOIN table1 ON table3.table1_id = table1.rowid
ORDER BY RANDOM()
LIMIT 1;

Resources