SQLite3 database - sql

Hello everyone i got this error while trying to create a table in my database, have checked my query carefully but could not understand where the problem is:
sqlite> CREATE TABLE Subreddit (subreddit VARCHAR(15) PRIMARY KEY,name_name VARCHAR(15), FOREIGN KEY(name_name) REFERENCES Name(name), subreddit_id VARCHAR(15) );
Error: near "subreddit_id": syntax error

Table constraints must come after all column definitions. You are declaring a column subreddit_id after you specify a foreign key constraint, which is invalid syntax.
Simply swap the definition of subreddit_id and the FOREIGN KEY definition.

Related

SQLite - named constraint syntax

I wonder why the following syntax is working:
CREATE TABLE tab1(id INT,
PRIMARY KEY (id) CONSTRAINT PK_tab1
-- here the CONSTRAINT is after PRIMARY KEY def
);
CREATE TABLE tab3(id INT,
CHECK(id > 10) CONSTRAINT CHK_tab3_id
);
Normally I would expect:
CREATE TABLE tab2(id INT,
CONSTRAINT PK_tab2 PRIMARY KEY (id)
);
db<>fiddle SQLite demo
Based on documentation it seems to be invalid syntax:
CREATE TABLE table_constraint
For PostgreSQL/Oracle/MySQL/SQL Server above syntax returns error: db<>fiddle demo PostgreSQL
Is this some kind of compatibility mode with DB2/Informix?
What you're missing is in the column-def diagram.
Notice the loop in the column-constraint section; a single column can have multiple constraints. So your first example has the primary key, and then a second named constraint that doesn't actually have any actual rules applied to it - which is the unusual bit, as the diagrams suggest that shouldn't be allowed. However, the sqlite3 parser is very, very, very forgiving when it comes to column definitions and allows things the official syntax diagrams suggest it shouldn't.

create primary key on existing table without primary key in SQL Server

I am trying to assign an existing column to be the primary key(and another in different table as foreign key) in a table without primary key. I tried this:
Altering a column: null to not null, and it didn't work. The column contains number, text and null values.
Could someone create a step-by-step guide and share with everyone here?
This is the error message:
Msg 8152, Level 16, State 13, Line 2
String or binary data would be truncated.
It would great if you can help interpret the error message.
Thanks!
To add a primary key to an existing table you can do this:
ALTER TABLE yourTableName ADD yourColumnName INT NOT NULL PRIMARY KEY IDENTITY(1, 1)
which will add a new column and automatically populate it with unique integer values starting from one. To add a foreign key to another table use similar syntax to above but don't make the column NOT NULL until you've worked out how to link it to your existing primary key - which is a whole different question.
ALTER TABLE yourOtherTable ADD yourFKColumnName INT WITH CONSTRAINT [FK_SensibleForeignKeyName] FOREIGN KEY ([yourFKColumnName]) REFERENCES yourTableName([yourColumnName])
I haven't tested it but that should be pretty close to what you need.
Just do a
ALTER TABLE dbo.YourTable
ADD CONSTRAINT PK_YourTable
PRIMARY KEY CLUSTERED (YourColumnHere)
and you're done. This requires that YourColumnHere is a non-nullable column, of course.

Integrity Constraint Invalid Identifier SQL

I am new to SQL and I am currently have an issue with a constraint I am trying to put on one of my columns.
My database models an art gallery and paintings can either be in the gallery or on loan to another gallery. Obviously it can't be both so I was trying to put a constraint on my on_loan table when creating it to stop the painting ID (P_id) of my on_loan table being the same as the P_id in my in_gallery table. This is what I have done so far:
create table in_gallery (
P_id NUMBER (10) CONSTRAINT PK_IN_GALLERY PRIMARY KEY,
CONSTRAINT IN_GALLERY_FK FOREIGN KEY(P_id) REFERENCES painting(P_id) ON DELETE CASCADE);
create table on_loan (
P_id NUMBER (10),
CONSTRAINT BOOK_IS_IN_GALLERY CHECK(P_id != in_gallery(P_id)));
This comes up with the error:
ERROR at line 3:
ORA-00904: "IN_GALLERY": invalid identifier
How would i fix this error?
Thanks.
You can't reference another table like that in a check constraint.
Check the answers to the question here for some solutions. You could achieve this with a user defined function.
EDIT: Also based on the little bit of information from your post I don't think you have a correct normalized database model. You could have a Gallery table and a Painting table with a relation between the two.

