I want to insert an element in my table :
events(eventID int primary key autoincrement,type text,date date,coordinates text,deviceID int,userID int)
how the auto increment works?
in fact when I did not write the id I have an error like "you have 6 columns but 5 were supplied."
and if I just write nil I have always id=0, this is what I wrote :
insert into events(type,date,coordinates,deviceId,userID) values('%#','%#','%#','%d','%d');
thanks by advance
The documentation says that
if a rowid table has a primary key that consists of a single column and the declared type of that column is "INTEGER" in any mixture of upper and lower case, then the column becomes an alias for the rowid. […] A PRIMARY KEY column only becomes an integer primary key if the declared type name is exactly "INTEGER". Other integer type names like "INT" or "BIGINT" or "SHORT INTEGER" or "UNSIGNED INTEGER" causes the primary key column to behave as an ordinary table column with integer affinity and a unique index, not as an alias for the rowid.
Related
If I want to add a PRIMARY KEY to an existing column table :
ALTER TABLE table_name
ADD CONSTRAINT column_name_PK PRIMARY KEY (column_name);
Now, If I want to add a NOT NULL to an existing column table :
ALTER TABLE table_name
ALTER column column_name INTEGER(or other data type) NOT NULL;
Isn't NOT NULL a constraint ?
Why for a PRIMARY KEY is ADD CONSTRAINT
and for a NOT NULL is not ADD CONSTRAINT but ALTER COLUMN ?
To my eyes, NOT NULL is also a kind of constraint..
Specifying NOT NULL means 'the column must have a value'. It only means that some value must be present, but it says nothing about what those values should be. Note that in SQL terms, NULL itself is not a value but it is the absence of a value.
A CONSTRAINT on the other hand is a rule for the allowed values. You can even have a constraint on NULL columns, and then such a CONSTRAINT for the allowed values is enforced only if a non-NULL value is present.
You can just use NOT NULL inline when you declare the parameter. Like this:
CREATE TABLE People
(
ID INT NOT NULL,
Name NVARCHAR(100) NOT NULL,
Notes NVARCHAR(MAX) NULL
)
Think of it as the NULL or NOT NULL actually being part of the type declaration. A field that can hold an Integer and also can hold a NULL is a different type than one that can hold an Integer but never a NULL.
Consider
create type IntegerIsSometimesNull from integer null
create type IntegerIsNeverNull from integer not null
go
create table DifferentType ( N IntegerIsSometimesNull,
I IntegerIsNeverNull )
Here we see that NULL and NOT NULL are actually a part of the type declaration.
Consider also that these fields require a different amount of space in the database.
To my eyes, NOT NULL is also a kind of constraint..
Yes. Data Types, NULL-ness, CHECK CONSTRAINTS, and FOREIGN KEY constraints are all concerned with defining the "domain" of the column. A "domain" is the set of possible values for a column, and is a fundamental concept of the relational model.
In most RDBMS systems domains are implemented by a combination of data types and constraints.
I want to create a table in SQL which has a string attr for Users of a website. How should I declare this attr, since names don't have a max length? Can I just leave the length empty and do it like this?
CREATE TABLE User(
id NUMBER PRIMARY KEY NOT NULL
name NVARCHAR
)
Also, do I need to say NOT NULL for PRIMARY KEYS, or are primary keys already never null?
Thanks in advance :)
You should declare length as MAX and primary key are automatically NOT NULL
CREATE TABLE User(
id NUMBER PRIMARY KEY
name NVARCHAR(MAX)
)
Since you have later specified dbms as SQL Lite , the documentation says
What is the maximum size of a VARCHAR in SQLite?
SQLite does not enforce the length of a VARCHAR. You can declare a
VARCHAR(10) and SQLite will be happy to let you put 500 characters in
it. And it will keep all 500 characters intact - it never truncates.
How should I declare this attr, since names don't have a max length?
Can I just leave the length empty and do it like this?
Yes, in SQLite you can just declare the column with any “text affinity” type name (CHAR, TEXT, CLOB, etc.) and it will store strings (or blobs) without length restriction (except for the global string length limit, which is 1 GB by default).
If you do want to constrain the length of strings, you can do it with an explicit CHECK constraint, like CHECK(LENGTH(name) <= 100).
Also, do I need to say NOT NULL for PRIMARY KEYS, or are primary keys
already never null?
Per the SQL standard, PRIMARY KEY implies NOT NULL. However, SQLite has a long-standing bug that makes the explicit NOT NULL constraint required.
According to the SQL standard, PRIMARY KEY should always imply NOT NULL. Unfortunately, due to a bug in some early versions, this is not
the case in SQLite. Unless the column is an INTEGER PRIMARY KEY or the
table is a WITHOUT ROWID table or the column is declared NOT NULL,
SQLite allows NULL values in a PRIMARY KEY column. SQLite could be
fixed to conform to the standard, but doing so might break legacy
applications. Hence, it has been decided to merely document the fact
that SQLite allowing NULLs in most PRIMARY KEY columns.
I'm trying to add a primary key with an autoincrement.
I have read some docs and other questions - there're SERIAL and nextval() statements but neither of them work.
Here's what I made:
CREATE TABLE IF NOT EXISTS "category" (
"id" integer SERIAL PRIMARY KEY,
"name" varchar(30) DEFAULT NULL
); // the error near "SERIAL"
and
CREATE SEQUENCE your_seq;
CREATE TABLE IF NOT EXISTS "category" (
"id" integer PRIMARY KEY nextval('your_seq'),
"name" varchar(30) DEFAULT NULL
); // the error near 'nextval'
What am I doing wrong? Is there a way to increment the primary key by 1.
serial is, more or less, a column type so saying integer serial is like saying text text, just say serial:
CREATE TABLE IF NOT EXISTS "category" (
"id" SERIAL PRIMARY KEY,
"name" varchar(30) DEFAULT NULL
);
If you want to create the sequence yourself then you want to make the default value of id the next value in the sequence and that means saying default nextval('your_seq'):
CREATE SEQUENCE your_seq;
CREATE TABLE IF NOT EXISTS "category" (
"id" integer PRIMARY KEY default nextval('your_seq'),
"name" varchar(30) DEFAULT NULL
);
To simulate the usual serial behavior you'll also want to make the sequence owned by the table:
alter sequence your_seq owned by category.id;
Reading the Serial Types section of the manual might be fruitful.
I'd also recommend that you don't double quote your table and column names unless you have to. PostgreSQL will fold your identifiers to lower case so id and "id" will be the same thing but unnecessary quoting is a bad habit that can easily lead to a big mess of quotes everywhere.
If someone needs to modify an existing table to add a primary key with auto-increment:
ALTER TABLE table_name ADD COLUMN pk_column_name SERIAL PRIMARY KEY;
Is there any difference between INT PRIMARY KEY and INTEGER PRIMARY KEY when defining a schema for a table?
When int primary key is used, I got sqlite_autoindex thing generated;
when integer primary key , I got sqlite_sequence table generated.
what's the difference? what side effects can have the first and second variants?
UPDATE: SQLite's ROWID column is now a 64-bit integer:
In SQLite, a column with type INTEGER PRIMARY KEY is an alias for the ROWID (except in WITHOUT ROWID tables) which is always a 64-bit signed integer.
It is all explained in SQLite 3 documentation:
2.0 The INTEGER PRIMARY KEY
One exception to the typelessness of SQLite is a column whose type is INTEGER PRIMARY KEY. (And you must use "INTEGER" not "INT". A column of type INT PRIMARY KEY is typeless just like any other.) INTEGER PRIMARY KEY columns must contain a 32-bit signed integer. Any attempt to insert non-integer data will result in an error.
INTEGER PRIMARY KEY columns can be used to implement the equivalent of AUTOINCREMENT. If you try to insert a NULL into an INTEGER PRIMARY KEY column, the column will actually be filled with an integer that is one greater than the largest key already in the table. Or if the largest key is 2147483647, then the column will be filled with a random integer. Either way, the INTEGER PRIMARY KEY column will be assigned a unique integer. You can retrieve this integer using the sqlite_last_insert_rowid() API function or using the last_insert_rowid() SQL function in a subsequent SELECT statement.
Yes, there is a difference: INTEGER is a special case in SQLite, when the database does not create a separate primary key, but reuses the ROWID column instead. When you use INT (or any other type that "maps" to INTEGER internally) a separate primary key is created.
That is why you see sqlite_autoindex created for the INT primary key, and no index created for the one of type INTEGER: SQLite reuses a built-in indexing structure for the integer primary key, rendering the autoindex unnecessary.
That is why the INTEGER primary key is more economical, both in terms of storage and in terms of performance.
See this link for details.
Just to add albeit implied already on the answers here. The INTEGER PRIMARY KEY column that you created is simply an alias for ROWID or _ROWID_ or OID. And if the AUTOINCREMENT keyword is added then every new record inserted is an increment of 1 of the last ROWID and the last ROWID is kept by an sqlite internal table named sqlite_sequence.
See link here and here
On the other hand if you declare a column as INT PRIMARY KEY sqlite create an automatic index (hence the sqlite_autoindex) to keep track of the value inserted in the primary key to make sure it is unique.
I have the following SQLite query:
CREATE TABLE Logs ( Id integer IDENTITY (1, 1) not null CONSTRAINT PKLogId PRIMARY KEY, ...
IDENTITY (1, 1) -> What does this mean?
PKLogId what is this? This doesn't seem to be defined anywhere
I want Id to be integer primary key with autoincrement. I would like to be able to insert into this Logs table omitting Id column in my query. I want Id to be automatically added and incremented. Is this possible? How can I do this?
At the moment when I try to insert without Id I get:
Error while executing query: Logs.Id may not be NULL
I'm not sure whether you're actually using SQLite according to the syntax of your example.
If you are, you may be interested in SQLite FAQ #1: How do I create an AUTOINCREMENT field?:
Short answer: A column declared INTEGER PRIMARY KEY will
autoincrement.
Change it to:
CREATE TABLE Logs ( Id integer PRIMARY KEY,....
If you are, you may be interested in SQLite FAQ #1: How do I create an AUTOINCREMENT field?:
Short answer: A column declared INTEGER PRIMARY KEY will auto increment.
This in fact is not entirely accurate. An integer primary key will indeed increment, however if the table drops all rows, it starts from the beginning again, It is important if you want to have all associated records tied correctly to use the autoincrement description after the primary key declaration on the integer field.