[Table creation in sqlite manager]i am working on iOS objective c.In my project am using the sqlite manager for database purpose.I declared id is auto increment on the time of table creation of sqlite manager but whenever i execute my code on that time id is not autoincremted.
So decided to wrote the code for auto increment.
I wrote the code for id auto increment but it is not working properly.
Can any please suggest me which code is better for autoincrment.[this is the my database table creation in sqlite manager[Code for id auto increment][Table creation in sqlite manager]code for id creation
Code for table creation in sqlite manager
You should define the field as INTEGER PRIMARY KEY AUTOINCREMENT, but when you insert data, do not include this field in the values being inserted. Don't try to increment this yourself. Let the database do this for you. If, after inserting the record, you want to know what the value assigned was, then call sqlite3_last_insert_rowid.
You might want to declare the id as Primary Key. Please see this answer
create table query
CREATE TABLE COMPANY(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
query to insert
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'Paul', 32, 'California', 20000.00 );
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ('Allen', 25, 'Texas', 15000.00 );
result
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
Related
I have table called charges which has fk of prev_charge_id
We have created new column prev_charge_uuid now want to convert prev_charge_id to prev_charge_uuid, what will be the efficient way to do it
DB columns
id name prev_charge_id prev_charge_uuid uuid
1 kv null null abcd-abcd-abcd-abcd
2 Op 1 null qbcd-aqcd-qbcd-qbcd
Have table like this
want prev_charge_uuid to get updated based on prev_charge_id
id name prev_charge_id prev_charge_uuid uuid
1 kv null null abcd-abcd-abcd-abcd
2 Op 1 abcd-abcd-abcd-abcd qbcd-aqcd-qbcd-qbcd
To do what you are requesting is not a good idea. It violates the database design principle that data should be represented in exactly one place. In your example, you could run into problems if a uuid gets changed, but the prev_charge_uuid does not.
A much better strategy is to define the method in the model:
def prev_charge_uuid
self.class.find(prev_charge_id).uuid
end
[update] I just noticed that prev_charge_id is a column in the table, so you can just use it iso calculating previous id... solves the problem that #sergio points out when there are "holes" in the id sequence.
I have a table with approximately 8 million rows in it. It has a uniqueness constraint on a column called Customer_Identifier. This is a varchar(10) field, is not the primary key, but is unique.
I wish to retrieve some customer rows from this table using SQL Developer. I have been given a text file with each record containing a search key value in the columns 1-10. This query will need to be reused a few times, with different customer_identifier values. Sometimes I will be given a few customer_identifier values (<1000 of them). Sometimes many (between 1000 and 10000 of them). For the times when I want fewer than 1000 values, it's pretty straightforward to use an IN clause. I can edit the text file to wrap the keys in quotes and insert commas as appropriate. But SQL developer has a hard limit of 1000 values in an IN clause.
I only have read rights to the database, so creating and managing a new physical table is out of the question :-(.
Is there a way that I can treat the text file as a table in Oracle 12.1, and thus use it to join to my customer table on the customer_identifier column?
Brgds
Chris
Yes, you can treat a text file as an external table. But you may need DBA assistance to create a new directory, if you don't have access to a directory defined in the database.
Thanks to Oracle Base
**Create a directory object pointing to the location of the files.**
CREATE OR REPLACE DIRECTORY ext_tab_data AS '/data';
**Create the external table using the CREATE TABLE..ORGANIZATION EXTERNAL syntax. This defines the metadata for the table describing how it should appear and how the data is loaded.**
CREATE TABLE countries_ext (
country_code VARCHAR2(5),
country_name VARCHAR2(50),
country_language VARCHAR2(50)
)
ORGANIZATION EXTERNAL (
TYPE ORACLE_LOADER
DEFAULT DIRECTORY ext_tab_data
ACCESS PARAMETERS (
RECORDS DELIMITED BY NEWLINE
FIELDS TERMINATED BY ','
MISSING FIELD VALUES ARE NULL
(
country_code CHAR(5),
country_name CHAR(50),
country_language CHAR(50)
)
)
LOCATION ('Countries1.txt','Countries2.txt')
)
PARALLEL 5
REJECT LIMIT UNLIMITED;
**Once the external table created, it can be queried like a regular table.**
SQL> SELECT *
2 FROM countries_ext
3 ORDER BY country_name;
COUNT COUNTRY_NAME COUNTRY_LANGUAGE
----- ---------------------------- -----------------------------
ENG England English
FRA France French
GER Germany German
IRE Ireland English
SCO Scotland English
USA Unites States of America English
WAL Wales Welsh
7 rows selected.
SQL>
I currently have the following tables in a database:
create table map (
id bigint not null unique,
zone box not null,
...
primary key(id)
);
create table other_map (
id bigint not null unique,
zone box not null,
...
primary key(id),
foreign key(id) references map(id)
);
I don't want to allow a new row to be inserted in other_map if there is a row in map whose id is equal to the new entry's id and their zone attributes overlap. I found this answer, which explains how to detect overlapping boxes, but I'd like to know how to (best) apply that in Postgres.
This is what I've come up with so far, using a trigger and a stored procedure:
CREATE OR REPLACE FUNCTION PROC_other_map_IU()
RETURNS TRIGGER AS $PROC_other_map_IU$
DECLARE
id bigint;
zone box;
BEGIN
SELECT map.id, map.zone INTO id, zone
FROM map
WHERE map.id = NEW.id;
IF zone = NEW.zone THEN
RAISE EXCEPTION '%\'s zone overlaps with existing %\'s zone', NEW.id, id;
END IF;
RETURN NEW;
END;
$PROC_other_map_IU$ LANGUAGE plpgsql;
CREATE TRIGGER TR_other_map_IU
AFTER INSERT OR UPDATE
ON other_map
FOR EACH ROW EXECUTE PROCEDURE PROC_other_map_IU();
Now obviously this is wrong, because it simply checks if the zone attributes are equal.
Thank you in advance for your input! Cheers!
Took me a while, but Postgres' geometric functions and operators (more specifically the && - or overlap - operator) do exactly what I wanted:
IF zone && NEW.zone THEN
As part of my school project, I'm supposed to design/make a database where one can store/update/retrieve yearly data about international trade and transportation. To begin with, I isolated a small part of the database in order to start small.
Firstly I tried to design a diagram that would store the number of passengers (not individual passengers) that embarked/disembarked on/off ships in each port of every country every year and how many local and foreign passengers there were (I don't need those two to interact).
(Ignore the Passengers on the top.) and the inwards_outwards entity would give me a table in the database that would look like this:
Secondly I tried to design the diagram of a table where I could store Origin-Destination data (e.g. of the passengers that arrived in (or left from ) a country, how many came from (went to) each other country etc.
For instance in 2011, from England 20 passengers flew to France, 10 to Germany, etc. and in 2011, in England arrived 23 from France, 19 from Germany, etc.
and the od_hellas entity would give me a table like this:
Questions:
Do the above look OK to you?
Is there a more efficient way to store yearly data?
Is what I'm trying to make doable in the context of a project? Any advice in general?
You can do this with three tables as shown below.
If you want to add data about Passengers then you would need a fourth table "Passenger"
The value in your "Numbers" column can be calculated from the base data by using SQL COUNT something like this:
SELECT COUNT(passengerNr)
FROM Departure
WHERE portCode = "EL_OGRPIR";
To get the data by year, you just add something like [AND date = "2011"] (depends on how you choose to store your date data.)
If my solution helps, please click on the vote icon.
Here is the logical view of the tables.
Here is the SQL DDL that you would use to generate the tables in a database. (e.g. you could cut and paste this SQL into the "New Query" panel in SQL Server Management Studio.)
CREATE SCHEMA Trade
GO
CREATE TABLE Trade.Port
(
portCode nchar(15) NOT NULL,
countryCode nchar(2) NOT NULL,
portName nchar(50) NOT NULL,
type nchar(10) CHECK (type IN (N'SeaPort', N'AirPort', N'LandBorder')) NOT NULL,
CONSTRAINT Port_PK PRIMARY KEY(portCode)
)
GO
CREATE TABLE Trade.Departure
(
passengerNr int NOT NULL,
portCode nchar(15) NOT NULL,
"date" datetime NOT NULL,
isInternational bit,
CONSTRAINT Departure_PK PRIMARY KEY(passengerNr, portCode)
)
GO
CREATE TABLE Trade.Arrival
(
passengerNr int NOT NULL,
portCode nchar(15) NOT NULL,
"date" datetime NOT NULL,
isInternational bit,
CONSTRAINT Arrival_PK PRIMARY KEY(passengerNr, portCode)
)
GO
ALTER TABLE Trade.Departure ADD CONSTRAINT Departure_FK FOREIGN KEY (portCode) REFERENCES Trade.Port (portCode) ON DELETE NO ACTION ON UPDATE NO ACTION
GO
ALTER TABLE Trade.Arrival ADD CONSTRAINT Arrival_FK FOREIGN KEY (portCode) REFERENCES Trade.Port (portCode) ON DELETE NO ACTION ON UPDATE NO ACTION
GO
Im using sqlite db in a sample rails application. From my users table, i have cleared all records using User.delete_all. But now whenever i insert a new record in the table using User.create, the id is starting at a value which is one more than the id of the last record which was there in the table. For example, if my table had 5 records and i cleared all, then when i do User.create, its starting at id 6.
Is there any way i can make the id start from 1 again ?
Thank You
Similar question : How to reset a single table in rails? . We can run the following at rails console to reset id column to 1 for a sqlite table
ActiveRecord::Base.connection.execute("DELETE from sqlite_sequence where name = '<table_name>'")
You seem to have autoincrement turned on for the id column.
Sqlite handles these values in an internal table called sqlite_sequence. You could reset the id for a particular autoincrement-enabled table by querying:
UPDATE "sqlite_sequence" SET "seq" = 0 WHERE "name" = $YOURTABLENAME
However, this is not a good idea because the autoincrement functionality is intended to be used in a way that the user does not influence its algorithm. Ideally, you should not care about the actual value of your id but consider it only as a unique identifier for a record.