Prevent INSERT if time overlap in PgSQL without trigger [duplicate] - php

This question already has an answer here:
Postgres constraint for unique datetime range
(1 answer)
Closed 7 years ago.
i would like to prevent an insert into my PgSQL table if the values for a time period (lets call them newStart and newEnd), if this would overlap with any other timeperiod in my rows.
So, the table has a bunch of row where each has a start and end date (oldStart and oldEnd).
Is it possible to do this inside the query, without an trigger, an without getting all the data from the db first end check it inside php (because i think this is not ne best/fastest way to do).
Please correct me i think wrong.
I found the PgSQL overlap function, but building a query was not possible for me! How can i get more in touch with advanced database things? Just by doing?

Use an exclusion constraint.
More elegant with actual range types instead of start/end:
Preventing adjacent/overlapping entries with EXCLUDE in PostgreSQL
But you can also use an expression in the constraint. Basically:
CREATE TABLE tbl (
tbl_id serial PRIMARY KEY
, starts_at timestamp
, ends_at timestamp
, EXCLUDE USING gist (tsrange(starts_at, ends_at) WITH &&) -- no overlapping
);
More details:
Postgres constraint for unique datetime range
How can I get more in touch with advanced database things?
Study answers here, read the excellent manual, experiment with newly found techniques.

Related

PHP Fastest query in huge DB mysql [duplicate]

This question already has answers here:
MySQL Integer vs DateTime index
(3 answers)
Closed 6 years ago.
I'm creating a table to store millions of records, that's it 86400seconds a day x 365days x 10years = 315,360,000 rows of records with only 3 columns,
with datetime, decimal, and smallint (only 3 fields) datetime as index.
I'm thinking of converting the datetime into INT unsigned (PHP time()) to reduce the storage. With the datetime, decimal and smallint, I'm having 2.5GB for 1 table. I've not tried to replace the DATETIME with INT.
The insertion to this table is 1 time job, and I'll have a lots of SELECT statement for analytical purpose, thus I'm changing the InnoDB to MyISAM.
Any thoughts or suggestion?
Indexes are one of the things used to get a faster search on a table:
http://dev.mysql.com/doc/refman/5.7/en/mysql-indexes.html
On the basic level, indexes are responsible for making the engine not iterate over the entire table when searching for something you asked for.
Some of the things stated in the link regarding the use of indexes:
To find the rows matching a WHERE clause quickly.
To eliminate rows from consideration. If there is a choice between
multiple indexes, MySQL normally uses the index that finds the
smallest number of rows (the most selective index).
See if that suits your needs

MySql: saving date ranges VS saving single day

I am currently working on a simple booking system and I need to select some ranges and save them to a mysql database.
The problem I am facing is deciding if it's better to save a range, or to save each day separately.
There will be around 500 properties, and each will have from 2 to 5 months booked.
So the client will insert his property and will chose some dates that will be unavailable. The same will happen when someone books a property.
I was thinking of having a separate table for unavailable dates only, so if a property is booked from 10 may to 20 may, instead of having one record (2016-06-10 => 2016-06-20) I will have 10 records, one for each booked day.
I think this is easier to work with when searching between dates, but I am not sure.
Will the performance be noticeable worse ?
Should I save the ranges or single days ?
Thank you
I would advise that all "events" go into one table and they all have a start and end datetime. Use of indexes on these fields is of course recommended.
The reasons are that when you are looking for bookings and available events - you are not selecting from two different tables (or joining them). And storing a full range is much better for the code as you can easily perform the checks within a SQL query and all php code to handle events works as standard for both. If you only store one event type differently to another you'll find loads of "if's" in your code and find it harder to write the SQL.
I run many booking systems at present and have made mistakes in this area before so I know this is good advice - and also a good question.
This is too much for a comment,So I will leave this as an answer
So the table's primary key would be the property_id and the Date of a particular month.
I don't recommend it.Because think of a scenario when u going to apply this logic to 5 or 10 years system,the performance will be worse.You will get approximately 30*12*1= 360 raws for 1 year.Implement a logic to calculate the duration of a booking and add it to table against the user.

MySQL replace field entry with substring [duplicate]

