4

I'm need to exclude some rows by id from SQL query results, but which way will be better to do this?

Using NOT IN by primary key id:

SELECT id, key1, key2 FROM my_table WHERE id NOT IN (#EXCLUDE_IDS)

Or in the post-processed loop after query in the script:

 foreach ($rows as $i => $row) {
    if (isset($exclude[$row['id']])) {
      unset($rows[$i]);
    }
 }

 # or
 for ($i = count($rows) - 1; $i >= 0; $i--) {
    if (isset($exclude[$rows[$i]['id']])) {
      unset($rows[$i]);
    }
 }
3
  • 3
    Do it in the query. Why fetch data you don't need? Commented Dec 16, 2015 at 8:36
  • I think in general you want to do things in SQL if possible, however large not in lists can be slow. But in this case probably not slower than processing it in PHP Commented Dec 16, 2015 at 8:36
  • How do you identify the IDS that you want to exclude. Tell us that and someone will come up with a SQL Query to match yor needs. Commented Dec 16, 2015 at 9:09

3 Answers 3

3

When querying from the database, you want to only get information that you require, which why you have the option of selecting the columns in your select statement with the ability to use the conditions in the where

In this case: 1. If you wish to exclude one specific primary key then

SELECT ID, KEY1, KEY2 FROM TABLE WHERE ID != 1

2. If it based on multiple ids then

SELECT ID, KEY1, KEY2 FROM TABLE WHERE ID NOT IN (ids)

3. If you wish the exclude to be based on a separate query, then

SELECT ID, KEY1, KEY2 FROM TABLE WHERE ID NOT IN(
    SELECT  ID
    FROM    TABLE2
    WHERE   ID IS NOT NULL )

An alternative to the NOT IN is 'NOT EXISTS'

Sign up to request clarification or add additional context in comments.

Comments

2

You should fetch the data which is needed. So doing it in the query with excluding those ids is better option. It also decrease the execution and cost.

Comments

0

What you need is to use next clouse:

SELECT id, key1, key2 FROM my_table WHERE id NOT REGEXP '[regexp]';

Where regexp describes list of ids you want to exclude.

1 Comment

Any documentation link to your answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.