# SQL Query - First and Last Entry

**URL:** <https://forum.inductiveautomation.com/t/sql-query-first-and-last-entry/64656>\
**Category:** Ignition\
**Tags:** database\
**Created:** [September 29, 2022, 2:22pm UTC](https://forum.inductiveautomation.com/t/sql-query-first-and-last-entry/64656 "2022-09-29T14:22:14Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![amarks](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/amarks/32/45610_2.png) [@amarks](https://forum.inductiveautomation.com/u/amarks)\
**Post date:** [September 29, 2022, 2:22pm UTC](https://forum.inductiveautomation.com/t/sql-query-first-and-last-entry/64656/1 "2022-09-29T14:22:14Z")

</div>

Using MS SQLExpress, trying to use a single query to get the first and last entry in the table. Could easily do it with two queries, but would like to use one

My two query statements

```auto
Select top 1 t_stamp from Data order by t_stamp asc

```

and

```auto
Select top 1 t_stamp from Data order by t_stamp desc

```

work just fine on their own  
 ![image](https://us1.discourse-cdn.com/inductiveautomation/original/3X/d/5/d5c92822e80e4a874f5a52ecaadb4c13f81b0cd4.png)

![image](https://us1.discourse-cdn.com/inductiveautomation/original/3X/0/7/07d3d77ccf65401f27bd4475768d4c08f9282c62.png)

But I get a syntax error when I try to union them  
 ![image](https://us1.discourse-cdn.com/inductiveautomation/original/3X/1/c/1cf0d7ad501c0ca74dddfc704a159db7b57f7d35.png)

Tried using parenthesis around the select statements, but then get an error on the select statement itself.

 ![image](https://us1.discourse-cdn.com/inductiveautomation/original/3X/2/c/2c083ba758c8820cbaad5ba93ef2c8f41bd6874b.png)

---

<div class="post-metadata">

**Author:** ![paul-griffith](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/paul-griffith/32/37249_2.png) [@paul-griffith](https://forum.inductiveautomation.com/u/paul-griffith)\
**Post date:** [September 29, 2022, 2:27pm UTC](https://forum.inductiveautomation.com/t/sql-query-first-and-last-entry/64656/2 "2022-09-29T14:27:04Z")

</div>

You have to wrap your two statements into subqueries, because SQL doesn’t allow you to have two independent `ORDER BY` clauses on the “same” data (the result of your UNION).

> <https://stackoverflow.com/questions/2927475/select-top-and-bottom-rows>

---

<div class="post-metadata">

**Author:** ![amarks](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/amarks/32/45610_2.png) [@amarks](https://forum.inductiveautomation.com/u/amarks)\
**Post date:** [September 29, 2022, 2:47pm UTC](https://forum.inductiveautomation.com/t/sql-query-first-and-last-entry/64656/3 "2022-09-29T14:47:37Z")

</div>

Thanks! Works like a charm  
 ![image](https://us1.discourse-cdn.com/inductiveautomation/original/3X/f/a/fa7ae1b6fcbb50e80ea70999862171ae6f7121d3.png)
