<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by hicham ouabella on Medium]]></title>
        <description><![CDATA[Stories by hicham ouabella on Medium]]></description>
        <link>https://medium.com/@ouabe2002hisham?source=rss-e3ef5fb6c9ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mT0cEQ5ytu0m-jZF</url>
            <title>Stories by hicham ouabella on Medium</title>
            <link>https://medium.com/@ouabe2002hisham?source=rss-e3ef5fb6c9ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:20:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ouabe2002hisham/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[HOW SQL Actually executes]]></title>
            <link>https://medium.com/@ouabe2002hisham/how-sql-actually-executes-7b9c8b9b0c8f?source=rss-e3ef5fb6c9ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b9c8b9b0c8f</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[sql-injection]]></category>
            <category><![CDATA[web-penetration-testing]]></category>
            <dc:creator><![CDATA[hicham ouabella]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 02:16:51 GMT</pubDate>
            <atom:updated>2026-03-15T02:16:51.303Z</atom:updated>
            <content:encoded><![CDATA[<h3>why you need this</h3><p>most of sql injection tutorials starts at the exploit . like they alwas start by the famous payload &#39; OR 1=1 # without knowing what’s actually happened there . so like that you find your self almost (memorizing the payloads , if you test those bunch of payloads and no sqli found then it’s not there).</p><p>that’s happens because you learned the surface without the substrate.</p><p>so .. ! This article fixes that. we are going to walk through HOW DATABASE ENGINE ACTUALLY PROCESSES A SQL QUERY from the moment your string arrives , to the moment rows come back. every concept we cover will be tied directly to an attack surface . by the end , you will not just know WHAT to inject, you will know WHY IT WORKS AT THE EXECUTION LEVEL, which is the difference between a (person who hack) and someone running scripts.</p><h3>The lie you were taught about sql (or at least you think about sql)</h3><p>when you first learned sql, you were implicitly taught that queries execute in the order they are written;</p><p>per example when :</p><p>SELECT name, email FROM users WHERE active = 1 ORDER BY name ASC LIMIT 10;</p><pre>| SQL Statement           | Explanation           |<br>|-------------------------|----------------------|<br>| SELECT name, email      | 1. Pick these columns |<br>| FROM users              | 2. From this table    |<br>| WHERE active = 1        | 3. Filter these rows  |<br>| ORDER BY name ASC       | 4. Sort them          |<br>| LIMIT 10;               | 5. Take the first 10  |</pre><p>This mental model is wrong and it matters from SQL injection.</p><p>the written order is declarative syntax . it is how you describe what you want , but the database doesn’t execute queries in that order , it has its own internal pipeline .</p><p>so the 2 orders are fundamentally different.</p><p>Understanding this difference is not academic , it directly controls:</p><ul><li>where your injection payload lands in the processing pipeline.</li><li>what data visible to each clause and therefore what you can extract.</li><li>why some injections work in WHERE but not in SELECT , or work in ORDER BY but nowhere else</li><li>why some clauses (like HAVING) can be weaponized to leak database schema through aggregate errors, while injecting the exact same payload into a WHERE clause will just crash.</li></ul><h3>The real execution pipeline</h3><p>here is the actual logical processing order of a sql select statement . (This is not specific to Mysql or PostgreSQL , it’s part of the ANSI SQL standard and every major database follows it) “with some minor variations in optimization”</p><pre>| Step    | SQL Operation &amp; What It Does |<br>|---------|-----------------------------|<br>| Step 1  | FROM / JOIN (allocate buffer in memory and load data into it) |<br>| Step 2  | WHERE (drops all rows that are not true, filters individual rows) |<br>| Step 3  | GROUP BY (collapse rows into groups) |<br>| Step 4  | HAVING (filter groups) |<br>| Step 5  | SELECT (compute output columns + aliases) |<br>| Step 6  | DISTINCT (remove duplicate rows) |<br>| Step 7  | ORDER BY (sort the output) |<br>| Step 8  | LIMIT / OFFSET (page the output) |</pre><h3>The parser: how the database reads your input</h3><p>before any of the execution stages above run, the database has to parse the raw SQL string you sent. Understanding the parser is critical because SQLI IS FUNDAMENTALLY A PARSING ATTACK. you are not breaking into the database through a vulnerability in it’s encryption or whatever else. you’re just making the parser misidentify the boundary between data and code.</p><h4>lexical analysis (Tokenization)</h4><p>the first thing the parser does is break the raw SQL string into flat list of tokens. A token is the smallest meaningful unit of SQL. The lexer reads character by character and classifies everything it sees:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*y0ZgCZa_gdcTRzRkTbgn4w.png" /></figure><p>if you want to see that in the source code you can see those sources:</p><p><a href="https://github.com/postgres/postgres/blob/master/src/backend/parser/scan.l">https://github.com/postgres/postgres/blob/master/src/backend/parser/scan.l</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fm8PtOY3aWL0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dm8PtOY3aWL0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fm8PtOY3aWL0%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2993fdca6fc60f193ddd032144fe55f/href">https://medium.com/media/c2993fdca6fc60f193ddd032144fe55f/href</a></iframe><p><a href="https://www.postgresql.org/docs/current/parser-stage.html">51.3. The Parser Stage</a></p><p>The lexer uses a state machine . At any point, it is in one of several states: reading an identifier, reading a string literal, reading a number, reading a comment, etc. Each state has rules about what characters are valid and what state transitions are allowed .</p><p>the single quote ‘ is the most exploited character is SQLI becuase it’s a state transition character for string literals. When the lexer sees ‘, it transitions from “reading code” to “reading string literal”. The next ‘ transition it will make the state back. everything between the quotes is treated as data not code .</p><p>By passing an unexpected quote, you force the lexer to prematurely exit the ‘reading string literal’ state and drop back into the ‘reading code’ state. From that exact character onward, the parser stops treating your input as harmless text and begins tokenizing your payload as executable database commands. :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*TNgQz9I1vPBnsNS63qYjNA.png" /></figure><h4>syntax analysis (the parser Tree)</h4><p>after the tokenization, the parser takes the tokens and build a parse tree (also called an Abstract syntax tree AST) . the AST represent the grammatical structure of the query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*i6h3XnxPntgj7j9MxY3ROQ.png" /></figure><p>the parse tree is what the engine actually works with , not the original string . This is why SQL keywords are case-ensensitive: the lexer normalizes them before they reach the tree. SELECT, select, and SeLect all produce the same token :[KEYWORD:SELECT] token.</p><h4>comments as weapons</h4><p>SQL supports 2 comment syntaxes. Both cause the lexer to discard everything until the end of the comment , which is one of the most powerful injection tools available beside the normalization phase happened in the lexer too, let’s leave the normalization rabbit hole to other articles 🙂.</p><pre>| SQL Comment Type                                                                  |<br>|-----------------------------------------------------------------------------------|                                                               |<br>| `--` single line comment (standard SQL, MySQL, PostgreSQL, MSSQL)                 |<br>| `#` single line comment (MySQL only)                                              |<br>| `/* ... */` multi-line comment (all databases)                                    |<br>| `/*! ... */` MySQL-specific inline comment — executes in MySQL, ignored elsewhere |</pre><p>for injection, comments serve 2 primary purposes:</p><ol><li>Termination: cut off the remainder of the original query after your payload</li><li>Bypass: split keywords to evade pattern-matching filters</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*Y1nWxit__Z9ZfuMZpfVtcQ.png" /></figure><h3>The query optimizer: What happens before execution</h3><p>the optimizer performs several types of rewrites, to make it better (it’s called the planer too).</p><p>and the important ones for hackers are :</p><ol><li>Short-circuit evaluation: is a database optimization trick where the engine stops reading a query the moment it knows the final True/False outcome. For hackers doing Time-Based SQLi, this can hide vulnerabilities. If you inject AND sleep(1) on a condition that evaluates to False (like a wrong username), the database skips your sleep entirely, giving a 0.00s response and making the site look secure. To bypass this, always test with both AND and OR. If AND gives you no delay, flip it to OR to force the engine to execute the sleep. Conversely, if your OR payload causes a massive timeout because the database is executing the sleep on every single row in the table, simply append LIMIT 1 to kill the table scan and get a clean, reliable delay.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*3Hmvl9xor-hsDpAirJdmCQ.png" /></figure><p>you can search for those (just for fun):</p><ol><li>Predicate pushdown: WHERE conditions are pushed as close to the data source as possible. so a filter on a subquery can get moved inside another subquery , changing where your injection takes effect.</li><li>Constant folding: Expressions with only constants are pre-evaluated. so 1=1 becomes TRUE before the execution.</li></ol><h3>How database sees your injected input</h3><p>this is the core of that vulnerability , as we said SQLI is parsing attack but the more important detail is how this database engine see our input .</p><h4>string concatenation: the root cause</h4><p>SQL injection is only possible when user input is combined with SQL code through string concatenation before the combined result is sent to the database parser, the parser receive a single string and has no way to know which part were ‘code’ and which part were ‘data’.</p><pre>user_input = request.form[&#39;username&#39;]<br># THE FATAL FLAW: String Concatenation<br>query = f&quot;SELECT id, dept FROM users WHERE username = &#39;{user_input}&#39;&quot;<br><br>cursor.execute(query)<br><br># if the input were &quot;zoublik&quot; then we have a query like :<br># SELECT id, dept FROM users WHERE username = &#39;zoublik&#39;<br># but if the input were &quot;admin&#39; OR 1=1 -- -&quot; the query will be :<br># SELECT id, dept FROM users WHERE username = &#39;admin&#39; OR 1=1 -- -&#39;</pre><h4>Parameterized Queries: Why They Actually Work</h4><p>parameterized queries fix the injection not by escaping your input but by sending the code section and the data through separate channels , the SQL code is parsed first , then the parameter value are bound after parsing in simple terms (YOUR INJECTED INPUT WILL NEVER BE PARSED).</p><pre>user_input = request.form[&#39;username&#39;]<br># the code channel :<br>query = &quot;SELECT id, dept FROM users WHERE username = ?&quot;<br># input passed as a parametter<br>cursor.execute(query, (user_input,))<br># this one will make the attacker injection looks like that :<br># SELECT id, dept FROM users WHERE username = &quot;admin&#39; OR 1=1 -- -&quot;<br># [admin&#39; OR 1=1 -- -] this one will be as one block ( a simple string ). that&#39;s it</pre><p>However, parameterization is not a universal fix. It only protects <em>data values</em>, not structural identifiers. If an application requires a dynamic query where the planner must build a completely different execution plan based on the input, parameters physically cannot be used. For example, you cannot parameterize a table name (SELECT * FROM ?) or a sorting column (ORDER BY ? DESC). Because the engine must know the exact table and columns to check permissions and indexes <em>before</em> execution, developers are forced to fall back to vulnerable string concatenation for features like dynamic column sorting (?sort_by=price) or dynamic table routing.</p><h4>Second order injection: injection that sleeps (for a while HIHI)</h4><p>second order injection (also called stored injection) happens when input is safely stored, but later retrieved and used unsafely. the injection doesn’t fire on the first request , it fires on a second request that reads the stored data. per example you can name your self in a platform some random sql query and then try to update your password so when the backed tries to :</p><pre># username is &quot;admin&#39; OR 1=1--&quot; stored safely BUT :<br>UPDATE users SET pass=&#39;new123&#39; WHERE username=&#39;admin&#39; OR 1=1 --&#39;</pre><h3>Injection Points Mapped to Execution Stages</h3><p>When you find an injection point, the clause you land in dictates exactly what tools you can use. You cannot escape the clause context or it’s order (you know ! the stacked queries are not allowed ). you have to play by it’s pipeline rules. here is how stages now will make sense .</p><h4>FROM clause injection point:</h4><p>this stage allocates the initial data buffer, it controls the literal source of the data before any filtering happens. since it’s step 1 you can completely swap the working data set, pointing the query to information_schema to map the database or switch from low privilege table to a high privilege one . or UNION based injection as well 🙂.</p><p>per example:</p><pre># the query  is : SELECT * FROM &#39;[input]&#39;<br>SELECT * FROM information_schema.tables</pre><h4>WHERE clause injection point:</h4><p>this stage evaluates the working set row by row and drops the false one , and because it runs at stage 2 (before the output is generated in stage 5 (SELECT) you can easily satisfy the filter and append a “UNION SELECT” so the engine finishes the WHERE filter , moves down the pipeline and cleanly stack your union data into the final output .</p><pre># SELECT dept FROM users WHERE username = &#39;[INJECT]&#39;<br>SELECT dept FROM users WHERE username = &#39;admin&#39; UNION SELECT password FROM users --&#39;</pre><h4>HAVING clause injection point:</h4><p>this stage filters data <em>after</em> it has been grouped together (</p><p>GROUP BY</p><p>). Therefore, all the attacker needs to do is inject a valid boolean expression (using logic, aggregates, functions, or subqueries) to manipulate which groups are returned or knowing some data out of that groups scope using some conditional sleeps or even aggregate errors that leak table and column names [THIS LAST ONE WE WERE TALKING ABOUT MSSQL].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*T83M0he2lIjRxdRdGvTpqg.png" /></figure><h4>ORDER BY clause injection point:</h4><p>this stage sorts the final output data after it has already been selected (SELECT ). Therefore, all the attacker needs to do is inject a valid sorting expression (using CASE WHEN logic, subqueries, or functions). You can use this to manipulate how the rows are ordered on the screen to extract true/false answers, pull out-of-scope data using conditional sleeps per row, or force function errors that leak hidden data directly into the error log [like using EXTRACTVALUE() in MySQL].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*LmcQIKBoS0FrpXw5Cgr8Gw.png" /></figure><p>Honestly, maybe I just overthought this entire thing and I’m just talking BS right now to sound smart. But at the end of the day, if you know how the engine breathes, you know how to choke it.</p><p>See you in the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b9c8b9b0c8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>