Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
when i am trying extract through `regexp` from the below source by using `\|(.*?),1,2` this, i am getting up to end but i need to 3rd / only. when i use `\|(.*/){1,3},1,2` it is giving `http://localhost:6148372/content/bdsajf` and i am stuck up at ending search position. please help me on this.
```
U=https://www.abcdf... | Try the following expression:
```
\|([^/]*/*[^/]*)
```
See [live demo](http://www.regex101.com/r/rH1qM1) | Try `'\|([^/]*/){1,3}'` (11i):
```
SQL> SELECT regexp_substr(txt, '\|(([^/]*/){1,3})', 1, 1, 'i', '1') regexp
2 FROM DATA;
REGEXP
--------------------------------------------------------------------------------
http://llcwokhfkdvc.webs.com/
http://localhost:6148372/
```
In 10g:
```
SQL> SELECT ltrim(regexp_sub... | need to parse up to 3rd / in a string by using regexp in sql | [
"",
"sql",
"regex",
"oracle",
""
] |
Imagine 2 tables, the first one is a list of products (products), the second one a join table between products and another table (categories), called products-categories
products:
```
id | name
------------
1 Lorem
2 Ipsum
3 Dolor
4 Sit
```
products-categories
```
product_id | categor... | ```
select * from products p
left join product_categories pc on p.id=pc.product_id
where pc.product_id is null
```
will return all products in table products that are not found in product\_Category. LEft join and where is very fast. 30k records is also very little, so don't worry there. | You can achieve this in 2 ways:
Using SubQuery:
```
SELECT name FROM products
WHERE id NOT IN (SELECT product_id FROM products-categories);
```
or Using JOIN (preferred way)
```
SELECT name FROM products
LEFT JOIN products_categories ON (id=product_id)
WHERE product_id IS NULL;
```
Better to go with join
sqlfidd... | how to get orphans from a join table in MySQL | [
"",
"mysql",
"sql",
"myisam",
""
] |
For example, I have table:
```
ID | Value
1 hi
1 yo
2 foo
2 bar
2 hehe
3 ha
6 gaga
```
I want my query to get ID, Value; meanwhile the returned set should be in the order of frequency count of each ID.
I tried the query below but don't know how to get the I... | ```
select t.id, t.value
from TABLE t
inner join
(
SELECT id, count(*) as cnt
FROM TABLE
group by ID
)
x on x.id = t.id
order by x.cnt desc
``` | you can try this -
```
select id, value, count(*) over (partition by id) freq_count
from
(
select 2 as ID, 'foo' as value
from dual
union all
select 2, 'bar'
from dual
union all
select 2, 'hehe'
from dual
union all
select 1 , 'hi'
from dual
union all
select 1 , 'yo'
from dual
union... | How to do select count(*) group by and select * at same time? | [
"",
"sql",
"oracle",
""
] |
I have a more detailed description ready, but I thought I'd try the simple one first.
```
X Y
7 F
7 F
7 E
7 F
8 F
8 F
```
I want to do something else based on figuring out if for a value (x) of X there is a value of F in Y for all of the x's in the corresponding table. This means 7 doesn't cut it... | Try following query
```
select distinct X from temp
except
select X from temp where Y!='F' -- x,y columns, temp -> table
--Query select all distinct X which has all Y as F
```
Following is alternative query for the same
```
select distinct X from temp where not exists (select X from temp where Y='E')
``` | `Select * from mytable
where X not in ( Select X from mytable
Where Y <> 'F'
)` | SQL: Basic Query | [
"",
"sql",
"sql-server",
""
] |
I'm running a query on a MySQL database
```
SELECT * FROM t_college WHERE NAME="CEPT University"
```
Even though the entry `CEPT University` exists in column `name`, no match is found.
This is same for every other multi-word `varchar` entry in the database. If the value to be matched is a single word like `xyz`, it ... | You clearly have some whitespace characters (tabs, newlines, etc) other than space characters in your data.
The best approach usually to clean it up. To help debug the problem, use `HEX()`:
```
select HEX(name)
from t_college
```
This will show each character as a two hexadecimal characters in the range `00` to `FF`... | So maybe try to update this column to replace your current values with trimmed ones - use TRIM() function to remove trailing and leading spaces and then try to make this SELECT. | Why is SQL not matching anything? | [
"",
"mysql",
"sql",
"database",
""
] |
I have written a sql query
```
select a.unit_code unit,
a.gh_vill pl_vill,
a.gh_grow pl_grow,
(select gh_area
from w_cane_survey_2013 b
where b.croptype_code > 12 and a.gh_no = b.gh_no ) as paudha,
(select gh_area
from w_cane_survey_2013 b
where b.croptype... | try this query i hope it be helpful:
```
select unit_code as unit,
gh_vill as pl_vill,
gh_grow as pl_grow,
case when croptype_code > 12 then gh_area end as paudha,
case when croptype_code < 13 then gh_area end as pedi
from
w_cane_survey_2013
where
unit_code = '03' and gh_vill = '9991' and gh_grow = '1' ... | It's because the sub-query returned more than one rows. Add one more condition of ROWNUM=1 in the sub-query and try.
```
select
a.unit_code unit,
a.gh_vill pl_vill,
a.gh_grow pl_grow,
(select gh_area from w_cane_survey_2013 b
where b.croptype_code > 12 and a.gh_no = b.gh_no and ROWNUM=1) as ... | how to run such sql query. I am facing an error here ORA-01427 | [
"",
"sql",
"oracle",
""
] |
I have two tables `country` and `state`:
```
country
-----------
cid
countrycode
countryname
state
-------
sid
cid (fk)
statecode
statename
```
I am writing a join as:
```
SELECT s.sid,
s.statename,
c.countryname
FROM state s,
country c
WHERE s.cid = (+) c.cid
AND c.id = 1
```
... | No, MySQL does not accept the `+` symbol. Aside from a few exceptions, MySQL uses ANSI standard `JOIN` syntax:
```
SELECT s.sid,
s.statename,
c.countryname
FROM state s
LEFT JOIN country c
ON c.id = s.cid
WHERE c.id = 1
``` | Try this::
```
select
s.sid,
s.statename,
c.countryName
from country c
LEFT JOIN state s on s.cid = c.cid
WHERE c.id=1
``` | sql outer join shows the error in mysql workbench | [
"",
"mysql",
"sql",
"join",
""
] |
Anyone have any ideas? I get this error message in bash...
```
insert_code_sam.rb:31: syntax error, unexpected tIDENTIFIER, expecting ')'
"INSERT INTO index1 (name) VALUES ("test1");"
^
insert_code_sam.rb:32: syntax error, unexpected ')', expecting end-of-input
```
In ... | You are prematurely ending the string – your code is not valid Ruby syntax. [SQLite expects single quoted strings, anyway](http://www.sqlite.org/lang_expr.html). The solution is to use single quotes for the `VALUES`:
```
db.execute(
"INSERT INTO index1 (name) VALUES ('test1');"
)
``` | ```
db.execute(
"INSERT INTO index1 (name) VALUES ('test1');"
)
``` | Getting "syntax error, unexpected tIDENTIFIER..." when trying to insert rows into SQLite via Ruby | [
"",
"sql",
"ruby",
"sqlite",
""
] |
While writing a C# program I am trying to do a batch retrieval from a SQL database instead of getting each record one at a time. This way I get all the records in one DataSet and can just hit the server once. I have found that this method can be significantly faster. However I need to maintain the order. Does anyone ha... | The appropriate query to run would be:
```
SELECT [UserID], [LastName], [FirstName]
FROM [users]
WHERE [UserID] IN ('2024443', '2205659', '2025493')
ORDER BY [UserID]
```
Provided that you want to keep the order in the results for the `[UserID]` column.
**Edit after clarification on a very weird order the OP is look... | Does ORDER BY not work?
```
SELECT [UserID]
,[LastName]
,[FirstName]
FROM [users]
WHERE [UserID] = '2024443' OR [UserID] = '2205659' OR [UserID] = '2025493'
ORDER BY [UserID];
```
This will return the records you requested, sorted by UserID. | MySQL custom sorting | [
"",
"sql",
""
] |
I have two tables
**EVENTS**
```
EventCode EventDate
1 2013-07-22 04:00:00.000
2 2013-07-21 11:00:00.000
3 2013-07-21 10:00:00.000
```
**DeviceSignal** which is transaction table
```
TimeStamp DeviceID Value
2013-07-22 03:10:00.000 Dev1 33
201... | ```
SELECT
e.EventCode, e.EventDate,
d.TimeStamp, d.DeviceID, d.Value
FROM
DeviceSignal AS d
OUTER APPLY
( SELECT TOP (1) e.EventCode, e.EventDate
FROM Events AS e
WHERE d.TimeStamp <= e.EventDate
ORDER BY e.EventDate
) AS e ;
``` | I think this is what you're looking for:
```
SELECT
EV.EventCode,
EV.EventDate,
DS.Timestamp,
DS.DeviceID,
DS.Value
FROM
Events EV JOIN DeviceSignal DS
ON CAST(EV.EventDate AS DATE) = CAST(DS.TimeStamp AS DATE)
``` | SQL how can i select data between dates? | [
"",
"sql",
"t-sql",
""
] |
**My Query:**
```
SELECT source.name, file_info.*
from FILE_INFO
JOIN source
ON source.id = file_info.source_ID
where file_info.source_ID in
(select ID from Source where name like 'Donatello.%');
```
**My Tables:**
```
FILE_INFO
FILE_NAME | FILE_ID | SOURCE_ID | DATE_SEEN | CURRENT_STATUS
SOURCE... | What about the following ?
```
SELECT source.name, file_info.*
from FILE_INFO
JOIN source
ON source.id = file_info.source_ID and source.name like 'Donatello.%';
``` | Would this not be the same?
```
SELECT source.name, file_info.*
FROM FILE_INFO
JOIN source
ON source.id = file_info.source_ID
WHERE source.name like 'Donatello.%'
``` | WHERE claus after JOIN is slowing down my query | [
"",
"sql",
"oracle",
"join",
"where-clause",
""
] |
I need to display all fixtures(who plays 'against' who) for a current user so I wrote SQL query
```
SELECT
fixture.*
FROM
sport_team_player AS team_player, sport_team AS team
INNER JOIN sport_fixture AS fixture
ON (`team_player`.`team_id` = fixture.`team1_id` OR `team_player`.`team_id` = fixture.`team2_id`)
W... | Precedence of the comma operator is less than of INNER JOIN, CROSS JOIN, LEFT JOIN. That's why when you mix comma with other join table operators [Unknown column 'col\_name' in 'on clause'] error occur. Same query will work if you specify the cross join ( to get a Cartesian product of the first two tables) instead of c... | Try this one. Should result to the same query as yours;
```
SELECT fixture.*
FROM sport_team_player AS team_player
JOIN sport_team AS team
ON team_player.`team_id` = team.`team_id` AND team_player.`player_id` = '16'
INNER JOIN sport_fixture AS fixture
ON (`team_player`.`team_id` = fixture.`team1_id`
OR `t... | selecting from multiple tables vs JOIN | [
"",
"mysql",
"sql",
""
] |
I know that there are other questions with the exact title as the one I posted but each of them are very specific to the query or procedure they are referencing.
I manage a Blackboard Learn system here for a college and have direct database access. In short there is a stored procedure that is causing system headaches.... | I see a couple of potential errors that could be preventing the commit but without knowing more about the structure these are just guesses:
1. The update clause in the nested if is trying to update a column (or set of columns) that must be unique. Because the check only verifies that at least one item exists but does ... | Maybe you could use a MERGE statement :
<http://msdn.microsoft.com/fr-fr/library/bb510625%28v=sql.100%29.aspx>
I think it will be more efficient. | Current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I am currently working on a DataImport script, which is intended to move data from one database to another. The main problem I have come across is that the table in question contains a lot of duplicate records, with the duplicate fields being Product Code, Language, Legislation, Brand Name, Formula and Version, i.e we ... | You can already use a `common-table-expression` and `ROW_NUMBER` in SQL\_Server 2005:
```
WITH CTE AS
(
SELECT ProductCode, Language, Legislation, BrandName, Formula, Version,
RN = ROW_NUMBER()
OVER (
PARTITION BY productcode, language, legislation, brandname, formu... | You could use row\_number() over (partition by productcode, languageid, legislationid, brandName, versionnumber, formulaid order by productId desc )
and delete all producitids with row\_number > 1 | SQL Server 2005 - deleting duplicate records whilst maintaining the first one | [
"",
"sql",
"t-sql",
"sql-server-2005",
""
] |
How to get the "max" range of dates from multiple dateBegin and dateEnd ? My question is not well explained (cause im not english) but the example below will show you what I expect.
My database :

The output I'd like :
```
id_master beginDate ... | This is probably a lot more contrived than it has to be, and someone else can come up with a simpler answer, but you can try something like the following:
```
WITH ordered AS (
SELECT a.id_master, a.beginDate, a.endDate,
ROW_NUMBER() OVER(PARTITION BY id_master ORDER BY beginDate, endDate) AS rn
FROM Table1... | For others, here is the result of my current needs. On ***Informix 11.70*** and above has the same results this construction :
```
SELECT id_master , MIN(beginDate) AS beginDate, endDate FROM
LATERAL (
SELECT id_master, beginDate, MAX(endDate) AS endDate FROM
LATERAL (
SELECT id_master, beginDate, ... | SQL : Get range date from multiple begin and end date | [
"",
"sql",
"sql-server",
""
] |
Imagine I have a table (Mysql myISAM) with a child->parent relationship (categories and multiple levels of subcategories)
```
+--------+---------+
| id |parent_id|
+--------+---------+
| 1 | null |
| 2 | 1 |
| 3 | 2 |
| 4 | 7 |
| 5 | 1 |
| 6 | 5 |
+---... | ```
create table my_table(
id int,
parent_id int
);
insert into my_table values
(1,null),
(2,1),
(3,2),
(4,7),
(5,1),
(6,5);
```
This stored procedure will get you all the children of any given id
```
DELIMITER $$
DROP PROCEDURE IF EXISTS get_children$$
CREATE PROCEDURE get_children(IN V_KEY INT)
proc:
BEGIN
DECL... | Ok, so thanks to Deepak code, I managed to write this, a bit shorter readable, it accepts a table as parameter and returns also the depth of the element.
```
DELIMITER $$
CREATE PROCEDURE get_children(IN V_KEY INT,IN SOURCETABLE VARCHAR(255))
proc:
BEGIN
DECLARE vid text;
DECLARE count int;
DROP TABLE IF EXIST... | find out list of inverted hierarchy in mysql | [
"",
"mysql",
"sql",
"myisam",
""
] |
I have the followings tables on my database

There are several *project statuses* (waiting, working, finished, paid) and a project have to pass through all the status from waiting to paid.
In order to keep complete track of the project, each status are kept, so ... | ```
select p.* from projects p
left join projects_status_projects psp on (psp.project_id = p.id)
where created_at = (select max(created_at)
from projects_status_projects where
project_id = p.id)
```
sqlfiddle with some example here: <http://sqlfiddle.com/#!2/725fcc/7/0> | If you just need the current status of the project
Try this::
```
Select DITINCT(p.id),p.*
from projects p
left join projects_status_projects psp on psp.project_id = p.id
where project_status_id = XX
order by created_at desc
``` | Join query by date and primary | [
"",
"mysql",
"sql",
""
] |
I have a booking table with 6 columns called booked\_start, booked\_stop, used\_start, used\_stop, invoice\_start, invoice\_stop. The values are floats. I want to get a sum of the rows that has values above 0 but i also want it to calculate say used\_stop - used\_start.
Currently im working with this:
```
SELECT
... | This should work:
```
SELECT
room,
SUM(
CASE WHEN booked_stop_time - booked_start_time > 0
THEN booked_stop_time - booked_start_time
END
) AS booked,
SUM(
CASE WHEN used_stop_time - used_start_time > 0
THEN used_stop_time - used_start_time
END
) AS used,
SUM(
CASE WHEN i... | You can do it like this:
```
SELECT
room,
SUM(IF( booked_stop_time > 0, booked_stop_time - booked_start_time, 0 )) as booked,
SUM(IF( used_stop_time > 0, used_stop_time - used_start_time, 0 )) as used,
SUM(IF( invoice_stop_time > 0, invoice_stop_time - invoice_start_time, 0 )) as invoice
FROM bookings
... | Calculate multiple values with sql with if expression | [
"",
"mysql",
"sql",
"math",
""
] |
Good Day Every one
i have this code
```
SELECT
'Expired Item -'+ DateName(mm,DATEADD(MM,4,AE.LOAN)) as [Month]
,COUNT(ISNULL(PIT.ID,0))'COUNT'
,SUM(ISNULL(PIT.KGRAM,0))'GRAMS'
,SUM(ISNULL(PH.AMOUNT,0))'PRINCIPAL'
FROM #AllExpired AE
INNER JOIN Transactions.ITEM PIT
ON AE.MAINID=PIT.MAINID
... | Edited: Added a months table to handle empty temp tables.
Change inner joins to left joins.
```
DECLARE @months TABLE (ReportMonth VARCHAR(20) NOT NULL)
INSERT INTO @months VALUES
('January'),('February'),('March'),('April'),
('May'),('June'),('July'),('August'),
('September'),('October'),('November'),('December')
... | Try this in your select
```
SELECT (CASE WHEN (AE.fld_LoanDate IS null) THEN 0 ELSE AE.fld_LoanDate END) as fld_LoanDate
``` | Generate Zeroes when no rows where selected | [
"",
"sql",
"t-sql",
"reporting-services",
"sql-server-2008-r2",
"isnull",
""
] |
I've following table **stuinfo**
```
+------------+-------+-----------+
| Roll_no | Name | Lastname |
+------------+-------+-----------+
| 37032 | johny | bravo |
| 37034 | sam | smith |
+------------+-------+-----------+
```
and second one **stu\_attendace**
```
+------------+-------+------... | You can easily do what you want, in the `SELECT` clause you can select a literal value, or a column name, or any valid expression.
Just `JOIN` the two tables, and then calculate the percent like this:
```
SELECT
i.roll_no,
i.name,
i.Lastname,
((a.month / 26) * 100) AS percent
FROM stuinfo AS i
INNER JOIN stu... | Try this
```
select a.roll_no , a.name ,a.last_name,(b.month/26)*100 as per_attendace
from stuinfo as a join
stu_attendace as b on a.roll_no=b.roll_no
``` | how to show virtual column with calculated runtime values(i.e not in database) in mysql? | [
"",
"mysql",
"sql",
""
] |
Is there any way to optionally update any of a number of fields in an SQL statement? I can only get so far as something like:
```
UPDATE Customer SET
ContactName = ? <=== what to do here if ? is null???
, CompanyName = ? <=== what to do here if ? is null???
, AddressId = ? <=== what to do here if ? is nu... | Not entirely clear on your goal, but I think you're looking for the [coalesce](https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce) feature; it will return the first non-null value:
> mysql> SELECT COALESCE(NULL,1); -> 1
>
> mysql> SELECT COALESCE(NULL,NULL,NULL); -> NULL
So you can se... | Usually you would want to use the existing value if the parameter is null in an update:
```
UPDATE Customer SET
ContactName = COALESCE(?,ContactName)
``` | Update any of a number of fields in an SQL statement | [
"",
"mysql",
"sql",
""
] |
A salary table is given and we need to write a single query which prints the cumulative salary of employees.
For Example:
```
Emp Sal
A 10
B 15
C 20
D 5
OutPut:
Emp Sal Cum_Sal
A 10 10
B 15 25
C 20 45
D 5 50
``` | in some RDBMS (like PostgreSQL or SQL Server 2012 or Oracle) it's possible to use window function:
```
select
Emp, Sal, sum(Sal) over(order by Emp) as Cum_Sal
from employees
```
if it's not possible, you can use self-join
```
select
e1.Emp, e1.Sal, sum(e2.Sal) as Cum_Sal
from employees e1
inner join empl... | For MS SQL please try this:
```
select NAME,SAL,sum(SAL)
over(order by SAL rows between unbounded preceding and current row) as cum_sal
from employee
``` | What query should I write to calculate the cumulative salary of employees from the salary table | [
"",
"sql",
"oracle",
"oracle9i",
""
] |
While reading data of sql server from gridview ,the date column adds an extra 12:00:00 AM to the end of the date.
eg:9/29/2013 12:00:00 AM
In the gridview it shows this way, but i only have a **date** type date saved in the sql table.
I need that to be only 9/29/2013.
same thing happened while reading and displayin... | Here's an example of a bound field.
```
<asp:BoundField DataField="TheDateField" HeaderText="HeaderText"
DataFormatString="{0:MM-dd-yyyy}" />
```
All you should have to do is add DataFormatString="{0:MM-dd-yyyy}" to your bound field. | To format a DATETIME value in a GridView, you can do it like this:
DataFormatString="{0:MM-dd-yyyy}". | Reading date from sql date format adds extra 12:00:00 AM? | [
"",
"asp.net",
"sql",
"sql-server",
"gridview",
""
] |
Im trying to write a select query in pgSQL that shows items that are priced at more than `100,000` and less than or equal to `200,000`. I realise there is a `BETWEEN` function but that isn't exactly what I want.
What I have so far:
```
SELECT id FROM Item WHERE (Price = >100000 AND Price = <=200000);
```
Apologies f... | You have problems with your `<=` and `>=` conditions. the `=` is always last and only occurs once.
```
SELECT id FROM Item WHERE Price >=100000 AND Price <=200000;
``` | You have two choices:
```
SELECT id
FROM Item
WHERE Price > 100000
AND Price <= 200000
```
Or use the inclusive BETWEEN with an adjusted lower bound:
```
SELECT id
FROM Item
WHERE Price BETWEEN 100001 AND 200000
``` | BASIC SQL How To Select Greater than 100000 and less than 200000 | [
"",
"sql",
"postgresql",
""
] |
I am trying to create a high score board for a video game.
There is a `users` table:

And a `scores` table:

I have tried using this query:
```
SELECT MAX(`scores`.`score`) AS ma... | ```
SELECT scores.score, scores.team, users.name
FROM users
JOIN scores
ON users.id = scores.user_id
WHERE NOT EXISTS
(SELECT *
FROM scores scores2
WHERE scores2.score > scores.score
AND scores2.user_id = users.id)
``` | [SQL Fiddle](http://sqlfiddle.com/#!2/1b5efe/8)
**MySQL 5.5.32 Schema Setup**:
```
CREATE TABLE users
(`id` int, `name` varchar(8), `pass` varchar(4))
;
INSERT INTO users
(`id`, `name`, `pass`)
VALUES
(2, 'JAKE', 'jake'),
(3, NULL, NULL),
(4, 'AWNO', 'ffff'),
(5, 'FFF', 'ffff'),
(6, 'AS... | Selecting Rows Based on Max Column in Group By | [
"",
"mysql",
"sql",
""
] |
I have this code in my select statement
```
ISNULL(a.PolicySignedDateTime,aq.Amount) AS 'Signed Premium',
```
But I want to see if "a.PolicySignedDateTime" is not null.
Is there a easy function to do this which does not involve using a "if" statement?
Cheers guys | You have to use `CASE`
```
SELECT CASE WHEN Field IS NOT NULL
THEN 'something'
ELSE 'something else'
END
``` | I know is late but just in case someone else viewing this and using MSSQL 2012 or above you could use 'IIF' statement.
I guess OP don't want to use 'IF' clausule cause is "too much code syntax" to acomplish simple stuff.
An alternative also cleaner than 'IF' statement is 'IIF'. Is just an inline 'IF' simplification.
... | Is there a opposite function to ISNULL in sql server? To do Is not null? | [
"",
"sql",
"sql-server",
"isnull",
""
] |
Is there a value or command like DATETIME that I can use in a manual query to insert the current date and time?
```
INSERT INTO servers (
server_name, online_status, exchange, disk_space, network_shares
) VALUES(
'm1', 'ONLINE', 'ONLINE', '100GB', 'ONLINE' 'DATETIME'
)
```
The quoted DATETIME value at the end is... | You can use `NOW()`:
```
INSERT INTO servers (server_name, online_status, exchange, disk_space, network_shares, c_time)
VALUES('m1', 'ONLINE', 'exchange', 'disk_space', 'network_shares', NOW())
``` | Use **CURRENT\_TIMESTAMP()** or **now()**
Like
```
INSERT INTO servers (server_name, online_status, exchange, disk_space,
network_shares,date_time) VALUES('m1','ONLINE','ONLINE','100GB','ONLINE',now() )
```
or
```
INSERT INTO servers (server_name, online_status, exchange, disk_space,
network_shares,date_time) VALUE... | How to get current date & time in MySQL? | [
"",
"mysql",
"sql",
"datetime",
""
] |
I have table containing one datetime column. I need to return rows for only last 6 months. This can be done by
```
where datetime_column > DATEADD(m, -6, current_timestamp)
```
But how to extend this option if I want to return latest month beginning with first day of the month? E.g. I run this condition in the middle... | For MS SQL Server, you can use:
```
where datetime_column >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6,
current_timestamp)), 0)
``` | ## In SQL Server
```
where datetime_column > dateadd(m, -6, getdate() - datepart(d, getdate()) + 1)
```
### [SQLFiddle demo](http://sqlfiddle.com/#!3/d41d8/22330)
## In MySQL
```
where datetime_column > curdate() - interval (dayofmonth(curdate()) - 1) day - interval 6 month
```
### [SQLFiddle demo](http://sqlfiddl... | SQL Last 6 Months | [
"",
"sql",
"sql-server",
""
] |
I want a query that returns the number of sequential match of words in two strings
example:
Table
```
Id column1 column2 result
1 'foo bar live' 'foo bar' 2
2 'foo live tele' 'foo tele' 1
3 'bar foo live' 'foo bar live' 0
```
to get total number of occu... | Personally, in this situation, I would choose PL/SQL code over plain SQL. Something like:
Package specification:
```
create or replace package PKG is
function NumOfSeqWords(
p_str1 in varchar2,
p_str2 in varchar2
) return number;
end;
```
Package body:
```
create or replace package body PKG is
functio... | Why to give up on the query approach. I know it's a bit complicated and I hope someone can work on it to improve it, but working on this during my spare time I was able to survive a an afternoon of calls...
Here on [SQLFidlle](http://sqlfiddle.com/#!4/2c047/61)
```
SELECT Table1.id,
Table1.column1,
Tabl... | Count sequential matching words in two strings oracle | [
"",
"sql",
"oracle",
"stored-procedures",
""
] |
I've written the below query :
```
SELECT DateTime, configId, rowId
FROM linkedTableDefinition a,
INNER JOIN tableDefinition b,
ON a.Target = b.Id
INNER JOIN ViewWithInfo c,
ON a.Target = c.Id
```
This gives the following output:
```
DateTime configId rowId
12-09-2013 11:00 4 12
12-09-2013... | ```
SELECT *
FROM
(
SELECT DateTime, configId, rowId,
ROW_NUMBER() OVER(PARTITION BY configId, rowId ORDER BY DateTime DESC) AS RowNum
FROM linkedTableDefinition a
INNER JOIN tableDefinition b ON a.Target = b.Id
INNER JOIN ViewWithInfo c ON a.Target = c.Id
) src
WHERE src.RowNum = 1
``` | You could do this, substituting proper joining fields as appropriate:
```
SELECT testResults.ResultDate, testResults.ConfigurationId, testResults.TestCaseId,
(SELECT MAX(ResultDate) FROM dbo.TestResultView WHERE TestCaseId = testResults.TestCaseId AND ConfigurationId = testResults.ConfigurationId) AS MaxDate
FROM ... | SQL max(DateTime) and category filter without group by | [
"",
"sql",
"sql-server",
""
] |
I have the following SQL code in a stored procedure:
```
CREATE PROCEDURE sp_createAColDiffTable (@table_name nvarchar(128))
AS
CREATE TABLE @table_name (
[table_name] VARCHAR (128) NOT NULL,
[column_name] VARCHAR (128) NULL,
[what_changed] VARCHAR (128) NULL,
[sr_data_type] VARCHAR (128) NOT NUL... | You would need to use dynamic SQL for this, as `CREATE TABLE` doesn't take a variable name.
e.g.
```
CREATE PROCEDURE sp_createAColDiffTable (@table_name nvarchar(128))
AS
DECLARE @sql nvarchar(MAX)
SET @sql = 'CREATE TABLE ' + @table_name + ' (
[table_name] VARCHAR (128) NOT NULL,
[column_name] VARC... | `@table_name` is used when declaring table variables, whereas `table_name` or `#table_name` or `##table_name` is used to create tables/temp tables.
So you would have
```
DECLARE @table TABLE (
ID INT,
....
```
and
```
CREATE TABLE #table_name (
ID INT,
....
```
If you wish to create a table dynamic... | using parameter values in stored procedures | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I am working in SQL Server 2012. My date column in a data set looks like this: `41547`. The column is in `nvarchar (255)`. I want to convert it to something like this: `yyyy-mm-dd hh:mm:ss` (Example: `2013-09-14 12:23:23.98933090`). But I can not do this. I am using following code:
```
select convert(datetime, date_co... | I have just found the way to do this.
First I have to covert the nvarchar to int then I have to convert it to date time. I have used following code:
```
Select convert(datetime, (convert (int, [date_column])), 6) as 'convertedDateTime' from mytable
``` | Your date is actually a numeric value (float or integer), stored in a char column. So, you need to convert it to a numerical value (in this case, to `float`) first, like:
```
select convert(datetime, CONVERT(float,date_column))
```
A value of `41547.5` will result in:
```
`2013-10-02 12:00:00`
```
The style argumen... | Converting a numeric value to date time | [
"",
"sql",
"sql-server",
"date",
"sql-server-2012",
"type-conversion",
""
] |
I currently have the following results:
```
ID Location
1 NYC
1 LA
2 NYC
3 PIT
```
and I'd like the following:
```
ID Location
1 Multiple
2 NYC
3 PIT
```
Does anyone know an easy way to accomplish this? | Here's one way to do it using `case` with `count` and `distinct`:
```
select distinct id,
case when count(location) over (partition by id ) > 1
then 'Multiple' else location end Location
from yourtable
```
* [SQL Fiddle Demo](http://sqlfiddle.com/#!3/bdc51/1) | With `sub-query`, `COUNT`, `CASE`, `GROUP BY`:
```
SELECT mm.id, CASE WHEN mm.count > 1 THEN 'Multiple' ELSE loc END As Location
FROM
(SELECT COUNT(id) As count, id, MAX(location) As loc
FROM myTable
GROUP BY id) As mm;
```
[**SQL Fiddle**](http://sqlfiddle.com/#!3/63c6a/14) | Select From Table with Multiple Rows for some ID's, with an identifier value | [
"",
"sql",
"sql-server",
""
] |
How can i query a column with `Names` of people to get only the names those contain **exactly 2** `“a”` ?
I am familiar with `%` symbol that's used with `LIKE` but that finds all names even with 1 `a` , when i write `%a` , but i need to find only those have **exactly** 2 characters.
Please explain - Thanks in advance... | Use `'_a'`. `'_'` is a single character wildcard where `'%'` matches 0 or more characters.
If you need more advanced matches, use regular expressions, using `REGEXP_LIKE`. See [Using Regular Expressions With Oracle Database](http://docs.oracle.com/cd/B12037_01/appdev.101/b10795/adfns_re.htm).
And of course you can us... | Assuming you're asking for two `a` characters search for a string with two a's but not with three.
```
select *
from people
where names like '%a%a%'
and name not like '%a%a%a%'
``` | Matching exactly 2 characters in string - SQL | [
"",
"sql",
"oracle",
""
] |
This sql is valid:
```
WITH A AS
(SELECT TOP 1000 *
FROM dbo.SomeTable)
SELECT * FROM A
```
While this one gives an error(*Incorrect syntax near the keyword 'DECLARE'*):
```
WITH A AS
(SELECT TOP 1000 *
FROM dbo.SomeTable)
DECLARE @dt DATETIME
SET @dt = GETDATE()
SELECT * FROM A
PRINT DATEDIFF(SS,GE... | Just do
```
DECLARE @dt DATETIME;
SET @dt = GETDATE();
WITH A
AS (SELECT TOP 1000 *
FROM dbo.SomeTable)
SELECT *
FROM A;
PRINT DATEDIFF(SS, GETDATE(), @dt);
```
The only valid thing following a CTE definition is a single statement using it | A CTE must be followed by a single SELECT, INSERT, UPDATE, or DELETE statement that references some or all the CTE columns. A CTE can also be specified in a CREATE VIEW statement as part of the defining SELECT statement of the view.
<http://msdn.microsoft.com/en-us/library/ms175972.aspx> | Cant define SQL variable when using WITH statement | [
"",
"sql",
"sql-server",
"sql-server-2008",
"common-table-expression",
""
] |
Is it posible to use *case* in *where in* clause?
Something like this:
```
DECLARE @Status VARCHAR(50);
SET @Status='published';
SELECT * FROM Product P
WHERE P.Status IN (CASE WHEN @Status='published' THEN (1,3)
WHEN @Status='standby' THEN (2,5,9,6)
... | No you can't use `case` and `in` like this. But you can do
```
SELECT * FROM Product P
WHERE @Status='published' and P.Status IN (1,3)
or @Status='standby' and P.Status IN (2,5,9,6)
or @Status='deleted' and P.Status IN (4,5,8,10)
or P.Status IN (1,3)
```
BTW you can reduce that to
```
SELECT * FROM Product P ... | I realize this has been answered, but there is a slight issue with the accepted solution. It will return false positives. Easy to fix:
```
SELECT * FROM Products P
WHERE (@Status='published' and P.Status IN (1,3))
or (@Status='standby' and P.Status IN (2,5,9,6))
or (@Status='deleted' and P.Status IN (4,5,8,... | SQL use CASE statement in WHERE IN clause | [
"",
"sql",
"select",
"switch-statement",
"case",
"where-in",
""
] |
I have a problem when I need range from 10 to 20 (LIMIT 10, 20) it is returns everything from 1 to 20. I don't have any idea why it's works so.
Here is a query:
```
SELECT *
FROM table
LIMIT 10, 20
```
This table has 5 foreign keys, can it be a reason? | The limit syntax is `LIMIT offset, rowcount`. So you're asking for 20 rows, starting with the 10th. You probably want `LIMIT 10, 10`. | The limit command works as follows:
<http://php.about.com/od/mysqlcommands/g/Limit_sql.htm>
Your query should be:
`SELECT *
FROM table
LIMIT 10,10`
the first number indicates which record to start from, and the second indicates the amount of records to limit to. | LIMIT does not work correctly | [
"",
"mysql",
"sql",
"limit",
""
] |
It's Tuesday today.
How come when I run this SQL statement, it says it's not Tuesday?
```
SELECT
CASE
WHEN TO_CHAR(sysdate, 'Day') = 'Tuesday' THEN 'Its Tuesday'
ELSE 'Its Not Tuesday'
END AS case_result,
TO_CHAR(sysdate, 'Day') AS day
FROM DUAL
```
Returns:
```
CASE_RESULT DAY
It's Not Tuesday Tuesday
``` | Try like this,
```
SELECT CASE
WHEN trim(TO_CHAR(SYSDATE, 'Day')) = 'Tuesday' THEN 'Its Tuesday'
ELSE 'Its Not Tuesday'
END AS case_result,
TO_CHAR(SYSDATE, 'Day') AS DAY
FROM DUAL;
```
OR as ajmalmhd04 suggested, you can try with `FmDay` like,
```
SELECT CASE
WHEN TO_CHAR(SYS... | The value of to\_char(sysdate,'day') is actually 'tuesday ', with two space after tuesday. Oracle pads the value to the length of the longest day, which is wednesday, which is nine characters.
try
```
RTRIM(to_char(sysdate,'day'))
``` | Oracle - get day of week | [
"",
"sql",
"oracle",
""
] |
Hi I have a query that i want to return one value. If i run the query in two parts and add them together it is fine but when i try and the OR operator the value greatly increases.
Here is the first query:
```
select count (*) from tablename where DATE_TRE='2013-10-06' and SECTOR= '1'
```
This returns 3867
Here ... | I think it because it evaluates it like this
```
select count (*)
from tablename
where (DATE_TRE='2013-10-06' and SECTOR= '1') OR SECTOR = '01'
```
When you are looking for this(Try this one)
```
select count (*)
from tablename
where DATE_TRE='2013-10-06' and (SECTOR= '1' OR SECTOR = '01')
``` | `and` binds stronger than `or`. use parentheses
```
select count (*)
from tablename
where DATE_TRE = '2013-10-06'
and (SECTOR= '1' OR SECTOR = '01')
```
or
```
select count (*)
from tablename
where DATE_TRE = '2013-10-06'
and SECTOR in ('1', '01')
``` | Using Count and OR giving too high a value | [
"",
"sql",
"count",
"sybase",
""
] |
Hi im working on a query to get 1row for each product but the problem is that there are multiple records with propertys of 1 product.
**TABLE PRODUCTS\_DATA**
```
NAME : DESC. | ID|FIELD1|FIELD2|FIELD3|FIELD4|
Row 1:PRODUCT1 | 1 | 200 | high | | |
Row 2:PRODUCT1 | 2 | 10 | | low | |
Row 3:P... | I think you will get your solution now dear...
```
SELECT
SS.[DESC],
(SELECT '|' + US.FIELD1
FROM XYZ US
WHERE US.[DESC] = SS.[DESC]
FOR XML PATH('')) [FIELD1],
(SELECT '|' + US.FIELD2
FROM XYZ US
WHERE US.[DESC] = SS.[DESC]
FOR XML PATH('')) [FIELD2],
(SELECT '|' + US.FIELD3... | You need to be careful about the semantics of the two "field1" columns. You are showing both coming out in your example result. Presumably you could end up with data in each of the four fields for each row and therefore a very variable length result with duplicate column names, which seems broken to me. (Or you need to... | sql query to get multiple records in one row | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
```
SELECT dbo.Team.ID, dbo.Team.Comment, dbo.Team.Date, dbo.TeamName.Name, dbo.Contacts.ContactName
FROM dbo.Team
INNER JOIN dbo.TeamName ON dbo.Team.ID = dbo.TeamName.id
INNER JOIN dbo.Contacts ON dbo.Team.ContactID = dbo.Contacts.ContactID
WHERE dbo.TeamName.idstatus = 'Active'
```
I am trying ... | ```
SELECT dbo.Team.ID, dbo.Team.Comment, MAX(dbo.Team.Date) LatestDate, dbo.TeamName.Name, dbo.Contacts.ContactName
FROM dbo.Team
INNER JOIN dbo.TeamName ON dbo.Team.ID = dbo.TeamName.id
INNER JOIN dbo.Contacts ON dbo.Team.ContactID = dbo.Contacts.ContactID
WHERE dbo.TeamName.idstatus = 'Active'
G... | I'm assuming you want to filter by `dbo.Team.Date`.
Change your `WHERE` clause to:
```
WHERE (dbo.TeamName.idstatus = 'Active')
and (dbo.Team.Date=(select max(Date) from dbo.Team))
``` | Select Most Recent date | [
"",
"sql",
"sql-server",
""
] |
I am having an issue writing an SQL Update statement, where I need to update a not null field with an empty string.
```
UPDATE channel_mgmt.channels
SET registered_address_id=p_address_id
,vendor_id=p_spc_code
WHERE id=v_channel_id;
```
In this case, p\_spc\_code, can be set to '', and I am running i... | Have you tried using `' '` (string with one space in it)? If varchar, than I believe comparisons (for most cases, i.e. you're not specifying to compare white chars) work as expected.
What I mean that `' ' = ' '` (single and double whitespace) should evaluate to `true` for `varchar` fields.
(I don't have an instance o... | If there is a `NOT NULL` constraint defined on a column you cannot update the table by specifying `null` or zero length string(`''`) as a new value for a column. Oracle treats zero length string(`''` when assigned to a `varchar2` column or variable) as `NULL`, so from the *oracle's point of view*, these two statements ... | Oracle SQL Updating a NOT NULL column with an empty string | [
"",
"sql",
"oracle",
""
] |
I need to create a SQL script to determine if a sequence exists in a SQL Server 2012 database. I am familiar with process for determine if a stored procedure exist but not sequence. Thank you. | The script to determine whether or not a Sequence exists in SQL Server 2012 is very similar to checking for Stored Procedures. Consider the following code that checks to see if a Stored Procedure exists:
```
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[SProc_Name]') AND type IN (N'P', N'PC')
```
The... | By checking data in [sys.sequences](http://technet.microsoft.com/ru-ru/library/ff877934.aspx) table:
```
select *
from sys.sequences
where object_id = object_id('schema_name.sequence_name')
```
actually that if you're sure that there's no object other than sequence with name equals `'schema_name.sequence_name'`, you ... | How can I determine if a Sequence exist in SQL Server 2012? | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have the data in table EMP\_DETAILS
```
EMPLOYEE_NUMBER ROLE
NSA5421 CONTRACTOR
NSA390 CONTRACTOR
E8923 EMPLOYEE
E2390 EMPLOYEE
```
I would like to have zero displayed even there are no records, I tried the following but it didn't get the desired result
... | Please try:
```
select
NVL(y."ROLE", '0') "ROLE",
case when y."ROLE" is null then 0 else COUNT(*) end cnt
from(
SELECT 'E3400' employee_number from dual
)x left join emp_details y on x.employee_number=y.employee_number
group by "ROLE"
``` | Your inner query is returning nothing rather than null values.
```
SELECT COUNT (*) cnt, role
FROM emp_details
WHERE employee_number = 'E3400'
GROUP BY role
```
Use EXISTS clause | Fetch zero if even there are no matching records | [
"",
"sql",
"oracle",
"oracle10g",
""
] |
We have one 'master' table and three other tables with some kind of details like below.
```
+----------+
| TAB_A |
+----------+
*|PK ID_A |
+----------+ / |FK ID_MAIN|
|TableMain |/ | DATA_A |
------------ ============
|PK ID_MAIN| +-------... | Since you want to put values from different tables on the same row, you need to relate them to one another somehow. In the absence of an actual relationship, you probably have to make one up. One suggestion would be to assign row numbers per `ID_MAIN` in the three subordinate tables and use those numbers for matching.
... | Hi Please try this hope this helps you thanks
```
SELECT dbo.TableMail.ID_MAIN, dbo.TableMail.Main_Data,
CASE WHEN DATA_A IS NULL THEN '' ELSE DATA_A END AS DATA_A,
CASE WHEN DATA_B IS NULL THEN '' ELSE DATA_B END AS DATA_B,
CASE WHEN DATA_C IS NULL THEN '' ELSE DATA_C END AS... | How can I merge three tables by id from 4th table? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Here is the database description:
> Company(ID\_comp, name)
>
> Trip(trip\_no, id\_comp, plane, town\_from, town\_to, time\_out, time\_in)
>
> Passenger(ID\_psg, name)
>
> Pass\_in\_trip(trip\_no, date, ID\_psg, place)
* Company table has ID and name of the company, which transports passengers.
* Trip table has infor... | ```
SELECT
p.name
FROM
passenger AS p
JOIN
pass_in_trip AS pt
ON p.id_psg = pt.id_psg
GROUP BY
p.id_psg, p.pame
HAVING
COUNT(DISTINCT pt.place) < COUNT(*) ;
``` | ```
select name, place, COUNT(name)as "no of trips"
from Passenger p
join Pass_in_trip pt
on p.ID_psg=pt.ID_psg join Trip t
on pt.trip_no=t.trip_no
group by name, place
having count(name) > 1
``` | Tricky SQL Exercise | [
"",
"sql",
"postgresql",
"subquery",
""
] |
Is there any concept in mysql to localize the Date time function. I need Date time to be in Ethiopian format. Or atleast a mysql conversion function that displays datetime with respect to Ethiopian Date time. | No, you can not. In MySQL, [proleptic Gregorian calendar](http://dev.mysql.com/doc/refman/5.0/en/mysql-calendar.html) is used - and there are no other formats. That means there are no *native* ways to produce such conversions.
However, you can create your own output conversion. To do this, you will need to know both c... | MySQL does not a conversion function for ethiopic calendar.
The most straightforward approach would be to create a date table that contains gregorian date on one column and ethiopian on the next, allowing you to easily join it on a standard date to get your ethiopian date. | Does Mysql support Ethiopian calendar/ Ethiopian date time | [
"",
"mysql",
"sql",
""
] |
I have a sql query that joins a few tables by `user_id`, the problem is is that I would like to see all the data from these tables.
At the moment I am querying the user table and the payment table and joining them based on the `user_id`.
I seem to only getting one result per user\_id, now I know this it what is meant... | I find no flaws in your query. It should be working as expected.
I'm suspecting there is no more than one row *per user* in the `subscription` and `detail` tables. That's why your `left join` produces exactly one row per user (if it was an inner join, it would produce *at most* one row per user). | I suggest using another method:
```
select
'your selected columns'
from
user u,
u_subscription us,
u_detail ud
where
u.user_id = us.user_id and
u.user_id = ud.user_id
```
this works just like the join method but for me, this method makes the query cleaner and easier to understand.. hope it helped! | Having SQL Query not group results | [
"",
"mysql",
"sql",
"join",
""
] |
Please check fiddle: [myFiddle](http://sqlfiddle.com/#!3/184dc/1)
Query:
```
create table Emp(empId int primary key, EmpName varchar(50),MngrID int)
insert into Emp(empId,EmpName,MngrID)values(1,'A',2)
insert into Emp(empId,EmpName,MngrID)values(2,'B',null)
```
A has mngr B but A has no mngr, so while fetching the ... | For some reason it doesn't work in SQLFiddle, but i ran it in my own instance of SQL Server to verify it does work:
```
SELECT e1.EmpID, e1.EmpName, e2.EmpName
FROM emp e1 LEFT OUTER JOIN emp e2
ON e1.MngrID = e2.EmpID
```
Basically, you're doing a 'self join' by declaring two instances of the table (e1 and e2), a... | You need to LEFT JOIN table to itself:
```
select A.empID, A.empName, b.empName as mgrName
from emp A left join emp B on A.mngrID = b.empID
```
<http://sqlfiddle.com/#!3/184dc/8> | SQL Server fetch alias name for query | [
"",
"sql",
"sql-server-2008",
""
] |
I'm trying to show rows in which one field occurs a certain number of times. Assuming the following table: `Campaign`
```
+------------+-------------+--------------+---------------+
| account_id | campaign_id | account_name | account_users |
+------------+-------------+--------------+---------------+
| 85 ... | Give this a try:
```
SELECT DISTINCT c.*, a.account_code FROM campaign c
JOIN account a ON c.account_id = a.account_id
WHERE c.account_id IN (
SELECT account_id FROM campaign
GROUP BY account_id
HAVING count(*) >= 2
)
``` | You are using COUNT as aggregate function. Try using it as analytical function.
```
select account_id ,campaign_id ,account_name ,account_users ,account_code,
from
(SELECT c.account_id ,c.campaign_id ,c.account_name ,c.account_users ,a.account_code,
count(1) over (partition by c.account_id) as c
FROM campaign... | Show rows that have values occur a certain number of times | [
"",
"sql",
"oracle",
""
] |
I am updating the table with values from multiple tables.
```
UPDATE pv SET
pv.[TotalDInTCG] = Dr.TCGDCnt
,pv.[AvgHbA1cImprovement] = hsd.AvgHbA1cCnt
,pv.[TotalCHDInTCG] = cpc.CHdCnt
,pv.[TotalCHDNTCG] = cpd1.CHdWithCholBPCnt
,pv.[PercentageOfCHDWithBPChol] =... | Assuming that the columns you are updating in `pv` are all nullable this should ensure you capture all the relevant data:
```
UPDATE pv SET
pv.[TotalDInTCG] = Dr.TCGDCnt
,pv.[AvgHbA1cImprovement] = hsd.AvgHbA1cCnt
,pv.[TotalCHDInTCG] = cpc.CHdCnt
,pv.[TotalCHDNTCG] = cpd1.CHdWithCholBPC... | Left outer join worked.. The main issue was due to normal behavior of INNER JOIN | Update table by selecting values from multiple tables sql | [
"",
"sql",
""
] |
I need to calculate the averages of a couple of columns which range from 0 to 5. However I want to exclude the zero's from the AVG calculation.
So I have something like
```
SELECT AVG(column1), AVG(column2), AVG(column3) FROM table1
WHERE ???
``` | AVG() only counts records that are non-null.
NULLIF() will return null, when the value matches the 2nd parameter.
```
SELECT AVG(NULLIF(column1,0)), AVG(NULLIF(column2,0)), AVG(NULLIF(column3,0)) FROM table
WHERE ????
```
You could create a more complex AVG() by using IF(column1 IN (x,y,z), column1, NULL) within.
... | You can do something like this, where you sum the colummn and divide by the count of rows where the value is not equal to zero:
```
SELECT SUM(Column1) / SUM (IF(Column1 = 0, 0, 1)),
SUM(Column2) / SUM (IF(Column2 = 0, 0, 1)),
SUM(Column3) / SUM (IF(Column3 = 0, 0, 1))
FROM table1
```
Not you will also have to trap d... | Aggregate queries remove zeros | [
"",
"mysql",
"sql",
"average",
""
] |
I have following DB structure:

I wanted it in single column like:
```
Param
-
-
AccountNo
AccountNo DueDate
```
For this i written case when query:
```
select
case when Param1 <>'' then 'Param1'+Param1
+case when Param2 <>'' then 'Param2'+Par... | If you indent it some you get (I've kept the first only the first three params)
```
select case when Param1 <>''
then 'Param1'+Param1 + case when Param2 <>''
then 'Param2'+Param2 +case when Param3 <>''
... | You can use `NullIf()` function with `IsNull()/Coalesce()` like below:
```
Select coalesce(nullif(param1,''),'') + coalesce(nullif(param2,''),'') + ... +
coalesce(nullif(param5,''),'') newColName
From yourTable
```
For *your case* just a null check like below may be enough:
```
Select coalesce(param1,'') + c... | case when blank check returning null | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I have a query, that should return all records in T1 that not linked to records in T2:
```
SELECT DISTINCT fldID, fldValue FROM T1
WHERE NOT EXISTS
(
SELECT T1.fldID, T1.fldValue
FROM T2
JOIN T1 ON T2.fldID = T1.fldPtr
)
```
But it returns empty set -- should be one record.
If I use query like this (... | You can also use [`EXCEPT`](http://technet.microsoft.com/en-us/library/ms188055.aspx) for this:
```
SELECT DISTINCT fldID, fldValue FROM T1
EXCEPT
SELECT T1.fldID, T1.fldValue
FROM T2
JOIN T1 ON T2.fldID = T1.fldPtr
``` | A more efficient and elegant query that will work with every database is:
```
SELECT T1.*
FROM T1
LEFT JOIN T2
ON T2.fldID = T1.fldPtr
AND T2.flrValue = T1.flrValue
WHERE T2.fldID IS NULL
```
The LEFT JOIN attempts to match using both criteria, then the WHERE clause filters the joins, and only non-joins have ... | WHERE + NOT EXIST + 2 Columns | [
"",
"sql",
"sql-server",
""
] |
```
492953BI -2284424
492953BI -2014941
492953BI -1916038
492953BI -1908036
```
I need to split the first coloumn (ID) into two coloumns. (ie. Have the numbers in first coloumn, and BI in the second.) Am battling to do this on SQL Server. Am also new to SQL so battling to work with older questions, thank y... | Using `Left()` and `Right()` functions:
```
--If the number part is always 6 digits
Select left(yourColumn,6) Col1, right(yourColumn,2) Col2
From yourTable
--For any number of front digits (bit more generic)
Select left(yourCol, charIndex('B',yourCol)-1) Col1,
right(yourCol, len(yourCol) - charIndex('B',yourC... | ```
select substring(col1, 1, 6) as new_col1,
substring(col1, 7, 2) as new_col2
from your_table
``` | Remove values that net each other out to zero, leaving only one positive 2472320 in this case | [
"",
"sql",
"sql-server-2008",
""
] |
Which Oracle SQL-technique is possible to use for concatenate this rows:
```
id | from | to
--------------
a | 20 | 25
a | 26 | 30
a | 32 | 40
b | 1 | 5
b | 7 | 10
b | 11 | 20
```
for such result:
```
a | 20 | 30
a | 32 | 40
b | 1 | 5
b | 7 | 20
```
? Assumed that `from` and `to`... | Maybe something similar:
```
select
field_id,
min(field_from),
max(field_to)
from (
select
field_from,
field_to,
field_id,
sum(willSum) over(partition by field_id order by field_from) as GID
from (
select
field_from,
field_to,
... | Another approach, which uses `model` clause to assign a group number to a consecutive pairs of values:
```
select id1
, min(from1) as from1
, max(to1) as to1
from (select *
from t1
model
partition by (id1)
dimension by (row_number() over(partition by id1 order by f... | Group by calculating the non-breaking periods from two (from and to) values | [
"",
"sql",
"oracle",
"oracle11g",
"group-by",
"connect-by",
""
] |
Lets assume I have 2 tables:
```
Order -< OrderItem
```
I have another table with 2 FKs:
```
Feature
- Id
- FkOrderId
- FkOrderItemId
- Text
```
UPDATE
---
This table is linked to another called FeatureReason which is common to both types of record, be they OrderFeatures or OrderItem features.
Feature -< Fea... | I would recommend using following structure, because if you have 2 foreign keys which either of them can be null, you can have rows with both columns being null or having value.
Added the FeatureReason table too
 | You can do this, but why? What is your reasoning for collating these two distinct items in a single table?
I would suggest having two separate tables, `OrderFeatures` and `OrderItemFeatures`, and on those occasions that you need to query both, collate them with a `union` query. | Is it OK to have 2 FKs on a table, which point to different tables, and one of which will only be used? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2008-r2",
""
] |
I have the following code:
```
select O.ONO
from Customers C, Odetails Od, Orders O, Parts P
where P.PNO=Od.PNO and Od.ONO=O.ONO and O.CNO=C.CNO
group by O.ONO
order by sum(Od.QTY*P.PRICE)desc;
```
However, instead of selecting the `O.ONO` column, I need to select the `C.CNAME` from a different table. How would I go ... | If what you want is a list of Customer Names ordered by the sum of their orders then just change your query from
```
select O.ONO
...
group by O.ONO
```
to
```
select C.CName
...
group by C.CName
```
This will display the customer name and the order number. NOTE: This will repeat the customer name as many times as ... | Please do like this,
```
select C.CNAME from Customers C, Odetails Od, Orders O, Parts P where P.PNO=Od.PNO and Od.ONO=O.ONO and O.CNO=C.CNO group by C.CNAME order by sum(Od.QTY*P.PRICE) desc;
``` | SQL: How to display a column not in group by expression? | [
"",
"sql",
"oracle",
""
] |
I am trying to pick the top 1 result from a select statement inside the set statement of an Update. I can pick the top 1 but the order by clause does not work. Is there a way to make it work or a workaround please?
```
UPDATE a1
SET a1.ServiceLength = ( SELECT TOP 1
a3.START_DA... | Try to do this using a CTE:
```
WITH TopDate
AS
(
SELECT TOP 1 a3.START_DATE, a3.employee_no
FROM #t a1
JOIN #tempservice a2 ON a1.employeeno = a2.employee_no
JOIN #tempservice a3 ON a3.employee_no = a2.employee_no
WHERE a2.start_date = a3.end_date + 1
AND @specifiedDate > a2.start_date... | You can use MAX(START\_DATE) to get the latest START\_DATE for each employee
```
update A set A.ServiceLength= (select MAX(B.Start_Date) from #tbl1 B where B.EmployeeNo=A.EmployeeNo)
from #tbl1 A
```
Please add necessary where clause for your query. | Order by clause within the Set of an Update Statement | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm trying to read tutorials and find question on syntax on sql subqueries for a specific purpose but I can't seem to find the right choice of words to describe my problem.
Table - Part Descriptions
```
+------------+------------+------------+
| ID | Part # | Type |
+------------+------------+------... | You can use a combination of WHERE, GROUP BY and a HAVING clause to get the result. The key in the HAVING clause is to count the distinct items that are included in your WHERE filter:
```
select [part #]
from partDescriptions
where type in (2, 4)
group by [part #]
having count(distinct type) = 2;
```
See [SQL Fiddle ... | ```
SELECT *
FROM PartDesciption P
WHERE EXISTS (SELECT * FROM PartDesciption WHERE ID = P.ID AND Type = 2) AND
EXISTS (SELECT * FROM PartDesciption WHERE ID = P.ID AND Type = 4)
``` | Sql - How to search for distinct rows that have two specific variables | [
"",
"sql",
"sql-server",
""
] |

This query gives all the templateId that are assigned to product id less than 5 and that's the expected output. But we wanted to achieve that without using the sub query in the where clause (Highlighted in red).
If I just remove the subquery then th... | You can do this using a LEFT JOIN in place of a subquery, and check for NULL.
```
SELECT DISTINCT tp.template_id
FROM templateproduct tp
LEFT JOIN templateproduct tp2
ON tp.template_id = tp2.template_id AND tp2.prod_id IN (6, 7, 8, 9, 10)
WHERE tp.prod_id < 5
AND tp2.template_id IS NULL
```
You can do a similar t... | It's because your where clause should be **tp.prod\_id <= 5** | SQL Query Assistnace | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a table in mysql like this
```
CREATE TABLE IF NOT EXISTS `connections` (
`src` int(10) unsigned NOT NULL,
`sport` smallint(5) unsigned NOT NULL,
`dst` int(10) unsigned NOT NULL,
`dport` smallint(5) unsigned NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`src`,`sport`,`d... | First of all you should try to run the SQL query directly against the database without Rails. This helps to identify the bottleneck: Is the query itself slow or is rails slow? I guess the SQL part should not be a problem, but double check that first.
I guess your biggest problem lies in `connections.each`. This loads ... | As already mentioned, fetching 2.5 mio entries requires loads of memory / cpu power. Try fetching the records in batches.
Rails has batch support build-in: <http://api.rubyonrails.org/classes/ActiveRecord/Batches.html>
```
connections.find_each do |con|
link = getServerID(con['src'])
link = getServerID(con['d... | How to handle millions of records daily with mysql | [
"",
"mysql",
"sql",
"ruby-on-rails",
"ruby",
""
] |
I have an Access 2010 database which stores IP addresses of source and destination machines. If I have the following entries in my database
```
|source | destination|
|--------------------------------|
| A | B |
| B | A |
| A | B |
... | Your question seems to imply two things:
1. When listing source/destination pairs you only want to see the pairs in one direction, e.g., (A,B) but not (B,A).
2. The list should omit pairs where the source and destnation are the same, e.g., (D,D)
In that case the query...
```
SELECT DISTINCT source, destination
FROM
... | select unique source, destination from YourTable
or
select distinct source, destination from YourTable
or
select source, destination from YourTable
group by source, destination | selecting distinct pairs of values in SQL | [
"",
"sql",
"ms-access",
"ms-access-2010",
""
] |
I have problem in query. I use posgresql. I need to get total row but with condition "group by"
```
table qwe
----------------------------
TIPE | VAL
----------------------------
1 | 2
2 | 3
2 | 1
2 | 4
3 | 1
3 | 3
```
the result I need is
```
-------------------------
TIPE | VAL ... | you can try this one:
```
select
tipe, sum(val), count(tipe) over() as "total tipe"
from qwe
group by tipe
order by tipe
```
**`sql fiddle demo`**
You see, instead of counting number of not-null `tipe` records inside each group, you can count number of not null tipe over the whole resultset - that's why you need... | That's a strange request, however, I would suggest that you build a view that returns just the count(tipe) of the table and then join that view in? I haven't tested that but I am pretty sure that it would work. | Total row with condition "group By" | [
"",
"sql",
"postgresql",
""
] |
I have tables as follows:
**muscles**
```
id primary_synonym_id source
---------- ------------------ ----------
1 1 1
2 2 2
3 3 3
```
**muscle\_synonyms**
```
id synonym
---------- ---------------
1 ... | I was unfamiliar with the `coalesce()` function. The following query was inspired by [this](https://stackoverflow.com/a/14988043/82216), and it works:
```
select muscles.id, synonym, coalesce(url, isbn) as ref
from muscles
join muscle_synonyms on muscles.primary_synonym_id = muscle_synonyms.id
join sources on muscles.... | i dont exactly understand what is sub\_id in sources and how its linked to source\_books
sql will almost looks like this
```
select m.id,ms.synonym,su.url from muscles m
join muscle_synonym ms on ms.id=m.primary_synonym_id
join sources s on s.id=m.source
join source_url su on s.sub_id=su.id
``` | Join in SQLite with per-row selection of join table based on value in link table | [
"",
"sql",
"sqlite",
"relational-database",
""
] |
I'm trying to write a small script to create a database if it doesn't exist, and create a table for that database if the table doesn't exist. What I have is this:
```
IF (db_id('db') is null) BEGIN
print 'Must create the database!';
CREATE DATABASE db;
END
USE db;
IF (object_id('test_table', 'U') is null) BE... | SQL statements are parsed as one batch unless you break them apart. In SQL Server, you can use GO to do this. In both MySQL and SQL Server, you can use BEGIN and END.
If you want to commit the separate blocks to the database in different instances you can use BEGIN TRANS / COMMIT TRANS and START TRANSACTION / COMMIT f... | Something along the lines of [Check if table exists in SQL Server](https://stackoverflow.com/questions/167576/sql-server-check-if-table-exists) would probably work (With a slight change)
```
IF (NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
... | Create Database and Table Conditionally | [
"",
"sql",
"sql-server",
""
] |
I have a query like
```
select id, item, producer from table
```
The result is like this:
```
id item producer
1 apple A
2 pear A
3 peach A
4 orange B
5 strawberry B
6 melon... | Use the rand function in ORDER BY like this:
```
select id, item, producer from table order by rand();
``` | To Shuffle the selection you can use **rand()**
The Answer for the link below contains more information.
```
SELECT id, item, producer
FROM table
ORDER BY RAND()
```
[MySQL: Shuffle a limited query result?](https://stackoverflow.com/questions/4534195/mysql-shuffle-a-limited-query-result) | SQL Query group shuffle | [
"",
"mysql",
"sql",
""
] |
I have three tables that share one field with another table, so:
```
Employee_Data: EMP_ID, PHONE_EXTENSION
Outage_Data: DATE, EMP_ID
Phone_Data: DATE, PHONE_EXTENSION
```
I need to combine data where the agent data is matched with data in the other two tables. Basically, I need to combine the data from `Outage_data`... | Your query looks mostly fine assuming you mean the RIGHT JOIN on Shrink so you don't miss any rows that don't have a matching Employee\_Data row. There's just an extraneous `JOIN (` at the end of your `FROM` clause that I removed:
```
With Epi AS
(SELECT EMP_ID, PHONE_EXTENSION, Name, Manager, EWFMDeptname, Loca... | ```
Select * from employee_data e
join outage_data d on e.emp_id = d.emp_id
join phone_data p on d.date = p.date
``` | Joining three tables with separate sets of identifying columns | [
"",
"sql",
"join",
""
] |
I am inserting the string into table. But there are some ambiguous, illegal text characters like 'ÔÇô' , '├®' appearing in the string. I want to replace all these invalid characters from the table and update my table. Is there any way to replace such characters in SQL. I am using SQL server 2008. | You could use one of the functions here:
[How to strip all non-alphabetic characters from string in SQL Server?](https://stackoverflow.com/questions/1007697/how-to-strip-all-non-alphabetic-characters-from-string-in-sql-server)
You haven't included your insert statement, so I'm going to guess you've done it similar to... | Like you said... "Replace".
[Replace documentation](http://technet.microsoft.com/en-us/library/ms186862.aspx)
Hint: Replace the ambigous character with an empty string. | Replace Ambigious / Invalid Text Characters from String | [
"",
"sql",
"regex",
"sql-server-2008",
""
] |
I am trying to create an SQL query that combines the results of 3 queries together.
The idea is get the top 1000 users with new messages AND/OR requests AND/OR notifications and then email them one per week.
Note: I am using MS SQL Server.
I have 3 separate complex queries (which i have simplified here) such as:
``... | Try UNION like this :
```
SELECT mbrid, SUM(messageCount), SUM(notificationCount), SUM(requestCount)
FROM (
SELECT mbrid, messageCount, 0 AS notificationCount, 0 AS requestCount
FROM tblMessages
WHERE messageCount > 0
UNION
SELECT mbrid, 0 AS messag... | Just curious, once you "union" all three tables together, how are you going to decide which records are the top 1000?
If your intention is to treat messages, notifications and requests similarly, then the following may be the answer you are looking for:
```
SELECT TOP 1000 * FROM
(SELECT mbrid, messageCount as Count
... | Combine separate SQL queries together filling in the blanks | [
"",
"sql",
""
] |
For Oracle Database, suppose I have two tables here (Similar structure, but much larger amount of data) Definition below:
```
create table payments(
record_no INTEGER;
cust_no INTEGER;
amount NUMBER;
date_entered DATE;
);
insert into payments values(1,3,34.5,sysdate-1);
insert into payments values(2,2,... | First you need to get your creation script right. The `;` terminates a *statement* not a line inside a statement. Secondly the `varchar2` data types needs a length specification: `name VARCHAR2(20)` instead of `name VARCHAR2`. Also character literals need to be enclosed in single quotes. `'90001'` is a character litera... | ```
SELECT * FROM (
SELECT
c.cust_no,
p.amount as payment,
p.date_entered as paydate,
ROW_NUMBER() OVER (PARTITION BY cust_no ORDER BY p.record_no ASC) AS rn
FROM customer c
JOIN payments p ON p.cust_no = c.cust_no
) t
WHERE
rn <= 2
ORDER BY cust_no, rn;
```
W... | Oracle SQL : table Joining | [
"",
"sql",
"oracle",
""
] |
I'd like to get both the minimum value of a particular value, *and* the key of the row that has that minimum value. Currently, I do this as follows:
```
SELECT dates.date AS Date, num_apples.apples AS MinApples FROM
(
SELECT date, MIN(apples) AS MinApples, apples
FROM Table
HAVING MinApples = apples
) AS d... | Assuming that `date` is your key:
```
SELECT qryNumApples.* FROM
(
SELECT MIN(apples) AS MinApples
FROM Table
) AS qryMinApples
JOIN
(
SELECT *
FROM Table
) AS qryNumApples
ON qryMinApples.MinApples= qryNumApples.apples
);
``` | This is ANSI standard SQL:
```
select *
from (
select date,
apples,
min(apples) over () as min_apples
from the_table
) t
where apples = min_apples;
```
Window functions are available across a wide range of DBMS. | Can I get data pertaining to the aggregate in a single query? | [
"",
"sql",
""
] |
Is this statement true or false
The performance of these queries
```
SELECT * FROM table;
UPDATE table SET field = 1;
SELECT COUNT(*) FROM table;
```
Are identical
Or is there ever a case in which the performance of one will greatly differ from the other?
# UPDATE
1. I'm more interested if there's a large diffe... | There are different resource types involved:
* disk I/O (this is the most costly part of every DBMS)
* buffer pressure: fetching a row will cause fetching a page from disk, which will need buffer memory to be stored in
* work/scratch memory for intermediate tables, structures and aggregates.
* "terminal" I/O to the fr... | When you say "performance", do you mean "how long it takes them to execute"?
* One of them is returning all data in all rows.
* One of them (if you remove the "FROM") is writing data to the rows.
* One is counting rows and returning none of the data in the rows.
All three of those queries are doing entirely different... | UPDATE vs COUNT vs SELECT performance | [
"",
"mysql",
"sql",
"performance",
"select",
"sql-update",
""
] |
I have a stored procedure to insert values in to a table.Here I need to check the values for insert is already in the table .how can I check this in my stored procedure.here is my stored procedure.
```
USE [Databasse_sync]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[kt_getyoutubevideo] ... | ```
USE [Databasse_sync]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[kt_getyoutubevideo]
@ProductID nvarchar(200),
@YoutubeUrl nvarchar(200),
@YoutubeImage nvarchar(200)
AS
MERGE [YoutubeVideo] AS Y
USING (SELECT @ProductID,@YoutubeUrl, @YoutubeImage) AS SourceRow... | try this:
```
ALTER PROCEDURE [dbo].[kt_getyoutubevideo]
@ProductID nvarchar(200),
@YoutubeUrl nvarchar(200),
@YoutubeImage nvarchar(200)
```
`AS BEGIN`
```
DECLARE @counter int
@counter = SELECT count(ProductID) FROM YoutubeVideo WHERE ProductID=@ProductID
IF(@counter = 0)
BEGIN
INSERT INTO YoutubeVi... | Storedprocedure to check the value already in the table | [
"",
"sql",
"sql-server",
"sql-server-2008",
"stored-procedures",
""
] |
I am working on a project related to ticket booking.
I can store passenger data i.e. Name,Age,Sex along with Ticket ID in passenger table.
But the problem is if another ticket is booked for same passenger I will have to re-enter the same passenger data & just the Ticket ID will differ.
```
mysql> desc passenger;
+----... | You could store a passenger entity, consisting of name/age/sex etc. (in a passenger entity table) and then your passenger booking table would simply contain the passenger entity ids (integers, GUIDs etc.). This is a form of *normalisation*.
However this may be an optimisation too far. Whether you do this really depend... | In a relational database like mysql, surely the passenget and ticket data should be in separate tables. So have a passenger table that contains personal details like Name, DateOfBirth, Address, Telephone etc and then have a ticket table that has ticketNumber, date etc as well as passengerId (classic many to one relatio... | Lot of redundancy in passenger table | [
"",
"mysql",
"sql",
"database",
"redundancy",
""
] |
I’m doing:
```
SELECT uid, intStatus from dbo.MYTABLE
WHERE
intStatus = 10 and uid = 'a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1'
```
And I get:
```
uid | intStatus
-------------------------------------- +---------------
'a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1 | 10
```
Then I need to... | Probably you have already a row with intStatus 18 and uid 'a1a1...'
Try to run and see if you have already the row that you try to create with your UPDATE:
```
SELECT uid,
intStatus
FROM dbo.MYTABLE
WHERE intStatus = 18
AND uid = 'a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1'
``` | If uid is your primary key then it is unique by definition, therefore the intStatus condition is irrelevant. This should work:
```
UPDATE dbo.MYTABLE SET intStatus = 18
WHERE uid = 'a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1';
```
If that doesn't work, then you could have a composite key combining both columns rather th... | Need explanation for Cannot insert duplicate key row in object error | [
"",
"sql",
"sql-update",
"key",
"duplicates",
"uniqueidentifier",
""
] |
I have the following table ordered by Id, Year DESC
```
Id Year Valid
1 2011 1
1 2010 1
1 2009 0
1 2002 1
4 2013 1
4 2012 1
4 2011 1
etc.
```
What I would like to have is an extra rank field like:
```
Id Year Valid Rank
1 2011 1 1
1 2010 1 1
1 200... | yes, using Left JOIN we can do that.
see the below code and result.
first image is actual data inserted and second image is expected result.

```
DECLARE @t TABLE
(
id INT
,_YEAR INT
,valid TINYINT
)
INSERT INTO @t( id, [_YEAR], v... | This is somewhat similar to [@Anup Shah's suggestion](https://stackoverflow.com/a/19306054/297408) but doesn't use a join and instead uses a window aggregate function:
```
WITH derived AS (
SELECT
Id,
Year,
Valid,
LatestInvalidYear = ISNULL(
MAX(CASE Valid WHEN 0 THEN Year END) OVER (PARTITION ... | How to group/rank records based on a changing value of a column? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have table containing one datetime column. I need to return rows for only last 6 months. This can be done by
```
WHERE CloseTime >= DATEADD(Month, DATEDIFF(Month, 0, DATEADD(m, - 6, CURRENT_TIMESTAMP)), 0)
```
This gets me data for the month I am starting this script + 6 last months. So e.g. if I run this script to... | If you want to have the previous 6 months regardless of whether today is the 1st, 3rd, 9th, 29th, whatever, then just subtract 7 months. Here is one way to do that: get the first of the month into a variable, then use an open-ended range in the query.
```
DECLARE @ThisMonth DATETIME;
SET @ThisMonth = DATEADD(MONTH, DA... | When creating queries you do not want to use a function on the search column since it will result in a full table scan.
The solution works and should pick up any index on CloseTime.
```
-- Get me data in months 3 (mar) to 9 (sep) of this year
select
*
from
my_table
where
CloseTime between
DATEADD... | SQL for last six "full" months | [
"",
"sql",
"sql-server",
""
] |
I have a date column that is in varchar. I need to convert it to datetime format.
> My data looks like this in varchar:29-JUL-11 02.44.29.984664000 PM
>
> I want this to be in datetime format like this: 29-JUL-11 02.44.29.984664000 PM
I am using following query:
```
select convert (datetime, (convert (float, [KYC_ST... | You could go the whole hog and do a replace/substring to get your answer
```
select cast(Replace(SUBSTRING('29-JUL-11 02.44.29.984664000 PM',
0, len('29-JUL-11 02.44.29.984664000 PM') - 9),'.',':') as datetime)
```
Ugly but it works! | > I have a date column that is in varchar.
Wrong in the first place. You should use the datatype created for the data.
> I need to convert it to datetime format.
If you're using ASP.NET (I am guessing by the sql-server usage) then you can use this:
```
var time = Convert.ToDateTime("some_time");
```
However
> My ... | Convert a varchar to datetime including hour minute and seconds | [
"",
"sql",
"sql-server",
"datetime",
""
] |
my DB has this structure:
```
ID | text | time | valid
```
This is my current code. I'm trying to find a way to do this as one query.
```
rows = select * from table where ID=x order by time desc;
n=0;
foreach rows{
if(n > 3){
update table set valid = -1 where rows[n];
}
n++
}
```
I'm checking ho... | Assuming that `(id,time)` has a `UNIQUE` constraint, i.e. no two rows have the same `id` and same `time`:
```
UPDATE
tableX AS tu
JOIN
( SELECT time
FROM tableX
WHERE id = @X -- the given ID
ORDER BY time DESC
LIMIT 1 OFFSET 2
) AS t3
ON tu.id = @X ... | You can use a subquery in the `WHERE` clause, like this:
```
UPDATE table
SET valid=-1
WHERE (
SELECT COUNT(*)
FROM table tt
WHERE tt.time > table.time
AND tt.ID = table.ID
) > 3
```
The subquery counts the rows with the same ID and a later time. This count will be thre... | update row if count(*) > n | [
"",
"mysql",
"sql",
"insert",
"sql-update",
""
] |
Have a problem find a query for my tables
I have 2 tables table A and table B as follow
```
table A
---------------------
| Name | addrid |
---------------------
| zlai | 1 |
| blai | 2 |
table B
---------------------
| addrid | addr |
---------------------
| 1 | AMERICA |
| 1... | I try to modified the `addrid` values by 101 and 325 (for example)
```
table A
---------------------
| Name | addrid |
---------------------
| zlai | 101 |
| blai | 325 |
table B
---------------------
| addrid | addr |
---------------------
| 101 | AMERICA |
| 101 | SPAIN |
| ... | ```
SELECT CASE WHEN No != 1
THEN ''
ELSE CAST(a.addrid AS VARCHAR(20))
END AS Num,
CASE WHEN No != 1
THEN ''
ELSE name
END AS name,
addr
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY a.addrid
... | query for grouping multiple same record into 1 line | [
"",
"sql",
"postgresql",
""
] |
I am trying to create the following SQL table, using the query:
```
create table Return_indiv (Date datetime, issueid varchar(255), Return varchar(255))
```
As you see, one of the columns names is "Return". However, SQL believes it is the function `return`, and gives the following error:
```
Msg 156, Level 15, Sta... | You need to add brackets around the column name since it's a keyword:
```
create table Return_indiv
(
Date datetime,
issueid varchar(255),
[Return] varchar(255)
)
```
Note that you'l also have to use brackets every time you *query* that column in the table (or update, etc.) With that in mind you need t... | Just to clarify a bit, Return is a reserved word in your database (probably a function or something). So you can't just use it as a table name, column name, etc. You can get around this by surrounding it with []. But a much better idea is to not use reserved words in any of your object names. I can't really tell what w... | Creating SQL table with column name "Return" | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I'm having a very difficult time trying to get my result to display they i need them to display... here and example of what my query looks like and below will be the result i need...
iv been at this for a long time trying case statements and joins but have had no luck, if anybody can help i would really appreciate it... | First, use CTEs to separate Credits and Debits into separate data sets, then FULL JOIN them based on PTNO, CD, and inverse value (\* -1) of AMT.
Edit: Since joining based on AMT is not a goal, I used BatchSeqID as a way to sort the data chronologically. Using a ROW\_NUMBER() to order the two data sets, I then joined t... | if you don't like Matt's solution and the risk of duplicated rows, you can have every transaction on a different row:
```
SELECT PTNO,
CASE WHEN AMT < 0 THEN cd ELSE null END DBTCD,
CASE WHEN AMT < 0 THEN amt ELSE null END AMTCD,
CASE WHEN AMT < 0 THEN DESCRIPTION ELSE null END DBTDESCRIPTION,
... | SQL Return different values on the same row, based on a value thats in the same table | [
"",
"sql",
"sql-server",
""
] |
I am trying to find a specific `legalStatus` for a specific date range from the following table layout.
```
CREATE TABLE dbo.LegalStatus (
LegalStatusID int IDENTITY,
CaseID int NOT NULL,
LegalStatusTypeID int NOT NULL,
LegalStatusDate smalldatetime NOT NULL
```
Example: I may have three status records.
```
LegalSta... | OK, if I understand your comment, for a given `CaseID`, you can have multiple records, each with with a `LegalStatusTypeID` unique to that case, each with a date, and the applicability for each `LegalStatusTypeID` is between that record's `LegalStatusDate` and *the next record entered for that case*'s `LegalStatusDate`... | ```
SELECT *
FROM LegalStatus
WHERE LegalStatusTypeID = 62 AND
LegalStatusDate BETWEEN '01/01/13' and '07/01/13'
``` | How can I find a specific status within a date range | [
"",
"sql",
"t-sql",
""
] |
I have a table named accessories\_other in my database. In the table, I have column :
1) Item
2)Available
This is the illustration on how the data in the respective column.
## Item
Mouse
Keyboard
Cable
## Available
4
6
3
The thing is, I would like to select Item = 'Mouse' together with column 'Available'=4. ... | > This is just to show how it could be done . You should be using MySQLi
> or PDO . Also if in Production environment , you should not be
> displaying MySQL errors to the user .
You could do it either way :
```
// SQL to find Available value for Item Mouse
$sql = "SELECT Item, Available FROM accessories_other
... | I think your query will not show results of mouse which is lesser than 5..
I suggest you try:
```
$sql ="SELECT Item, Available FROM accessories_other WHERE Item ='Mouse';
```
and then, try to implement your code in another language..
if I'm not mistaken, you're using php.. | How to retrieve data from 2 column in one table? | [
"",
"sql",
"sql-server",
""
] |
This is my stored procedure:
```
ALTER PROCEDURE [dbo].[procViewAdvSearchL1]
-- Add the parameters for the stored procedure here
@keyword nvarchar(800),
@CourtID int = null,
@SYear int = null,
@EYear int = null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with ... | ```
@CourtID int = null,
@SYear int = null,
@EYear int = null
```
All above variable should be declare in NVARCHAR Because dynamic query
give error except it.
```
It Should be
@CourtID NVARCHAR(20) = null,
@SYear NVARCHAR(20) = null,
@EYear NVARCHAR(20) = null
```
Use `exec sp_execute` to execute your query ex... | Based on the posted code i can only see it would get a conversion error of :
`Conversion failed when converting the varchar value '' to data type int.`
Use the following
```
CONVERT(VARCHAR(4),@SYear)
```
and
```
CONVERT(VARCHAR(4),@EYear)
``` | How to pass int parameter in dynamic sql query | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I have 2 queries
```
Select * From wp_booking_transaction
Where DATE(launched) >= "2013-10-10" And DATE(launched) <= "2013-11-10"
And action = 1 status = 1 And type = 2 And student_id = 81569
Order by launched desc
```
and
```
Select * From wp_booking_transaction
Where (DATE(launched) >= "2013-10-10" And DATE(lau... | ```
SELECT *
FROM wp_booking_transaction
WHERE /* Conditions that appeared in both original queries */
DATE(launched) >= "2013-10-10"
AND DATE(launched) <= "2013-11-10"
AND type = 2
AND student_id = 81569
AND /* Conditions that are different between the two queries */
((... | Try using `UNION`:
```
Select
*
From
wp_booking_transaction
Where
DATE(launched) >= "2013-10-10"
And DATE(launched) <= "2013-11-10"
And action = 1
And status = 1
And type = 2
And student_id = 81569
UNION ALL
Select
*
From
wp_booking_transaction
Where (
D... | Combining 2 queries into one query | [
"",
"mysql",
"sql",
""
] |
I have two tables Product table and Rate Table.
**Product**
```
ProductId Name
```
**Rate**
```
LevelId Cost ProductId
```
Each Product has 7 Levels and cost for each level is 100, 200.... 700.
I now need a script to take all the product Ids and Populate the Rate table , so that my end output would look like this... | ```
INSERT INTO Rate
SELECT bs.level, bs.costs, P.productid
FROM
(SELECT 1 as level, 100 as cost
UNION ALL
SELECT 2 as level, 200 as cost
UNION ALL
SELECT 3 as level, 300 as cost
UNION ALL
SELECT 4 as level, 400 as costs
UNION ALL
SELECT 5 as level, 500 as costs... | Have a look at [CTEs (Common Table Expressions)](http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx):
```
WITH CTE AS
(SELECT 1 as LevelID , 100 as Cost
UNION ALL
SELECT LevelID + 1 , Cost + 100
FROM CTE
WHERE LevelID < 7)
INSERT INTO Rate
SELECT CTE.LevelID, CTE.Cost, Product.ProductID
FROM... | Sql script to use a column from one table and populate another table | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"sql-server-2008-r2",
""
] |
I'm writing a basic `SELECT` query, something like:
```
SELECT id, pname, pnumber
FROM tableName
WHERE pnumber IS NOT NULL
```
I'd like to then perform an `INSERT` by using the result of that `SELECT` like so:
```
IF {**the above SELECT query returned 0 rows**}
BEGIN
INSERT INTO tableName (pname,pnumber) VALUE... | ```
IF NOT EXISTS (SELECT ...)
BEGIN
INSERT ...
END
```
You could also do this, if you expect that the query might often return rows (especially a lot of rows), which may offer a better opportunity to short circuit:
```
IF EXISTS (SELECT ...)
BEGIN
PRINT 'Do nothing.';
END
ELSE
BEGIN
INSERT ...
END
```
...sinc... | In MySQL you can check the number of rows returned from last SELECT query like this:
```
SELECT FOUND_ROWS();
``` | Check if SELECT Returns Any Rows in Stored Procedure | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
Using ORACLE sql developer
I have:
Field ID 1: '006789'
Field ID 2: '026789'
Field ID 3: '126789'
I want:
Field ID 1: '6789'
Field ID 2: '26789'
Field ID 3: '126789'
This lives in table "EMPLOYEES"
I want to do something like this
```
begin
if FIELD_ID is like '00%' then
update EMPLOYEES
... | If you need to remove leading or trailing characters from a string, you don't need regex, TRIM functions wil suffice. In Oracle, there
are three functions, [TRIM](http://docs.oracle.com/cd/E16655_01/server.121/e17209/functions229.htm#SQLRF06149), [LTRIM](http://docs.oracle.com/cd/E16655_01/server.121/e17209/functions10... | not sure why did you go with RegExp, but if you need just removing Leading and Trailing character from string Oracle has TRIM function for that.
***TRIM(both '1' from '123Tech111') would return '23Tech'***
[example that fits your requirement](http://www.techonthenet.com/oracle/functions/trim.php)
[Oracle Documentati... | pl/sql conditionally replace characters of field in a table using regex | [
"",
"sql",
"regex",
"oracle",
""
] |
I hope the title is somewhat helpful. I'm using MySQL as my database
I am building a database of products and am not sure how to handle storing prices/SKU of variations of a product. A product may have unlimited variations, and each variation combination has its own price/SKU/etc..
This is how I have my products/vari... | Applying normalization to your problem, the solution is as given. Run and see it on [SQL Fiddle](http://sqlfiddle.com/#!2/7fd9c/1).
```
CREATE TABLE products (
product_id int AUTO_INCREMENT PRIMARY KEY,
name varchar(20),
description varchar(30)
);
INSERT INTO products
(name, description)
VALUE... | Part of your issues stem from a confusion between product and SKU.
When you sell, "XYZ pullover, size M, blue model", the latter corresponds to an SKU. It is marketed as an XYZ pullover (the product), which has a set of attributes (size and colors), each with their own set of potential values. And not all possible com... | Designing a SQL schema for a combination of many-to-many relationship (variations of products) | [
"",
"sql",
"schema",
"e-commerce",
"database-schema",
"entity-attribute-value",
""
] |
I have 2 tables (AllClients & AllActivities) and need to retrieve the following information:
I need a list of clients where there are no associated activities.
Here are my tables with some fake data to help explain what I'm looking for:
... | You don't necessarily need a join
```
select *
from AllClients c
where TypeCode = 'P'
and not exists (select 1 from AllActivities a where a.LookupCode = c.LookupCode)
``` | ```
select c.*
from AllClients c
left join AllActivities a on a.LoopupCode = c.LoopupCode
where a.LoopupCode is null
and c.TypeCode = 'P'
``` | Not sure which SQL join to use | [
"",
"mysql",
"sql",
"join",
""
] |
SQL is not my best thing but I have been trying to optimize this stored procedure. It had multiple scalar-valued functions that I tried to change to table-valued functions because I read in many places that it's a more efficient way of doing it. And now I have them made but not real sure how to implement or if I maybe ... | Table-valued functions return a table, in which, like any other table, rows have to be inserted.
Instead of doing `set @result = .....`, do:
```
INSERT INTO @T (result) VALUES ( ..... )
```
**EDIT**: As a side note, I don't really understand the reason for this function to be table-valued. You are essentially return... | Getting a count just to see if at least one row exists is *very* expensive. You should use `EXISTS` instead, which can potentially short circuit without materializing the entire count.
Here is a more efficient way using an inline table-valued function instead of a multi-statement table-valued function.
```
ALTER FUNC... | SQL Table Valued Function in Select Statement | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Given the following table structure:
```
CREATE TABLE [dbo].[NodeTest] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[NodeCode] NVARCHAR (50) NOT NULL,
[ParentNodeCode] NVARCHAR (50) NULL,
[NodeName] NVARCHAR (255) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
```
And the following data:
```
... | Using a common table expression (CTE)
```
declare @parentCode varchar(20) = '01'
;with cte as
(
select * from NodeTest where ParentNodeCode = @parentCode
union all
select NodeTest.*
from NodeTest
inner join cte on cte.NodeCode = nodeTest.ParentNodeCode
)
select @parentCode, nodeCode from ct... | Working [SQLFiddle](http://sqlfiddle.com/#!3/7826c/4)
I think you want this
```
with cte as
(
select * from NodeTest where ParentNodeCode = '01'
union all
select NodeTest.*
from NodeTest
inner join cte on cte.NodeCode = NodeTest.ParentNodeCode
)
select * from cte... | How to get all descendants of a node | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
My query causes the following error:
> Msg 512, Level 16, State 1, Procedure Item\_insupd, Line 17
> Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Query:
```
INSERT INTO [Total_Database].[dbo].[Item]
(
... | I suspect the problem is in this string (line 26 in your [code](http://pastebin.com/trF85RHq)):
```
IF NOT (EXISTS (SELECT G.GLAccountID FROM GLAccnt G INNER JOIN Inserted I ON G.GLAccountID = I.SalesGLAccountID))
OR ((SELECT I.COGSGLAccountID FROM Inserted I) IS NOT NULL) AND NOT (EXISTS (SELECT G.GLAccountID FROM GL... | If you really only want to insert one row, then You just add `Where` at the end, followed by some predicate (logical statement) that will be true for only one row in the table the query is reading from.
```
INSERT INTO [Total_Database].[dbo].[Item](ItemID,
ItemNo,ItemDescription,Notes,StandardCost,SalesGLAccountID... | SQL Subquery returned more than 1 value | [
"",
"sql",
"sql-server",
""
] |
suppose you have a data set having 3 columns: ID, user, date.
is it possible to filter the data based on the minimum date even if some of the rows have identical IDs?
sorry if the question is a bit unclear. hopefully the image below will help clear things.
there are two records having ID=1, with different users as w... | ```
SELECT id, user, date
FROM OriginalData od
WHERE date = (SELECT MIN(date)
FROM OriginalDate od1
WHERE od.id = od1.id)
``` | ```
Select * from table_name where date in
( select MIN(date) from table_name)
``` | group rows based on ID and then return the row with the lowest date per ID grouping | [
"",
"sql",
""
] |
In Ms Access i can create a query, called "CustomerList" with following datas:
```
CustomerName, City, Revenue
```
Then i can create another query, for instance "CustomerCount" like:
```
Select count(*) as Tot
from CustomerList ( <<<- is a query name)
where CustomerList.City
```
This query is based on another Que... | Yes, like this
```
Select count(*) as Tot
from
(
select City from some_table
) x
where x.City = 'NYC'
```
You have to alias subqueries. | You can create a `VIEW`
A `VIEW` works like a table but really is a select on one or more tables.
<http://dev.mysql.com/doc/refman/5.0/en/create-view.html> | Nested query in MySql | [
"",
"mysql",
"sql",
"ms-access",
""
] |
I have this query in PostgreSQL
```
SELECT numeric_value, entity_id
FROM data_value
WHERE
entity_id = 16029 OR
entity_id = 16026 OR
entity_id = 33768 AND
category_id = 158
```
The important thing to me is the numeric value, but I would like to display in this format:
```
16029 | 16026 | 33768
value | value | val... | Have you missed parenthesis in your query, should it be something like this:
```
select
numeric_value, entity_id
from data_value
where
entity_id in (16029, 16026, 33768) and
category_id = 158
```
Anyway, you can easily pivot data by hand with aggregates (you just have to specify key if you want to get mor... | Should be possible to create that result using the [crosstab](http://www.postgresql.org/docs/9.1/static/tablefunc.html) function.
Not the easiest part of Postgres, so be prepared to spend some time reading the docs and experimenting :)
As I think it's not immediately obvious from the doc: tablefunc is the extension c... | sql columns by field value - is it possible? | [
"",
"sql",
"postgresql",
"calculated-columns",
""
] |
I have a table like this :
```
id | user_id | param_id | param_value
1 1 44 google
2 1 45 adTest
3 1 46 Campaign
4 1 47 null
5 1 48 null
6 2 44 google
7 2 45 a... | ```
SELECT DISTINCT up.user_id
FROM user_params AS up
LEFT JOIN user_params AS upp ON up.id = upp.id
group by up.user_id
having sum(param_id = 44 AND param_value = 'google') >= 1
and sum(param_id = 45 AND param_value = 'adTest') >= 1
``` | Another way:
```
SELECT -- DISTINCT
up1.user_id
FROM
user_params AS up1
JOIN
user_params AS up2
ON up1.user_id = up2.user_id
WHERE
up1.param_id = 44 AND up1.param_value = 'google'
AND
up2.param_id = 45 AND up2.param_value = 'adTest' ;
```
You do not need the `DISTINCT`, if there is... | How to select distinct rows where 2 columns should match on multiple rows? | [
"",
"mysql",
"sql",
""
] |
I have the following SQL Server 2012 table:
```
create table dbo.Packs {
Id int identity not null,
Info nvarchar (200) not null
}
```
How can I get all rows where Info starts with "File" ... I might have:
```
"File #200 View", "File #100 Delete", "Stat F#20"
```
So I would get the first two records.
Thank You,... | You can use the [`LIKE` operator](http://technet.microsoft.com/en-us/library/ms179859.aspx) with the % wildcard:
```
SELECT [Id], [Info]
FROM [dbo].[Packs]
WHERE [Info] LIKE 'File%'
```
Example
```
CREATE TABLE packs ([Info] varchar(16));
INSERT INTO packs ([Info])
VALUES ('File #200 View'), ('File #100 Delete'), (... | ```
SELECT Id,
Info
FROM Packs
WHERE Info LIKE 'File%'
``` | Read part of column value | [
"",
"sql",
"sql-server-2012",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.