What is the best approach for executing delete and update queries on MySQL databases?

When it comes to deleting or updating ID information from a database, what is the most effective approach? Should I first check if the ID exists before making any changes, or should I update the data and then verify the result to see if the data actually exists?

Option 1

let find_id = "Select id from MyGuests where id=2";
if(find_id.length === 0 || find_id.length === undefined) {
     return not found //exit immediately
}
let result = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"
return result;

Alternatively, should I consider this method?

Option 2

let result = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"
if (result === 0) {
    return not found
}
return result;

The same question arises when dealing with delete queries. Which approach is more optimal in this case?

Answer №1

It is generally recommended to minimize the number of database queries for efficiency. To achieve this, simply execute the UPDATE or DELETE query and then verify the count of affectedRows in the returned result.

let sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
con.query(sql, function (err, result) {
    if (err) throw err;
    if (result.affectedRows == 0) {
        console.log("ID not found");
    }
});

Remember that database queries operate asynchronously, so you cannot expect a synchronous return of results. For more information on handling asynchronous calls, refer to How do I return the response from an asynchronous call?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to dividing content in ASPX files

I have code that retrieves multiple data entries from the database. My expected output is: 1. line1 2. line2 However, when using this code, I get: 1. line12. line2 Even though the data from the database contains new lines. This is the code snippet: ...

Detecting empty or default form fields in Angular using Reactive Forms to disable buttons

Is it possible to disable the submit button when the initial form is empty, and enable it if any value is not empty? <form [formGroup]="registerForm" (ngSubmit)="onSubmit()"> <div class="form-row"> ...

Can Elements be classified as Method, Constant, or Component?

When it comes to grouping up reusable elements, I have a few options: constants, methods, or components: const someElementsConst = <div><p>Some Elements</p></div> const getSomeElements = () => <div><p>Some Elements&l ...

Issue with Angular 5: Unable to update template within Observable sequence

When I have a component and need to display a loader Here is the component code: ngOnInit() { this.route.params .do(x => this.contentLoading = true) .switchMap(x => this.getClientSearchResults()) .subscribe(x => { ...

Uh oh! The dreaded Error [ERR_HTTP_HEADERS_SENT] has struck again in the Node Express MongoDB world. Headers cannot be set after they have

Hey there, newbie in the coding world! I've been diving into a guide on setting up a backend server using Node.js, Express, and MongoDB. You can find the guide here: But I seem to keep running into an error when testing with Postman. Error [ERR_HTTP ...

AngularJS offers the same features as Dev HTTP Client for similar functionality

Currently, I am developing a web interface using AngularJS. My goal is to achieve similar functionality as the Dev HTTP Client, but I am struggling with adding headers the way DHC does. I have attempted to implement it like this, but it's not working ...

Generating multiple dropdown menus using PHP

I am currently facing an issue with getting a second dropdown box to repeat another "onchange" function. I have 3 dropdown lists that need to be populated from an SQL database using PHP and javascript/ajax. The first list starts with filled options, and th ...

Using a conditional statement to control the visibility of a button depending on the outcome of the game

I run 1v1 browser games on my website and I want to display a button for the winner but not for the loser in a pop-up modal after the game. Specifically, I am targeting the "Claim Prize" button on the Pop-up Modal "Claim Prize" Here is the HTML code for t ...

Handlers for mouseover, mouseout, and click events are failing to trigger

Take a look at this code snippet - setEvents:function(a, b){ if(b) { $('#id').mouseover(function(){ console.log('mouse over') }) $('#id').mouseout(function(){ console.l ...

Problem encountered when populating table using JSP AJAX and jQuery

I created a servlet that pulls information from a MongoDB database and presents it in a table on a JSP file: The servlet: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { MongoClie ...

What is the best way to embed MongoDB queries in Node.js?

I have a group of users with the following details: { "_id" : ObjectId("56f60e4eea8af4670408483e"), "twitterHandle" : "shrutip", "firstName" : "Shruti", "lastName" : "Patil", "emailID" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...

Understanding the functionality of $q in AngularJS

Can someone help explain how $q functions in Angular? Let's say I have a few lines of code that need to be executed. var app = angular.module('app', []); app.controller('HelloCtrl', function ($q, $scope) { $scope.Title = "Pr ...

Vue JS - Issue with data reactivity not being maintained

Currently, I have implemented a pagination indicator that displays the number of results on each page. For instance, page 1 shows '1-5' and page 2 shows '6-10 out of 50 results', and so on. The logic for updating the results seems to b ...

Retrieve most recent information from two combined tables

After extensively searching through various SQL query questions, I have not been able to pinpoint a solution that works for my particular case... so, here is my question. I am working with two MySQL tables: players: pid pname player_stats: pid statdate ...

Storing Material-UI Choices Using Redux State

Looking to integrate a Material-UI Select component with Redux data for persistent selections after page refresh. Within Redux, I have two arrays: the sourceTags array, consisting of clickable menu options, and the selectedTags array, containing the user& ...

When implementing Firebase Cloud Messaging with React, the token generated by firebase.messaging().getToken() will vary with every refresh

I'm working on a React web app using Gatsby and I want to integrate push notifications through FCM. My firebase-messaging-sw.js service worker is set up, and I'm trying to retrieve a token using the following method in my app: messaging .req ...

Retrieve information based on the class

I've been struggling for hours trying to find a solution. Here's a simplified version of my code: PHP : foreach($db->query("SELECT id FROM news ORDER BY position ASC") as $row) { ... <input type="text" class="_title" > ...

The image loading and completion count function in JavaScript experiences sluggish performance on mobile devices

While this feature performs optimally on all the desktop browsers I've checked, it tends to have a glitch on mobile browsers. It often skips from 0% to 100% right away upon loading, or shows only a few numbers in between like 0%, 30%, 67%, 100%. Is th ...

Error encountered in ES6 destructuring syntax

Could you please assist me in figuring out what is causing the issue here: var foo = { bar: 1, baz: 2 }; var { bar, baz } = foo; I encountered an error SyntaxError: Unexpected token {. I am using node v5.4.1 and I am unsure if the problem lies wit ...

Using jQuery's Ajax function to retrieve or send information within the "error" field

Seeking guidance for a minor question that has proven difficult to find the solution to on Google. My query involves utilizing the data setting within the error: function. To provide some context, consider the following example. I am working with an Ajax ...