Jihane Elberouhi
Jihane Elberouhi

Reputation: 55

Detect Whether the first query is fininished in sql then run a second

I am trying to execute two queries in Sql but i want to run the second only when the first one is executed.

here is an example to help understanding what i am trying to do:

-------------------------------
| id | name  | level | passed |
|--------------------|--------|
| 1  |Jose   | A     | YES    |
|--------------------|--------|
| 2  |Jeehan | B     | YES    |
|--------------------|--------|
| 3  |Sara   | D     | NO     |
|--------------------|--------|
| 4  |Sami   | B     | YES    |
|--------------------|--------|
| 5  |Lucy   | C     | NO     |
|--------------------|--------|
| 6  |Maria  | A     | YES    |
|--------------------|--------|

Now i want to select first users who has (passed=YES).

Then run a second query to show all rest of users.

I don't want to order them by YES or NO because i don't want them to be ordered. i want first query to give me random users but all has same value of passed column. and also second gives me random users with same value of the column.

here what i did but it doesn't work.

(SELECT * FROM users WHERE passed='yes' ORDER BY RAND()) UNION 
(SELECT * FROM users WHERE passed='no' ORDER BY RAND())

Upvotes: 2

Views: 34

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270081

Just use a single order by:

SELECT u.*
FROM users u
ORDER BY u.passed DESC, RAND();

This assumes that passed only takes on the values 'yes' and 'no'. If it takes on other values, then filter first:

SELECT u.*
FROM users u
WHERE u.passed IN ('yes', 'no')
ORDER BY u.passed DESC, RAND();

Upvotes: 2

Related Questions