Jump to content

Using ORDER BY and WHERE in the same SQL statement


Recommended Posts

Hello. I seem to have an issue where adding an `ORDER BY` clause with a `WHERE` clause removes everything completely and I get nothing. I am confused since I am using a statement:
SELECT * FROM forum_answer WHERE question_id='".$id."'"
and then it orders everything descending by default. Example is shown below.

(cause I can't share images, here)

Chat:

ID: 1

Yo. Anyone here?

ID: 2

Yep. This website is pretty cool.

ID: 3

I agree.


I want instead for the answers to the forum (yes, I created an entire forum system from scratch instead of using a pre-made one) to order ASCENDING instead of DESCENDING, in this case the newest answers shown first instead of last. I have it so that my code inserts a new row into the database, and then have the database add the primary key by 1 for each new row. Thus, the oldest answer will have an id of 1, and the newest id an id of 26 if there are 26 answers in that thread. Hope that makes sense. Anyways, onto my current issue. As I said, I want the answers to be ordered ascending, but after some research, it seems that no one has had the same problem as me (after some Googling). I want my statement to be something like this:
SELECT * FROM forum_answer ORDER BY question_id ASC WHERE question_id='".$id."'"
Code: https://hatebin.com/qnqhnidqsh

SQL statements are like a recipe: there are a variety of things you can combine together to get the desired end result, but you have to do them in a certain order for it to work.

For example, WHERE clauses have to come before ORDER BY clauses.

13 minutes ago, requinix said:

SQL statements are like a recipe: there are a variety of things you can combine together to get the desired end result, but you have to do them in a certain order for it to work.

For example, WHERE clauses have to come before ORDER BY clauses.

Thank you! It seems to work now. Thanks!

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.