This question already has answers here:
Converting a date in MySQL from string field
(4 answers)
Closed 9 years ago.
I currently have dates stored in my database (in string format) currently as mm/dd/yyyy.
I need to replace all entries as yyyy/mm/dd for sorting purposes.
To clarify, I am a PHP developer but my raw MySql isnt as strong. I was thinking of doing this by using substrings to re-arrange the date. (I tried in PHP first but it take way too long to process this much data, about a half million rows).
Am i going about this correctly? if so, how do I "loop through" the data, assigning my substr variables for the current iteration?
Note: I did try str_to_date here and it ended up nullifying half of the fields. Im not entirely sure why.
Your help is greatly appreciated.
this is an insert statment
INSERT INTO yourtable (datefield) VALUES (str_to_date(date, '%Y/%m/%d'));
and this an update
UPDATE Table SET date=STR_TO_DATE('date','%Y/%m/%d')
try this
UPDATE Table SET date = DATE_FORMAT('date', %Y/%m/$d);
I believe this will work if your column is in a consistent mm/dd/yyyy format
UPDATE mytable
SET date = CONCAT(right(date,4), '/', left(date,5))

Why to use TIMESTAMP instead of INT value? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What are the pros and cons of the various date/time field types in MySQL?
In many database, I saw they use TIMESTAMP type to store time value, my question is why don't use INT type to store $date->getTimestamp() value and then we could get time value easier?
Because when you treat a date as a date, and not as a number, you can do neat stuff like adding durations (DATE+1MONTH-1HOUR). TIMESTAMP, DATETIME etc are also optimized for dates, and will do native validation for you.
There can be many reasons, I'd say the most obvious (and straight forward one) is that the databse knows that the value is a TIMESTAMP (so Date/Time related), which is not the case for an INT.
This has several consequences, for example that Mysql is aware of timezones and automatically concerts the TIMESTAMP to UTC. That means the data is much more concrete, because it is clear what the data means. For the INT types you would need to take care of that your own, it would not be relative to the database any longer.
The next big difference is automatic initialization and updating. That means, if the row is inserted or changed, a TIMESTAMP column will get "stamped" with the current time.
There are several other differences then as well between these types, most of the are related to data/time functions. I suggest you dig into:
11.3.1. The DATE, DATETIME, and TIMESTAMP Types
You can do many more things in the database when using a timestamp instead of a plain number. Query by day of week, group by month, determine intervals, etc...
An int is only 4 bytes a datetime is 8 bytes so you'd have less possible values. In particular for php you are getting Unix timestamps which have a min date 1901-12-13, and max of 2038-01-19. This is essentially going back and making the same sort of decisions that lead to the Y2K problem. Assuming you can live with that you should be okay but what about non-Unix based hosts?
Because actual representation of data does not have to be exposed. Why?
flexibility (internal representation of data may change any time and user won't depend on it).
reliability (database may check data for consistency if it knows what the data is)
readability (there's no reason to treat a timestamp as integer, it shows the meaning of a record)
The reason there are different number types (such as timestamp), is to provide data integrity.
Data Integrity makes sure that we don't accidentally put in the number of waffles we had for breakfast :)
If we try to put in an invalid timestamp, MySQL will throw an error and prevent us from putting in bad data.

Best way to search a comma separated mysql field

I have been given the task to combine 2 mysql fields into one and then make it so that the new field can be searched. The 2 fields I had to combine in my database where previous year registered and current years registered. The format both these fields are in are dd/mm/yyyy. I have combined these fields into a field called Years Registered whih is still in the same format dd/mm/yyyy but has the years registered seperated by a comma(,). I am wondering how I would go about performing a couple different kinds of querys on this column. The mysql queries I have to perform are: Show All() , Show All between dates: mm/yyyy and mm/yyyy , Before: mm/yyyy , After: mm/yyyy
Any help would be greatly appreciated.
Thanks for your time.
I don't like it but if you need you can use the next solution:
extract date using start_date = STR_TO_DATE(SUBSTRING(your_new_field, 1, 10))
and end_date=STR_TO_DATE(SUBSTRING(your_new_field, 12, 10))
Do not do this!
I do not know how it is exactly possible (some SQL Stringoperations and Datefunctions in a storedprocedurem i presume), but it will surely kill performance of your database.
use a relation for this.
This is:
way faster
more expandable (eg. for three dates..)
easier to code
much better understandable
more portable to other databases
If you have problems with existing platforms you have to support, use a code base where both alternatives are supported. This is still easier and better to maintain than to use a comma-separated list
Your database would be breaking 'First Normalized Form (1NF)' and would be highly ineffecient.
In order to search for a selected date, you would either have to query all rows in the table, or use LIKE which is also very sluggish.
Whoever is asking you to do this should read this article on database normalization.
What is wrong with using two DATE, or DATETIME fields and the formatting them outside of MySQL?

Categories