Why this sql query doesn't return any error?

When i run these queries:
create table University ( branch text primary key, region text, enrollment int);
create table Student ( sID int primary key, sName text, average int);
create table Apply ( sID int references Student(sID), branch text references University(branch), major text, decision text);
insert into Apply values ( 123, 'stanford', 'CS', 'Y');
It should return an error because i am inserting a tuple that doesn't have a Corresponding value in the reference table. but when i run these commands, this tuple inersts Successfully. What's wrong with this queries?
My DBMS is sqlite and i'm using sqliteman.
You should learn how to enable foreign key support
Quoting docs:
In order to use foreign key constraints in SQLite, the library must be
compiled with neither SQLITE_OMIT_FOREIGN_KEY or SQLITE_OMIT_TRIGGER
defined. If SQLITE_OMIT_TRIGGER is defined but SQLITE_OMIT_FOREIGN_KEY
is not, then SQLite behaves as it did prior to version 3.6.19 -
foreign key definitions are parsed and may be queried using PRAGMA
foreign_key_list, but foreign key constraints are not enforced. The
PRAGMA foreign_keys command is a no-op in this configuration. If
OMIT_FOREIGN_KEY is defined, then foreign key definitions cannot even
be parsed (attempting to specify a foreign key definition is a syntax
error).
Also read sqliteman constraint triggers:
There is one more unsupported SQL feature. Sqlite does not enforce
foreign keys and not null constraints.

MySQL Error Code: 1005

I am trying to add foreign keys to my table but receiving this error.
Error Code: 1005 Can't create table 'william.#sql-88c_3' (errno: 150)
I have 3 tables. employee, client and Contract.
employe [employee_no PK] , Client[customer_no PK] contract [contract_no PK]
I want to have Foreign keys for contract as contract [contract_no PK, employee_no FK], customer_no FK]
I tried to do directly it failed, I am now trying the alter statement.Is anything wrong with the Alter script?
ALTER TABLE contract
ADD CONSTRAINT `employee_no_fk2` FOREIGN KEY (`employee_no`) REFERENCES `employee`
(`employee_no`);
ALTER TABLE contract
ADD CONSTRAINT `Customer_no_fk2` FOREIGN KEY (`Customer_no`) REFERENCES `client`
(`Customer_no`);
Most of such error will be related to data type miss match or so.. If you could go through these links.. it might help you i guess.. Check-this
... also Check-this
As they say in the second link:
The first place you should look is whether the data types agree
between the foreign key and primary key columns.
mysql> SHOW engine innodb STATUS;
------------------------
LATEST FOREIGN KEY ERROR
------------------------
100130 17:16:57 Error IN FOREIGN KEY CONSTRAINT OF TABLE sampledb/#sql-4a0_2:
FOREIGN KEY(member_type)
REFERENCES common_lookup(common_lookup_id):
Cannot find an INDEX IN the referenced TABLE WHERE the
referenced COLUMNS appear AS the FIRST COLUMNS, OR COLUMN types
IN the TABLE AND the referenced TABLE do NOT MATCH FOR CONSTRAINT.
make sure that one of the key field that you are trying to reference does not have an index and/or is not a primary key. and the two key fields type and/or size should be an exact match also make sure that both tables are InnoDB tables.
This can happen due to two reasons
Table creation failed because a foreign key constraint was not correctly formed or
Datatype mismatch in the constraints.
the below link would be helpful
http://dev.mysql.com/doc/refman/5.0/en/innodb-error-codes.html
Last time I encountered this, it was the constraints: referenced table key type was 'int' and referring table had 'unsigned int' referring field by mistake, instead of int.