How can I query data in the order it was created?
I don't have a date-created field in this table.
If you don't have a field storing the time of insertion, or any other meta-data regarding the order of insertion, there is no reliable way to get this information.
You could maybe depend on a clustered index key, but these are not guaranteed. Neither are IDENTITY fields or other auto-generated fields.
To clarify, an IDENTITY field does auto-increment, but...
You can insert explicit values with IDENTITY_INSERT
You can reseed and start reusing values
There is no built-in enforcement of uniqueness for an identity field
If the ID field is your PK, you can probably use that to get a rough idea:
SELECT *
FROM MyTable
ORDER BY IdField ASC
Per your comment, the field is a GUID. In that case, there is no way to return any sort of reliable order since GUIDs are inherently random and non-sequential.
You can use NEWSEQUENTIALID().
I came across this questions because I was facing the same issue and here is the solution that worked for me.
Alter the table and add an IDENTITY(1,1) column and that identity column will be auto-populated for existing rows when you add it. It will be in the order in which records were inserted.
It worked in my case but not sure if it works in all cases or not.
Related
Right now I have a table with three columns: GroupId,ObjectId and Data, with first two defined as partition key.
Currently it works as desired: if GroupIdand ObjectId match existing row, it gets overwritten.
I'm trying to add sorting by date, so I added third column, LastModified and specified it as clustering key. While it works for sorting, now I have multiple rows sharing the same GroupIdand ObjectId pairs, which is not what I need.
How can I achieve previous behaviour?
I could read table before writing and delete matching row before writing a new one.
I could, after reading, filter rows in my application.
I dislike both solutions because they seem to be too complicated and performance is a big concern. Is there a better way?
Here is how i did this in case someone else faces same problem:
I have a table with GroupId and ObjectId as key. I'm not sure if it matters, but ObjectId is defined as clustering key.
Then you get desired result from following view:
CREATE MATERIALIZED VIEW IF NOT EXISTS objectlistbylast
AS SELECT * FROM objectlist
WHERE groupid IS NOT NULL AND objectid IS NOT NULL AND lastmodified IS NOT NULL
PRIMARY KEY(groupid , lastmodified, objectid )
WITH CLUSTERING ORDER BY(lastmodified DESC);
Note that ordering when defining primary key matters.
Imagine a database table with a time_of_insert attribute, which is auto-filled by the current time for every INSERT (e.g. in a Django model's example, the attribute has auto_now_add=True).
In that case, is sorting the said table by time_of_insert equivalent to sorting it by each row's ID (primary key)?
Background: I ask because I have a table where I have an auto created time_of_insert attribute. I'm currently sorting the said table by time_of_insert; this field isn't indexed. I feel I can simply sort it by id, instead of indexing time_of_insert - that way I get fast results AND I don't have to incur the over-head of indexing one more table column. My DB is postgres.
What am I missing?
Now it's not.
id guarantees uniqueness. And your datetime column does not.
So in case if there are 2 rows with the same time_of_insert value - then the result set order is not guaranteed.
I'm working on an unusual table design. The primary key datatype is Guid and there is no date/time column in table. How I can order results descending?
Note that I'm not allowed to add a new column in table. Unfortunately other columns also have some flags which cannot be used for ordering data in descending order.
I need to get some of the last inserted rows.
I'm afraid that there is no way to get the last record inserted into a table with SQL Server unless you go through the transaction logs or can order by a sequential column of some sort.
See here for further details.
You may get lucky and your GUID has a date/time component or other similar sequential pattern, but without knowing how you're generating the GUIDs it's hard to say.
For your database, when inserting new rows you must use NEWSEQUENTIALID. Then you will be able to use the ORDER BY [GUID Column name] DESC to get rows in order of insertion. See https://msdn.microsoft.com/en-AU/library/ms189786.aspx
The only problem is when you restart the server it may start from a lower GUID. This maybe a problem or not depending on your circumstances.
I have two tables called VisitorMaster and SupportVisitor.
In VisitorMaster I have a column called VisitorID1 which is a primary key (but not an identity column).
In SupportVisitor I have a column called VisitorID2 which acts as a foreign key for the VisitorMaser table.But my requirement is I want the last generated column value of VisitorID1 to be inserted in VisitorID2 of SupportVisitor table.
How to achieve this..
Please Help??
I'm thinking your best bet would be to ensure that you wrap your INSERT into the VisitorMaster table with a transaction and that within the transaction you obtain the value of VisitorID using the data you've inserted to query it and finally putting that into SupportVisitor before either committing or rolling back the lot.
You could use a trigger to do this but triggers are nasty things that can have all kinds of unintended consequences since the operate more or less invisibly so I'd steer clear of them.
Ultimately though I'd ask why have you got a non-identity surrogate PK in one column? It's a pretty bad bit of design. Either use a natural key (combination of forename, surname, timestamp or whatever makes a natural unique key) or use an auto-incrementing identity field as a surrogate PK (whereupon you then can use SCOPE_IDENTITY) because otherwise your key is pretty shaky and not guaranteed to be unique. How are you generating this value? Is it held in a separate table (I've known some databases use this kind of system, especially EAV model databases, and it is not a good system in any way shape or form and isn't much easier to deal with than arbitrary values)? If you have any influence over this design at all then you should change it because this smells and is likely to cause you many, MANY more problems in future.
After inserting a record into a table with an IDENTITY-column you can retrieve this rows numeric identity by selecting the scope identity:
INSERT INTO VisitorMaster (Name) VALUES ('Jane doe')
SELECT SCOPE_IDENTITY() -- Will retrieve ID for Jane Doe
I need 1 column in the table to hold unique non-null values or NULL. TSQL UNIQUE constraint treats 2 NULLs as equal, so I cannot make column unique.
What is the right way to handle this problem?
After doing some research, I found 2 methods which seem correct to me, but I cannot determine which one is better.
The first which is not applied to all cases:
CREATE TABLE test (id INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
null_or_unique_id INT, unique_key AS
(CASE WHEN [null_or_unique_id] IS NULL THEN -(1)*[id]
ELSE [null_or_unique_id] END), UNIQUE(unique_key ));
It works but requires all allowed values of null_or_unique_id to be non-negative (that's ok in my case)
The second one :
CREATE VIEW test_view WITH SCHEMABINDING AS
SELECT [null_or_unique_id] FROM dbo.test WHERE [null_or_unique_id] IS NOT NULL;
GO
CREATE UNIQUE CLUSTERED INDEX byNullOrUniqueId
ON dbo.test_view([null_or_unique_id]);
Surely, it's also possible to implement the desired functionality with triggers, but I think trigger solution will create more overhead then any of mentioned above.
What is the best practice for such a case?
Thanks for your answers.
4 ways:
Filtered index (SQL Server 2008) <- recommended based on your tags
Trigger (mentioned)
Indexed view (in your question)
Unique constraint/index with computed column (in your question)
SQL 2008 allows you to define a filtered index - essentially an index with a WHERE clause - see Phil Haselden's asnwer to this question for MSDN links and an example.
Normalise it. Move the column to a new table together with your current table's primary key. Make the column unique and not null in the new table. Nullable unique constraints make no logical sense and are of little or no practical use.