How to select all even id's from a Table?

How to select all even id's from a Table?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Filtering Data by ID Parity: A Database-Centric Approach

Separating records based on whether their identifier is even or odd is a common requirement when implementing alternating layouts, pagination schemes, or specific UI patterns. While the logic seems trivial in JavaScript—applying id % 2 === 0 to an array—it often makes more architectural sense to handle this filtering at the database layer using PHP. Pushing this logic into the application code increases memory usage and processing time as you must load every row into memory before applying a filter, whereas SQL engines are optimized for set-based operations.

To retrieve even IDs from a MySQL table, you leverage the modulo operator within your WHERE clause. The expression id % 2 = 0 evaluates to true only when the remainder of the division is zero, effectively isolating even numbers. Conversely, id % 2 != 0 captures all odd identifiers.

Consider a standard MySQL query structure for this task:

SELECT id, text FROM posts WHERE id % 2 = 0;

This single statement returns only the rows with even IDs. To fetch the odd counterparts, you simply invert the condition:

SELECT id, text FROM posts WHERE id % 2 != 0;

In a PHP context using PDO or MySQLi, this translates to building two distinct queries and binding them to separate data containers. You can then iterate over these arrays independently to render your "Even Rows" section followed immediately by your "Odd Rows" section.

Implementation in PHP

Here is how you might structure the logic using PDO prepared statements to prevent SQL injection while maintaining separation of concerns:

$pdo = new PDO('mysql:host=localhost;dbname=your_database', $user, $pass);

// Fetch even IDs
$evenStmt = $pdo->prepare("SELECT id, text FROM posts WHERE id % 2 = 0");
$evenStmt->execute();
$evenPosts = $evenStmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch odd IDs
$oddStmt = $pdo->prepare("SELECT id, text FROM posts WHERE id % 2 != 0");
$oddStmt->execute();
$oddPosts = $oddStmt->fetchAll(PDO::FETCH_ASSOC);

By executing these queries separately, you ensure that the database engine optimizes the execution plan for each specific subset of data. This approach avoids loading unnecessary data into your application memory. If you attempted to SELECT * from the entire table and filter in PHP, you would waste resources processing records you never intend to display.

Performance and Trade-offs

There is a minor edge case to consider: auto-increment fields do not guarantee that IDs will be strictly sequential or contiguous if rows are deleted frequently. However, since the requirement relies on the numerical value of the id column rather than physical row position, the modulo arithmetic remains valid regardless of gaps in the sequence. An ID of 10 is even, whether it was assigned to the first record inserted after a deletion or not; the mathematical property holds true.

Another consideration involves data volume. If your table contains millions of rows and you frequently need to switch between viewing odd and even sets dynamically, maintaining separate query results in PHP arrays is efficient for small-to-medium datasets but consumes memory proportional to the result set size. For extremely large datasets where only a few records are needed at a time, you might consider adding an index on the id column (which is typically already indexed as a primary key) to ensure the optimizer can quickly locate these specific subsets without a full table scan if additional filtering conditions were introduced later.

Why Not Do This in JavaScript?

While it is technically feasible to fetch all posts via a single API call and filter them client-side using JavaScript, this approach introduces latency. The server must transmit the entire dataset over the network before the browser can apply the id % 2 logic. By filtering at the database level with PHP, you reduce the payload size sent to the client and offload the computational work to the database server, which is designed for such mathematical operations on bulk data.

For developers working within the Laravel ecosystem, this pattern aligns well with their existing Eloquent query builder methods. You could construct these queries directly in controllers or service classes, passing the resulting collections to views without additional manual iteration logic. This keeps your presentation layer clean and focused solely on rendering the data that has already been logically partitioned by the backend.

Our network