0

I have table documents (id, name, time). Is there a special sql command to set table limit by 10 rows?

6
  • 2
    Are you looking to limit the amount of rows in the table, or the number of rows returned by a select statement? Commented Nov 24, 2011 at 9:11
  • i need to limit amount of rows in the table Commented Nov 24, 2011 at 9:16
  • Well then see Haim's answer. It's not possible in any traditional sense. Commented Nov 24, 2011 at 9:19
  • 1
    Also can I ask why you want to do this? I'm sure there is another way to achieve what you are looking for. Commented Nov 24, 2011 at 9:20
  • in this table is information of saved documents name, so i'm using this table for displaying "latest 10 generated documents" Commented Nov 24, 2011 at 9:23

3 Answers 3

2

If you just want to display the "latest 10 generated documents", no need for a separate table. Just use a query on your existing table:

SELECT id, name, `time` FROM documents ORDER BY `time` DESC LIMIT 10 
Sign up to request clarification or add additional context in comments.

Comments

2

no you could not set a limit on the mysql table, you can achive this with trigger that delete rows.

Comments

2

So, if you have a table like this:

CREATE TABLE documents ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR( 99 ) NOT NULL, `time` DATETIME NOT NULL ) ENGINE = MYISAM 

then you can use this horrible query to limit row numbers by recycling the row having the lowest id field:

INSERT INTO documents (id,name,time) SELECT IF( (SELECT COUNT(*) FROM documents) < 3 -- max row number you allow ,NULL -- just use autoincrement id ,(SELECT MIN(id) FROM documents) -- update row with smallest id ), -- your values to insert 'name' ,'2011-11-11' ON DUPLICATE KEY UPDATE id = (SELECT MAX(id)+1 FROM documents) -- new id -- your values again, now for update ,name = 'name' ,time = '2011-11-11' 

Somebody please confirm if this query is atomic, i think it is, but who knows…

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.