Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a command to test an SQL query without executing it? ( MySQL or ANSI SQL )

Is there anything like this:
TEST DELETE FROM user WHERE somekey = 45;

That can return any errors, for example that somekey doesn't exist, or some constraint violation or anything, and reporting how many rows would be affected, but not executing the query?
I know you can easily turn any query in a select query that has no write or delete effect in any row, but that can lead to errors and it's not very practical if you want to test and debug many queries.

like image 806
Petruza Avatar asked Mar 12 '10 15:03

Petruza


People also ask

How can I test a SQL script without executing?

A solution for this is the noexec parameter. By default it is set to off but it can be enabled, if you want to test a script without executing it. The parameter tells SQL Server to parse the script and that is it, no execution.

How do I practice SQL in CMD?

Open a Command Prompt window, and type sqlcmd -SmyServer\instanceName. Replace myServer\instanceName with the name of the computer and the instance of SQL Server that you want to connect to. Press ENTER. The sqlcmd prompt (1>) indicates that you are connected to the specified instance of SQL Server.


4 Answers

The only thing I know of is to wrap it in a transaction that is always rolled back:

BEGIN TRANSACTION

DELETE FROM user WHERE somekey = 45;

ROLLBACK TRANSACTION

Make sure you execute the entire block and not just the delete statement. Also, DO NOT run this on any production environment or any system where you cannot afford to lose the data.

like image 137
DCNYAM Avatar answered Oct 09 '22 14:10

DCNYAM


As of MySQL 5.6, the EXPLAIN keyword works with SELECT, DELETE, INSERT, REPLACE, and UPDATE statements.

If your query has a syntax error, then it will still fail, however if successful you will only see the results of an EXPLAIN and the query will not make any changes.

This is much simpler than doing schema changes, using temp tables, or aborting transactions as all you need to do is insert "EXPLAIN " in front of your existing query.

More information: https://dev.mysql.com/doc/refman/5.6/en/explain.html

like image 20
DOOManiac Avatar answered Oct 09 '22 14:10

DOOManiac


In MySQL use this

START TRANSACTION;
QUERY;

It is important to use ";" because if you don't, it won't work. For example

START TRANSACTION;
UPDATE tableX SET colX = valueA, colY = valueB WHERE id=1

Reference here http://dev.mysql.com/doc/refman/5.0/en/commit.html

like image 9
絢瀬絵里 Avatar answered Oct 09 '22 13:10

絢瀬絵里


ANSI SQL: No.

MySQL: Maybe. The EXPLAIN keyword originally worked only with SELECT, but it might have been extended to UPDATE and DELETE by now.

like image 6
Larry Lustig Avatar answered Oct 09 '22 13:10

Larry Lustig