Why I cannot call null data row when I use IS NULL in sqlite
select roomkeyID from roomkey where dateOfReturn is null;
CREATE TABLE ROOMKEY (
roomkeyID VARCHAR(10) not null primary key,
roomID VARCHAR(10) not null,
keyID VARCHAR(10) not null,
dateOfIssue DATETIME,
dateOfReturn DATETIME,
FOREIGN KEY (roomID) REFERENCES ROOM(roomID),
FOREIGN KEY (keyID ) REFERENCES KEY(keyID )
)
"RK000001","R106","K0003","12/17/2015"," "
"RK000090","R101","K0002","12/12/2015"," "
From the example it seems that in the field dateOfReturn you do not have NULL values, but strings with a space inside. If this is true then you have to change your query to:
select roomkeyID from roomkey where dateOfReturn is null or dateOfReturn = ' '
Related
WITH CTE AS (
SELECT
user_id,
ip_addr,
MIN(reg_date) AS min_reg_date
FROM
user_info
GROUP BY
ip_addr
HAVING
COUNT(*) > 1
)
SELECT
users.id
FROM
users
JOIN user_info
ON users.id = users_info.user_id
JOIN CTE
ON user_info.ip_addr = CTE.ip_addr
AND user_info.reg_date > CTE.min_reg_date;
user_info table:
CREATE TABLE `user_info` (
`user_id` int(11) UNSIGNED NOT NULL,
`ip_addr` varchar(255) DEFAULT NULL,
`user_agent` varchar(255) DEFAULT NULL,
`reg_date` timestamp NOT NULL DEFAULT current_timestamp()
)
users table:
CREATE TABLE `users` (
`id` int(11) UNSIGNED NOT NULL,
`first_name` varchar(50) NOT NULL,
`last_name` varchar(50) NOT NULL,
`nickname` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(255) NOT NULL,
`avatar` varchar(255) NOT NULL,
`group_id` int(11) UNSIGNED DEFAULT NULL
)
I tried using EXISTS and IN keywords but it shows that the error is near "DELETE FROM..."
Should i change something else ? Please help.
Primary key on partitioned tables is incremented by n(n>1) and not by 1.
Tried to rewrite plpgsql in numerous different ways with no luck.
There must be something I am not understanding.
CREATE SCHEMA IF NOT EXISTS some_record_pool;
CREATE SEQUENCE some_record_pkey_seq;
create table some_record
(
id BIGINT not null DEFAULT nextval('some_record_pkey_seq'::regclass),
device_id bigint,
device_type bigint,
record_time timestamp,
module_serial_number bigint,
module_id bigint,
message_type bigint,
event_code bigint,
device_status bytea,
sequence_number bigint,
data_bytes bigint,
device_data bytea,
active boolean,
deleted boolean,
created_time timestamp default now() not null,
created_on timestamp with time zone default now() not null,
updated_on timestamp with time zone default now() not null
);
CREATE INDEX idx_device_id
ON public.some_record USING brin
(device_id)
TABLESPACE pg_default;
CREATE INDEX idx_module_id
ON public.some_record USING brin
(module_id)
TABLESPACE pg_default;
CREATE INDEX idx_er_created_time
ON public.some_record (cast(created_time as DATE));
----- CREATE TRIGGER ----------
CREATE OR REPLACE FUNCTION some_record_insert_function()
RETURNS TRIGGER AS
$$
DECLARE
partition_date TEXT;
partition_name TEXT;
start_of_month TEXT;
end_of_next_month TEXT;
BEGIN
partition_date := to_char(NEW.created_time, 'YYYY_MM');
partition_name := 'some_record_' || partition_date;
start_of_month := to_char((NEW.created_time), 'YYYY-MM') || '-01';
end_of_next_month := to_char((NEW.created_time + interval '1 month'), 'YYYY-MM') || '-01';
IF NOT EXISTS
(SELECT 1
FROM information_schema.tables
WHERE table_name = partition_name)
THEN
RAISE NOTICE 'A partition has been created %', partition_name;
EXECUTE format(
E'CREATE TABLE some_record_pool.%I ' ||
E'(CHECK ( date_trunc(\'day\', created_time) >= ''%s'' ' ||
E'AND date_trunc(\'day\', created_time) < ''%s'')) INHERITS (public.some_record)',
partition_name, start_of_month, end_of_next_month);
-- EXECUTE format('GRANT SELECT ON TABLE %I TO readonly',
-- partition_name); -- use this if you use role based permission
ELSE
RAISE NOTICE 'A partition DOES NOT EXIST %', partition_name;
END IF;
EXECUTE format(
'INSERT INTO some_record_pool.%I (device_id, device_type, ' ||
'record_time, module_serial_number, module_id, message_type, ' ||
'event_code, device_status, sequence_number, data_bytes, device_data,' ||
' active, deleted) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)',
partition_name) using NEW.device_id, NEW.device_type,
NEW.record_time, NEW.module_serial_number, NEW.module_id, NEW.message_type,
NEW.event_code, NEW.device_status, NEW.sequence_number, NEW.data_bytes,
NEW.device_data, NEW.active, NEW.deleted;
RETURN NEW;
END
$$
LANGUAGE plpgsql;
CREATE TRIGGER insert_some_record_trigger
BEFORE INSERT ON public.some_record
FOR EACH ROW EXECUTE PROCEDURE public.some_record_insert_function();
--- INSERTING DATA FOR TESTING
INSERT INTO some_record (
event_record_id, timestamp, event_description_id, event_source_label, event_source_track, event_source_direction,
measurement_description, measurement_value, hw_address_module_id, hw_address_rlc_address, sub_system_source,
event_type, device_id, active, deleted) VALUES(1, 2, to_timestamp('1953-10-21 14:30:46.555337', 'YYYY-MM-DD HH:MI:SS.US'), 1, 1, 1, 1, NULL, 1, 9, E'9 B
00000000 92 FF 3C 00 7F 00 00 03 E8 .ÿ<.....è
', TRUE, FALSE, to_timestamp('2019-10-21 14:30:46.555337', 'YYYY-MM-DD HH:MI:SS.US'), to_timestamp('2019-10-21 14:30:46.555337', 'YYYY-MM-DD HH:MI:SS.US'));
The point of the code is to auto create partitions and insert data if partition exists.
Primary key should be incremented by one but it is not behaving as such
expected output on only one run is id: 1
Working solution tested on postgres 12 is the following:
/** TABLE PARTITIONING EVENT RECORD **/
-- CREATE PROPER SCHEMA
CREATE SCHEMA IF NOT EXISTS test_par_pool;
-- CREATE PROPER TABLE
CREATE TABLE test_part
(
id bigserial not null
constraint test_part_pkey
primary key,
device_id bigint,
device_type bigint,
record_time timestamp,
module_serial_number bigint,
module_id bigint,
message_type bigint,
event_code bigint,
device_status bytea,
sequence_number bigint,
data_bytes bigint,
device_data bytea,
active boolean,
deleted boolean,
created_time timestamp default now() not null,
created_on timestamp with time zone default now() not null,
updated_on timestamp with time zone default now() not null
);
-- CREATE MINIMAL INDEXES
CREATE INDEX idx_device_id
ON public.test_part USING brin
(device_id)
TABLESPACE pg_default;
CREATE INDEX idx_module_id
ON public.test_part USING brin
(module_id)
TABLESPACE pg_default;
CREATE INDEX idx_er_created_time
ON public.test_part (cast(created_time as DATE));
-- CREATE INSERT FUNCTIONS
CREATE OR REPLACE FUNCTION test_par_insert_function()
RETURNS TRIGGER AS
$$
DECLARE
partition_date TEXT;
partition TEXT;
start_of_month TEXT;
end_of_next_month TEXT;
stmt TEXT;
BEGIN
partition_date := to_char(NEW.created_time, 'YYYY_MM');
partition := TG_RELNAME || '_' || partition_date;
start_of_month := to_char((NEW.created_time), 'YYYY-MM') || '-01';
end_of_next_month := to_char((NEW.created_time + interval '1 month'), 'YYYY-MM') || '-01';
IF NOT EXISTS(SELECT relname FROM pg_class WHERE relname = partition) THEN
RAISE NOTICE 'A partition has been created %',partition;
stmt = 'CREATE TABLE test_par_pool.' || partition || ' (check (date_trunc(''day'', created_time) >= '
|| chr(39) || start_of_month || chr(39)
|| ' AND date_trunc(''day'', created_time) < '
|| chr(39) || end_of_next_month
|| chr(39) || ' )) INHERITS ( public.' || TG_RELNAME ||
');';
EXECUTE stmt;
END IF;
EXECUTE 'INSERT INTO test_par_pool.' || partition ||
' SELECT( public.' || TG_RELNAME || ' ' || quote_literal(NEW) || ').* RETURNING id;';
RETURN NULL;
END
$$
LANGUAGE plpgsql;
-- CREATE TRIGGER
CREATE TRIGGER insert_test_part_trigger
BEFORE INSERT ON public.test_part
FOR EACH ROW EXECUTE PROCEDURE public.test_par_insert_function();
Im trying to get just inserted autoincremented id:
local luasql = require "luasql.sqlite3"
dbname = "dbname"
table1 = "table1"
table2 = "table2"
env = luasql.sqlite3()
con = env:connect(dbname)
-- Create table1
res1 = con:execute(string.format("CREATE TABLE '%s' (" ..
"id INTEGER PRIMARY KEY AUTOINCREMENT, " ..
"test1 varchar(32), " ..
"test2 varchar(32))", con:escape(table1)))
-- Create table2
res2 = con:execute(string.format("CREATE TABLE '%s' (" ..
"id INTEGER PRIMARY KEY AUTOINCREMENT, " ..
"id_of_row_in_table_1 varchar(32), " ..
"test2 varchar(32))", con:escape(table2)))
-- Insert data into table1
last_inserted_id = con:execute(string.format("INSERT INTO '%s' ('%s', '%s')", con:escape(table1), 'test1', 'test2', con:escape('1'), con:escape('1')))
print(last_inserted_id) -- unfortunately this do not return just inserted id
-- Insert data into table2
res = con:execute(string.format("INSERT INTO '%s' ('%s', '%s')", con:escape(table2), 'last_inserted_id', 'test2', con:escape(last_inserted_id), con:escape('1')))
How to get the last inserted id? I consider an insert function should return just inserted id but it don't.
You could do something like this (I'm using lsqlite3 so adjust accordingly):
db = sqlite3.open(':memory:')
db:execute [[
create table xxx(xxx);
insert into xxx values('one');
insert into xxx values('two');
insert into xxx values('three');
]]
sql = [[select last_insert_rowid() as num;]]
for ans in db:nrows(sql) do
print(ans.num)
end
I have these tables:
doodhiya
dhid INTEGER PRIMARY KEY NOT NULL,
dname TEXT NOT NULL,
dfname TEXT NOT NULL,
dage INTEGER NOT NULL,
dadd TEXT,
dphone INTEGER NOT NULL,
demail TEXT NOT NULL
doodhdata
dtid INTEGER PRIMARY KEY NOT NULL,
ddate INTEGER NOT NULL,
dmonth INTEGER NOT NULL,
dyear INTEGER NOT NULL,
dmilk INTEGER NOT NULL,
dprice INTEGER NOT NULL default 35 ,
dmore TEXT,
ddhid INTEGER NOT NULL
pricemilk
pid INTEGER PRIMARY KEY NOT NULL,
pmonth INTEGER NOT NULL,
pyear INTEGER NOT NULL,
milkprice INTEGER NOT NULL,
typeperson TEXT,
userid INTEGER,
gheeprice INTEGER,
defaultprice TEXT
cashdata
cashid INTEGER PRIMARY KEY NOT NULL,
cashdate INTEGER NOT NULL,
cashmonth INTEGER NOT NULL,
cashyear INTEGER NOT NULL,
cashamount INTEGER NOT NULL,
uid INTEGER NOT NULL,
utype TEXT NOT NULL,
cashtype TEXT NOT NULL,
cashmore TEXT
I want to make a monthly bill and I am succeed buy using it... but in a bill how can i show last month balance....I am trying to use it
SELECT
ddhid, dmonth, dyear, dmilk,
userid, pmonth, pyear, milkprice,
uid, cashmonth, cashyear, cashamount, utype,
SUM(dmilk) AS totalmilk,
SUM(dmilk*milkprice) AS totalamount,
SUM(cashamount) AS totalcash
FROM
doodhdata
LEFT JOIN pricemilk ON (
doodhdata.ddhid = pricemilk.userid
AND doodhdata.dmonth = pricemilk.pmonth
AND doodhdata.dyear = pricemilk.pyear
)
LEFT JOIN cashdata ON (
doodhdata.ddhid = cashdata.uid
AND doodhdata.dmonth = cashdata.cashmonth
AND doodhdata.dyear = cashdata.cashyear
)
WHERE
dmonth > '$mikdatem'
AND dyear='$mikdatey'
AND ddhid='$dhid'
But I want to use defaultprice when milkprice is NULL....how it is possible...?
Use
COALESCE(milkprice, defaultprice)
in place of milkprice in your query.
See SQLite core functions documentation.
my stored procedure is-
CREATE PROCEDURE [dbo].[usp_SetMenu](
#locationId BIGINT,
#menuId BIGINT = NULL,
#name VARCHAR(100) = NULL,
#taxable BIT = NULL,
#type VARCHAR(100) = NULL,
#dateFrom DATETIME = NULL,
#dateTo DATETIME = NULL,
#timeFrom VARCHAR(10) = NULL,
#timeTo VARCHAR(10) = NULL,
#price MONEY = NULL,
#discountPerc FLOAT = NULL,
#discTimeFrom VARCHAR(10) = NULL,
#discTimeTo VARCHAR(10) = NULL,
#textcolor varchar(10) = null,
#bodycolor varchar(10) = null,
#createdBy BIGINT = NULL,
#createdOn DATETIME = NULL,
#modifiedBy BIGINT = NULL,
#modifiedOn DATETIME = NULL,
#menuProductsXML NTEXT = NULL ,
#IsCopy VARCHAR (10) = NULL,
#CopyMenuId BIGINT = NULL,
#menuTaxXML NTEXT = NULL ,
#menuExists INT = NULL OUTPUT,
#newMenuId INT = NULL OUTPUT
)
AS
SET NOCOUNT ON
---------------------------------------------------------------------
-- Declarations of variables
---------------------------------------------------------------------
DECLARE #ptrHandle INT
---------------------------------------------------------------------
-- initialize variables
---------------------------------------------------------------------
---------------------------------------------------------------------
-- get the data
---------------------------------------------------------------------
IF(#menuId IS NULL) -- If menuid is null then create a new record
BEGIN
select #menuExists = count('x') from tblMenu
where [name] = #name and isDeleted = 0 and locationid=#locationId
if #menuExists > 0
Return
INSERT INTO tblMenu
(locationid
,[name]
,[type]
,taxable
,datefrom
,dateto
,timefrom
,timeto
,price
,discountperc
,disctimefrom
,disctimeto
,bodycolor
,textcolor
,createdby
,createdon)
VALUES
(#locationId
,#name
,#type
,#taxable
,#dateFrom
,#dateTo
,#timeFrom
,#timeTo
,#price
,#discountPerc
,#discTimeFrom
,#discTimeTo
,#bodycolor
,#textcolor
,#createdBy
,#createdOn)
SET #menuId = ##IDENTITY
END
ELSE -- If menuid is not null then update that record
select #menuExists = count('x') from tblMenu
where [name] = #name and MenuId <> #menuId and isDeleted = 0 and locationid=#locationId
if #menuExists > 0
Return
UPDATE tblMenu
SET locationid = #locationId
,[name] = #name
,[type] = #type
,taxable = #taxable
,datefrom = #dateFrom
,dateto = #dateTo
,timefrom = #timeFrom
,timeto = #timeTo
,price = #price
,discountperc = #discountPerc
,disctimefrom = #discTimeFrom
,disctimeto = #discTimeTo
,bodycolor = #bodycolor
,textcolor = #textcolor
,modifiedby = #modifiedBy
,modifiedon = #modifiedOn
WHERE menuid = #menuId
-- if menu product collection is passed then insert new records
IF(#menuProductsXML IS NOT NULL)
BEGIN
-- Clearing the old menu products and inserting new ones
DELETE tblMenuProduct WHERE menuid = #menuId
EXEC sp_xml_preparedocument #ptrHandle OUTPUT, #menuProductsXML
INSERT INTO tblMenuProduct
(menuid
,productid
,categoryid
,productprice
,createdby
,createdon)
SELECT #menuId,
ProductId,
CategoryId,
ProductPrice,
#createdBy,
#createdOn
FROM OPENXML (#ptrHandle, '/ArrayOfMenuProductEntity/MenuProductEntity', 2)
WITH(ProductId BIGINT,CategoryId BIGINT, ProductPrice MONEY)
END
if(#IsCopy = 'True')
Begin
INSERT INTO tblMenuProduct
(menuid
,productid
,categoryid
,productprice
,createdby
,createdon)
Select #menuId,productid,categoryid,productprice,#createdBy,#createdOn
From tblMenuProduct where menuid = #CopyMenuId
SET #newMenuId = #menuId
End
IF(#menuTaxXML IS NOT NULL)
BEGIN
DELETE tblMenuTaxClass WHERE menuid = #menuId
EXEC sp_xml_preparedocument #ptrHandle OUTPUT, #menuTaxXML
INSERT INTO tblMenuTaxClass
(menuid
,taxclassid
)
SELECT #menuId,
TaxClassId
FROM OPENXML (#ptrHandle, '/ArrayOfTaxClassEntity/TaxClassEntity', 2)
WITH(TaxClassId BIGINT)
END
---------------------------------------------------------------------
-- exit the sproc
---------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------
SET NOCOUNT OFF
END
Exception:insert statement conflicted with the foreign key constraint
Why I am getting this exception and how can I fix this?
The primary key value wont be there.you are trying to insert a Foreign key value to the table where corresponding PK wont be there.
table1
ID(PK)
1
2
3
table2
ID1(PK) ID(FK)
1 1
2 1
3 4// Error not there in PK table