Inserting a row at a specific position? - sqlite

So I created a recipe database, and just now I've noticed I forgot to add an ingredient to the second recipe. The order of ingredients is obviously important here, so even if I add it now to the end of the table, it will still be the last when I SELECT the second recipe, when it should be the second ingredient.
Is there any way I can insert it in a specific position, or am I doomed and will have to create an index column specifying the order of the ingredients?
NOTE: This is a junction table, so there's no primary key here, thus I can't insert it using a specific primary key value.
EDIT: Basically I have three tables: Recipe, Ingredient, and RecipeIngredient many-to-many junction table.
Here's the RecipeIngredient junction table structure:
RecipeId: FK
IngredientId: FK
Quantity: REAL
UOM: TEXT
Notes: TEXT

The rules of the First normal form (1NF) are strict on this:
There's no top-to-bottom ordering to the rows.
Meaning there is no way, in a proper database schema, that a record can be "missing at a certain position".
You are indeed "doomed" and
will have to create an index column specifying the order of the ingredients

can you show the table structure?
It is difficult to insert a row in specific position without primary key.

Related

Can a Cloud Spanner child table have the same primary key as the parent table?

Can a Cloud Spanner child table define the same primary key that the parent table uses (with the child is interleaved in the parent)? I know the child's primary key must use the parent's primary key as a prefix, but is the child key required to use at least one additional column? If it's permitted to use the same key, is it bad practice? And if it's not permitted, why not?
For example:
CREATE TABLE Furniture (
FurnitureId STRING(MAX) NOT NULL,
MakerId INT64 NOT NULL,
// additional fields here...
) PRIMARY KEY (FurnitureId, MakerId);
CREATE TABLE FurnitureHistory (
FurnitureId STRING(MAX) NOT NULL,
MakerId INT64 NOT NULL,
// additional fields here...
) PRIMARY KEY (FurnitureId, MakerId),
INTERLEAVE IN PARENT Furniture;
Thanks!
Peter
It is permitted, but it seems a little bit strange at first hand. This data model will allow you to insert at most one child row for each parent row. This is quite similar to adding a couple of optional fields to the parent table, but with these optional fields logically separated from the parent table. So I guess this makes sense if:
You have a number of additional fields that have a logical different meaning, which gives you a reason for storing them in a child table.
And/or
The additional fields should either not be filled at all, or all (or at least more than one) should be filled when one of them are filled.

What if a table doesn't have a primary key

I have made a simple relation table. All consist of three tables:
Tables for storing personal data (Table_Person)
Table for storing address data (Table_Address)
Table to store the relationship between Table_Person and Table_Address (Table_PersonAddress).
What I want to ask is can I delete the primary key in Table_PersonAddress so that Table_PersonAddress doesn't have a primary key and all that's left is the personID and addressID?
Below is an example of a database relation that I made:
enter image description here
Assuming you don't have any foreign key constraints setup on the junction table (that is, the third table which just stores relationships between people and their addresses), you could delete a person from the first table, while leaving behind the relationships in the third table. However, just because you could do this, does not mean you would want to. Most of the time, if you remove a person from the first table, you would also want to remove all of his relationships from the third table. One way to do this in SQLite is by adding cascading delete constraints to the third table, when you create it:
CREATE TABLE Table_PersonAddress (
...
CONSTRAINT fk_person
FOREIGN KEY (personID)
REFERENCES Table_Person (ID)
ON DELETE CASCADE
)
You probably would also want to add a similar constraint for the address field in the third table, since removing an address also invalidates all relationships involving that address.
Note that SQLite does not allow a cascading delete constraint to be added to table which already exists. You will have to recreate your tables somehow in order to add these constrains.
You can delete it, but my advice is to set a composite PRIMARY KEY for the 2 columns personID and addressID so each row is guaranteed to be UNIQUE.
PRIMARY KEY (personID, addressID)
and remember that in SQLite you always have the rowid column to use it as an id of the row if needed.
So create the table with this statement:
DROP TABLE IF EXISTS PersonAddress;
CREATE TABLE PersonAddress (
personID INTEGER,
addressID INTEGER,
PRIMARY KEY(personID, addressID),
FOREIGN KEY (personID) REFERENCES Person (personID) ON DELETE CASCADE,
FOREIGN KEY (addressID) REFERENCES Address (addressID) ON DELETE CASCADE
);
One more thing: why did you define personID and addressID as TEXT?
Surely SQLite is not at all strict at data type definitions, but since the columns they reference are INTEGER they also should be INTEGER.

Why two column created of same name in angular + ionic

I am creating a table inside the DB.I am a successfully created a table and able to insert data on table my issue is that in my table I have two "ID" columns but I only created one .why two ID column generate in table.
Follow this step to generate issue :-
Click the bottom right button (enter the text in pop up screen ).Press "add" button .It generate the row in a "cases" table but when you inspect it show two column of "ID" why ?
Here is my code
http://codepen.io/anon/pen/OVPgoP
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE "Cases" ("ID" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , "CaseName" VARCHAR NOT NULL )');
})
It appears that this is the expected behaviour for SQLite, the technology underpinning Web SQL (which is a deprecated technology, btw).
From the docs:
If a table contains a column of type INTEGER PRIMARY KEY, then that column becomes an alias for the ROWID. You can then access the ROWID using any of four different names, the original three names described above or the name given to the INTEGER PRIMARY KEY column. All these names are aliases for one another and work equally well in any context.
Therefore, my guess is that the Chrome devtools are showing the rowid column using its alias (ID), in addition to the alias column explicitly added (ID).
It seems like you don't actually need to explicitly add an ID column with Web SQL/SQLite. It will add one for you, which you can refer to using rowid, _rowid_ or oid in any statement.
EDIT: Here is a fork of your CodePen, with updates and deletes all correctly working.
Totally new to webSQL, so this answer is very useful to me as well. You can't expect primary keys to work properly with webSQL because internally it tracks something called "rowid" as the primary key. Use unique instead, as seen in a useful example here. You can also use this error code from the spec to figure out if a non-unique column value was inserted.

How should I go about making sure the value pairs in this table are unique?

I am using Visual Web Developer and Microsoft SQL server. I have a tag table "Entry_Tag" which is as follows:
entry_id
tag_id
I want to make the entry_id and tag_id pairing unique. A particular tag can only be applied to an entry once in the table. I made the two columns a primary key. They are also both foreign keys referencing the ids in their respective tables. When I dragged the tables into the Object Relationship Designer it only showed a relationship line between either "Entry_Tag" and "Entry" or when I tried again between "Entry_tag" and "Tag".
The "Entry_tag" table should have a relationship with both "Tag" and "Entry".
How do I go about doing this?
In general, you can add a unique constraint on the table that includes both columns. In this case, including both of the columns in the primary key should have already done this. If you have relationships set up for each field to other tables, then I believe those relationships should be displayed in the query designer... I see no cause for this given the information you've provided - perhaps you need to post more information.
Create an UNIQUE INDEX to for entry_id and tag_id.
CREATE UNIQUE INDEX index_name ON table (entry_id, tag_id)

Unique record in Asp.Net SQL

I asked this question previously but the answers weren't what I was looking for.
I created a table in Asp.net without using code. It contains two columns.
YourUserId and FriendUserId
This is a many to many relationship.
Heres what I want:
There can be multiple records with your name as the UserId, there can also be multiple records with FriendUserId being the same...but there cannot be multiple records with both being the same. For example:
Dave : Greg
Dave : Chris
Greg : Chris
Chris : Greg
is good
Dave : Greg
Dave : Greg
is not good.
I right clicked on the table and chose Indexes/Keys. I then put both columns in the columns section and chose to make the unique. I thought this would make them unique as a whole but individually not unique.
If you go to the Dataset, it show keys next to both columns and says that there is a constraint with both columns being checked.
Is there a way of just making sure that you are not inserting a duplicate copy of a record into the table without individual columns being unique?
I tried controling it with my sql insert statement but that did not work. This is what I tried.
INSERT INTO [FriendRequests] ([UserId], [FriendUserId]) VALUES ('"+UserId+"', '"+PossibleFriend+"') WHERE NOT EXIST (SELECT [UserId], [FriendUserId] FROM [FriendRequests])
That didn't work for some reason.
Thank you for your help!
You should create a compound primary key to prevent duplicate rows.
ALTER TABLE FriendRequests
ADD CONSTRAINT pk_FriendRequests PRIMARY KEY (UserID, FriendUserID)
Or select both columns in table designer and right click to set it as a key.
To prevent self-friendship, you'd create a CHECK constraint:
ALTER TABLE FriendRequests
ADD CONSTRAINT ck_FriendRequests_NoSelfFriends CHECK (UserID <> FriendUserID)
You can add the check constraint in the designer by right clicking anywhere in the table designer, clicking "Check constraints", clicking "add", and setting expression to UserID <> FriendUserID
You might want to look at this question
Sounds like you need a composite key to make both fields a single key.
I have a better idea. Create a new table. Called FriendRequestRelationships. Have the following columns
FriendRelationshipId (PRIMARY KEY)
UserId_1 (FOREIGN KEY CONSTRAINT)
UserId_2 (FOREIGN KEY CONSTRAINT)
Put a unique constraint to only allow one relationship wit UserId_1 and UserId_2. This table now serves as your many-to-many relationship harness.
Create a scalar function that can return the FriendUserId for a UserId, lets say it's called fn_GetFriendUserIdForUserId
You can now display your relationships by running the following query
SELECT dbo.fn_GetFriendUserIdForUserId(UserId_1) AS 'Friend1',
dbo.fn_GetFriendUserIdForUserId(UserId_2) AS 'Friend2',
FROM FriendRelationshipId

Resources