Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I would like to round up a value to the next nearest power of 2 in a mysql query, so
```
select RoundUpToNearestPowerOfTwo(700) -- Should give 1024
```
I need this solution as part of a much larger query to generate and read some bitmask. Using custom stored functions is not an option, since I cannot use those in our... | Try this.
```
FLOOR(POW(2,CEIL(LOG2(1025))))
```
The CEIL and FLOOR cope with the boundary conditions correctly. | Try this:
```
select power(2, 1 + floor(log2(XXX)))
```
MySQL conveniently has the `log2()` function, which does most of the work.
EDIT:
I think this may be what you want:
```
select (case when floor(log2(XXX)) <> log2(XXX)
then power(2, 1 + floor(log2(XXX)))
else power(2, floor(log2(XXX)... | Round up a value to the nearest power of 2 in MySQL query | [
"",
"mysql",
"sql",
""
] |
I am using SQL Server Compact 4.0 and am trying to get one query to return a single record with a column `Alarm` based on the maximum identity when another column `Cleared` is `NULL`.
This works:
```
SELECT Id, Alarm
FROM Alarm_History
WHERE Cleared IS NULL
```
Giving me half the answer. The problem is that it ret... | You could do it with max and a join, but that would be far too complicated. Instead, you can just try:
```
SELECT TOP 1 Id, Alarm
FROM Alarm_History
WHERE Cleared IS NULL
ORDER BY Id DESC
```
**Note:** what happens if two alarms have max id ? Well, that shouldn't happen (Id is unique). But that's an interesting probl... | Don't think "max". Think "order by". Try this:
```
SELECT TOP 1 Id, Alarm
FROM Alarm_History
WHERE Cleared IS NULL
ORDER BY Id DESC;
```
That way, you can get all the fields you want associated with the max id. | SQL Server CE retrieve a field from the record with the MAX(Id) | [
"",
"sql",
"sql-server-ce",
""
] |
I have created a calendar table that contains all the calendar dates of a year, incl. the corresponding quarter / week / month / day etc. information.
The following Select gives me all Fridays in December.
What would be the best way here to get only the second out of these ?
```
SELECT *
FROM Calendar
WHERE... | Assuming that you have a `day_of_month` type of field, the second Friday must be day 8 to 14.
```
SELECT *
FROM Calendar
WHERE (yearCal = 2014)
AND (monthCal = 12)
AND (weekDayCal = 6)
AND (dayInMonth BETWEEN 8 AND 14)
```
You could use a `Week of month` field, but this can ge... | If this is a recurring requirement, then you should add a column `weekInMonthCal` and include it in the constraint clause.
It is possible to count in SQL but, as this involves aggregation in the result set, it is expensive. | SQL Server: proper use of Select with calendar table | [
"",
"sql",
"sql-server",
"date",
"stored-procedures",
"calendar",
""
] |
I am very new to SQL and I would appreciate it if you could help me. I have a table that has a field with many IDs and that field is in number format. The same ID may repeat different number of times, e.g. 5 times, 6 times. I want to display records of **all fields** only when the same ID is repeated less than x times ... | Try this:
```
SELECT T1.* FROM TableName T1
INNER JOIN
(SELECT ID,COUNT(ID) as Count
FROM TableName
GROUP BY ID
HAVING COUNT(ID) < 5) T2 ON T1.ID=T2.ID
```
**EDIT:**
Try your query using alias names:
```
SELECT APropertyID,BPropertyID,Ayy,Byy from
(SELECT a.PropertyID as APropertyID, b.PropertyID as BPropertyID, ... | SQL Server allows for an [OVER Clause](http://technet.microsoft.com/en-us/library/ms189461.aspx) in aggregates (which is a useful but "nonstandard" SQL feature) that is handy in cases like this.
> Determines the partitioning and ordering of a rowset before the associated window function is applied. That is, the OVER c... | Select records from a table only where a field value is repeated less than x times | [
"",
"sql",
"sql-server",
""
] |
In [this fiddle](http://sqlfiddle.com/#!2/a4f5f/1) I have a single table called "tags". It has four columns:
```
id counter sessionid tag
(1, 1, 'session1', 'start'),
(2, 2, 'session1', 'sessionname1'),
(3, 3, 'session1', 'unimportant tag'),
(4, 4, 'session1', 'unimportant tag'),
(5, 5, 'session... | Something like the following should work for you:
```
SELECT tags.*, tagnames.tag AS sessionname
FROM tags
INNER JOIN
(SELECT sessionid, tag
FROM tags WHERE counter = 2) AS tagnames
ON tags.sessionid = tagnames.sessionid
```
This method works by creating a table that consists only of the session identifier an... | You can try:
```
SELECT tags.id, tags.counter, tags.sessionid, tags.tag, t.name
FROM (tags
LEFT JOIN
(SELECT sessionid, tag as name
FROM tags
WHERE counter = 2) as t
ON tags.sessionid = t.sessionid
) ;
```
Looks fine tested on [this fiddle](http://sqlfiddle.com/#!2/a4f5f/8) | SQL SELECT generate additional column from same table with special condition | [
"",
"mysql",
"sql",
"select",
"inner-join",
"conditional-statements",
""
] |
I got this similar question but it doesn't help me. ([Anorm parse float values](https://stackoverflow.com/questions/11180429/anorm-parse-float-values)).
And I can honestly say I didn't understand the solution of that question.
I am getting this complie time error:
```
could not find implicit value for paramete... | try this...
```
def getInformation(id: Long): List[(Float, Float, Float)] = {
DB.withConnection { implicit con =>
val query = SQL("select principal,interest,value from myTable where userId={id} and status=true").on("id"->id)
val result = query().map { row =>
Tuple3(row[Float]("principal").asIns... | Maybe a short review of implicits help you. Let's construct a very basic example:
```
// some class which will be used as implicit (can be anything)
case class SomeImplicitInformation(maybe: Int, with: Int, data: Int)
// lets assume we have a function that requires an implicit
def functionRequiringImplicit(regularPar... | Could not find implicit value for parameter c: anorm.Column[Float] | [
"",
"mysql",
"sql",
"scala",
"playframework",
"anorm",
""
] |
I am trying to create a `sp_send_dbmail` that uses HTML formatting that will send two different tables within 1 email. But I keep getting:
> The data types varchar(max) and varchar(max) are incompatible in the '&' operator
This script is pulling info from 2 different Views that populate the 2 different tables.
I am ... | Change `set @Mergedtable = @MTDResults & @Top10CustMTD` to `set @Mergedtable = @MTDResults + @Top10CustMTD`. `&` is not valid for string concatenation. | `&` in TSQL is, unlike Visual Basic, used for boolean operations, not for varchar concatenations. For it, you should use `+`, providing that both of the entries are varchars:
```
set @Mergedtable = @MTDResults + @Top10CustMTD
```
If one of them is not varchar, you will first have to convert it to varchar (not your ca... | The data types varchar(max) and varchar(max) are incompatible in the '&' operator | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
```
ID amount account number(varchar)
5105 0.70 23423423
5105 0.0 null
5105 0.0 null
5104 0.0 null
5104 0.0 null
5104 0.0 null
5106 0.0 32132111
5106 0.0 null
```
I want to get the distinct id for which all of its amount value is 0.0 and account number is nu... | ```
Select DISTINCT ID FROM TableName
GROUP BY ID
HAVING SUM(amount)=0.0
```
Update for another condition( another column which is varchar. It should be null)
```
Select DISTINCT ID FROM TableName
WHERE AnotherColumn IS NULL
GROUP BY ID
HAVING SUM(amount)=0.0
```
SQL Fiddle: <ht... | ```
Select DISTINCT ID FROM TableName
GROUP BY ID
HAVING min(amount)=0.0 and max(amount)=0.0
``` | SQL Query to select records for rows having value =0 in one column and unique id in another column | [
"",
"mysql",
"sql",
"sql-server",
""
] |
I have a field that returns a string value in this format `xxxxxxx(xxxxx)`. Now I need to extract the content of the string inside () as well the ones before (). How can I achieve this? | ```
declare @str varchar(100)
set @str='xxxxx(aaa)'
---- extracts xxxxx
select SUBSTRING(@str,0,CHARINDEX('(',@str))
---- extracts aaa
select SUBSTRING(@str,CHARINDEX('(',@str)+1,CHARINDEX(')',@str)-CHARINDEX('(',@str)-1)
``` | Please try:
```
declare @var nvarchar(100)='xxxxxxx(xxxxx)'
select @var,
LEFT(@var, charindex('(', @var, 1)-1),
replace(right(@var, charindex('(', @var, 1)-1), ')', '')
``` | Extracting a part of String in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I have a table which contains strings which is needed to be searched [like below image]
 TableA
After that, I have a table which stores data [like below image]
 TableB
And what the search function... | Please try:
```
select
a.*
From tblA a inner join tblB b
on b.Col like '%'+a.Col+'%'
```
[SQL Fiddle Demo](http://sqlfiddle.com/#!3/1bde1/1) | One of these should work according to me
```
SELECT b.colA
FROM TableB b join TableA a
WHERE colA like '%' + a.ColA + '%';
SELECT b.colA
FROM TableB b join TableA a
WHERE INSTR(b.colA, '{' + a.colA + '}') > 0;
``` | SQL select from table where column contains specific strings | [
"",
"sql",
"sql-server",
"aggregate-functions",
""
] |
I have theses two queries
```
SELECT course,
COUNT(*) AS countp
FROM table1
WHERE pickout='Yes'
GROUP BY course
SELECT course,
COUNT(*) AS countw
FROM table1
WHERE pickout='Yes' AND result='Won'
GROUP BY course
```
what I am trying to achieve is a table with three columns `Course`, `Countp`, `Countw` but I am hav... | In MySQL the result of conditions evaluate to `1` or `0`. You can sum that up
```
SELECT course,
sum(pickout='Yes') AS countp,
sum(pickout='Yes' AND result='Won') AS countw
FROM table1
GROUP BY course
``` | Try the following SQL:
```
SELECT
Course,
COUNT(*) AS CountP,
SUM(CASE WHEN result='Won' THEN 1 ELSE 0 END) AS CountW
FROM table1
WHERE pickout = 'Yes'
GROUP BY Course
``` | Combining two Count Queries into one | [
"",
"mysql",
"sql",
""
] |
I have two SQL queries that I thought should be equivalent:
```
SELECT COUNT(*) FROM (
SELECT distinct(e.id) FROM entity as e
join organization_feature as o on o.entity_id = e.id
where exists (
select * from entity where o.feature_id = 2086 and o.string_value is not null
) and ( o.feature_id = 2038 ) GRO... | In the other post you are mentioning, if you look at the answer with the `where exists` clause you would see that in this clause **a join was made between the table in your where exists clause and at least one of the tables in your main join** - which you haven't done so in your first query.
Based on the queries you po... | ```
where exists (
select * from entity where o.feature_id = 2086 and o.string_value is not null
) and ( o.feature_id = 2038 )
```
from the first select is actually suposed to be
```
where exists (
select * from entity where o.feature_id = 2086 and o.string_value is not null
) or ( o.feature_id = 2038 )
`... | Can anyone explain why this first SQL query gives 0 when this second query gives me results | [
"",
"mysql",
"sql",
""
] |
I need to match some gender specific data in a SQL query and am having some difficulty in getting the where clause logic correct. I am attempting to use a case statement, but am getting stuck... maybe the case statement isn't the best way to do this, and if so, any viable alternatives would be appreciated.
First, I ha... | ```
select x from y
where (( UPPER(d.Gender) = UPPER(@gender) OR UPPER(d.Gender) ='EITHER')
AND @gender IS NOT NULL )
OR (@gender IS NULL AND 1=1)
```
`1=1` condition in `WHERE clause` always evaluates to true and is a hack to essentially ignore WHERE statement , so here if `@gender` is... | Not sure why you are using a case conversion. Is your DB case sensitive?
Try this
```
select x from y
where UPPER(d.Gender) = upper(@gender)
OR UPPER(d.Gender) = UPPER(isnull(@gender,'EITHER'))
``` | sql case statement contained in where clause - conditional logic | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Using SQL Server
I have two tables
Table 1 contains each username and his manager
```
User HisManager
John Micheal
Gib Mai
Sara Mai
```
And Table 2 contains All records for the Users
```
Id UserName Comment Date
1 John [Any comment] [Any Date]
2 Sara [Any comment] [Any Da... | ```
SELECT * from Table2 a inner join
(SELECT * FROM Table1 WHERE Manager = 'ManagerX') b ON a.User = b.Username
``` | ```
SELECT Table2.*
FROM Table1
INNER JOIN Table2 ON Table1.User=Table2.UserName
WHERE Table2.HisManager = @ManagerX
``` | SQL Command - Advanced selecting | [
"",
"sql",
"sql-server",
"database",
"select",
""
] |
I want to split date in column in 3 fields, I use this query
```
SELECT
SUBSTRING(Account.date, 1, 2) AS "Month",
SUBSTRING(Account.date, 4, 2) AS "Day",
SUBSTRING(Account.date, 7, 4) AS "Year"
FROM Account
```
Almost all data is in format `02/11/2000`, but some of it can be `02/November/2000` or `2/11/2000`.
Only... | Surprisingly `CAST('2/November/2000' as datetime)` works (checked on SQL Server 2008), gives value **2000-11-02 00:00:00.000**
```
SELECT
Month(CAST(Account.date AS DateTime)) "Month",
Day(CAST(Account.date AS DateTime)) "Day",
Year(CAST(Account.date AS DateTime)) "Year",
FROM Account
```
But as rightly pointed ou... | You can do it this way by using `CHARINDEX` and `SUBSTRING` functions
```
select
LEFT(Account.date, CHARINDEX('/', Account.date) - 1),
SUBSTRING(Account.date, CHARINDEX('/', Account.date) + 1, LEN(Account.date) - CHARINDEX('/', Account.date) - CHARINDEX('/', Account.date, CHARINDEX('/', Account.date)) - 2),
... | SQL Server : split string in SELECT statement | [
"",
"sql",
"sql-server",
"substring",
""
] |
I have a table which contain `identity primary key id`, `CNum`, `CUID` and some other columns. I want to select distinct records based on `CNum` and `CUID`, in other words if two records have the same `CNum` and `CUID` I want to get the top one, I tried to group by but it will not work since the want the whole row.
``... | If you want to select the first row of a set of rows with the same characteristics, you can use the [ROW\_NUMBER() function](http://technet.microsoft.com/en-us/library/ms186734.aspx) and PARTITION BY clause. Something like this:
```
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY CNum, CUID ORDER BY Id) ... | You missing `distinct` from final select statement
```
select distinct c.CNum
from Con c
inner join a on a.CNum = c.CNum and a.CUID= c.CUID
order by id
``` | Select distinct columns sql server | [
"",
"sql",
"sql-server",
"t-sql",
"distinct",
"distinct-values",
""
] |
I am building a hotel booking system and I just got stuck when trying to make a query that retrieves all available room types in a given range.
I have two tables `Rooms` and `Reservations`. The `Rooms` table hold the rooms in the hotel. Their number (`id`) and their type (`type`).
Table `Reservations` holds the reser... | Try this:
```
SELECT * FROM Rooms WHERE ID NOT IN(SELECT room_id FROM reservations WHERE '2014-03-07 19:00:00' < e_to AND '2014-03-08 19:00:00' > e_from)
``` | Why not just reverse the comparison signs
WHERE reservations.e\_from >'2014-03-07 19:00:00'
AND reservations.e\_to <'2014-03-08 19:00:00' | Select available rooms in given date range | [
"",
"mysql",
"sql",
""
] |
I am trying to deploy the shared dataset in Visual Studio 2010 solution to Sql server 2012 reporting services. But always getting the below error:
> The feature: "Shared dataset" is not supported in this edition of Reporting Services. | Depends on what version of SQL Server you're using.
If it's Express Edition Advanced or Workgroup or Web edition, I think it's not supported.
[www.katieandemil.com](http://www.katieandemil.com/ssrs-the-feature-shared-dataset-is-not-supported-in-this-edition-of-reporting-services) | Shared dataset are absent in express, web & workgroup versions [see msdn link](http://msdn.microsoft.com/en-us/library/ms365156.aspx) | Shared Dataset is not supported with sql server 2012 reporting services | [
"",
"sql",
"sql-server",
"reporting-services",
"sql-server-2012",
"ssrs-2008",
""
] |
In PostgreSQL, is it possible to generate a series of repeating numbers? For example, I want to generate the numbers 1 to 10, with each number repeated 3 times:
```
1
1
1
2
2
2
3
3
3
.. and so on.
``` | You could cross join it to a series of 3:
```
SELECT a.n
from generate_series(1, 100) as a(n), generate_series(1, 3)
``` | You could try integer division like this:
```
SELECT generate_series(3, 100) / 3
``` | How can I generate a series of repeating numbers in PostgreSQL? | [
"",
"sql",
"postgresql",
"generate-series",
""
] |
I want to combine two queries on the same table that has group by.
Here is my table :
```
Date##### | Value1 | Value2 | Value3 | Type
------------------------------------------------------
23/04/2014 | 1,2 | 12,3 | 10 | Green
23/04/2014 | 11,2 | 3 | 10,3 | Non-Green
24/04/20... | ```
SELECT d,
sum(CASE WHEN LW = 'Green' THEN cnt ELSE 0 END) [Green],
sum(CASE WHEN LW = 'Non-Green' THEN cnt ELSE 0 END) [Non-Green]
FROM
(
SELECT [date] AS d,
[Type] as LW,
CASE WHEN Value1 >= 10 THEN 1 ELSE 0 END +
CASE WHEN Value2 >= 10 THEN 1 ELSE 0 END +
CASE WHEN Value3 >= 10 TH... | You could use two case statements, one for each value; here I'm splitting the rows up in a common table expression first to simplify the cases somewhat;
```
WITH cte AS (
SELECT date, type, value1 value FROM tbBooth UNION ALL
SELECT date, type, value2 value FROM tbBooth UNION ALL
SELECT date, type, value3 value ... | SQL Server : how to combine two select queries from the same table and take the result on Column | [
"",
"sql",
"sql-server",
"select",
"pivot",
"union",
""
] |
```
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
productid INTEGER[] NOT NULL,
amount INTEGER[] NOT NULL,
totalprice FLOAT NOT NULL,
ordertime TIMESTAMP NOT NULL,
FOREIGN KEY (productid) REFERENCES products(id)
);
```
I was trying to create a table to record orders. Since that on... | I think to solve this issue you can use a table for "orders" and another table for "products"
if the relationship between them one:many put the FOREIGN KEY in "products" table
however, it seems that the relationship is many:many, so create a new table "order-product"
that has the two key from the other two tables. | Arrays of foreign keys are not supported by PostgreSQL at this time.
Support was proposed for PostgreSQL 9.4, but performance and implementation quality issues lead to its being dropped from the release. It might be added in a future release, or might not. As of 9.6 I don't see anybody working on it.
You *can not* us... | SQL Foreign Key Array referencing non-array | [
"",
"sql",
"postgresql",
""
] |
I am trying to count total Logged In time for every user for my application.
I am providing necessary DDL and DML queries for necessary test data [here](http://sqlfiddle.com/#!2/61bb7/1).
I tried this Query for resolving my purpose.
```
select userId,
sum(loginTimeInHour) as loginTimeInHour
from(
select e1.userI... | You could just find all login/logout without an event between them, and sum the intervals;
```
SELECT e1.userid, SUM(UNIX_TIMESTAMP(COALESCE(e2.time, NOW())) -
UNIX_TIMESTAMP(e1.time))/3600 total
FROM eventlog e1
LEFT JOIN eventlog e2
ON e1.userid = e2.userid AND e2.eventType='LOGOUT' AND e1... | You need to check for two conditions. You only want adjacent pairs of login/logout. One way to do this is to find the next logout record. Then, count the number of login records between them. Only choose the number that have no other login records.
I prefer to do "next" type calculations using correlated subqueries, r... | MySQL count Total Logged In Time for Application | [
"",
"mysql",
"sql",
""
] |
I'm working with Sql server 2008.i have a table contains following columns,
```
Id,
Name,
Date
```
this table contains more than one record for same id.i want to get distinct id having maximum date.how can i write sql query for this? | Use the ROW\_[NUMBER() function](http://technet.microsoft.com/en-us/library/ms186734.aspx) and PARTITION BY clause. Something like this:
```
SELECT Id, Name, Date FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Date desc) AS ROWNUM
FROM [MyTable]
) x WHERE ROWNUM = 1
``` | If you need only `ID` column and other columns are NOT required, then you don't need to go with `ROW_NUMBER` or `MAX` or anything else. You just do a `Group By` over `ID` column, because whatever the maximum date is you will get same ID.
```
SELECT ID FROM table GROUP BY ID
--OR
SELECT DISTINCT ID FROM table
```
If y... | how to get the distinct records based on maximum date? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2008-r2",
"sql-server-2012",
""
] |
Provided this sort of db structure how might one write a query to find only movies that have both male and female patrons?
```
movie
movID
name
ticket
TID
movID
patronID
patron
PID
gender
``` | I'd say do two queries to get all male patrons and female patrons and then join those based on movID:
```
WITH malePatrons AS
(
SELECT name, m.movID
FROM movie JOIN ticket tic ON movie.movID = tic.movID
JOIN patron pat ON pat.PID = tic.patronID
WHERE pat.gender = "male"
), femalePatrons AS
(
SELECT... | You don't need to query the tables multiple times. My comment may have been a but too obscure, but I was trying to hint you towards something like:
```
select m.name
from movie m
join ticket t on t.movid = m.movid
join patron p on p.pid = t.patronid
group by m.movid, m.name
having count(distinct p.gender) = 2;
```
Th... | SQL Multiple Values in Same Column | [
"",
"sql",
"oracle",
""
] |
I need to generate a report 12 months before the current date.
Today is 2014-04-29. So my date range would be 2013-04-29 to 2014-04-29.
These is my sample data:
```
--------------------------------------
-- user_id | lead_id | date_entered --
-- 1 | 1 | 2013-12-05 --
-- 1 | 2 | 2014-03-15 ... | You need to query year on grouping too, using `WHERE a.year=DATE_FORMAT(d.date_entered, "%Y")` as extra condition at top select level.
```
select a.month, a.year, IFNULL(d.total, 0) AS total
from (
SELECT 'Apr' month, 2013 year, 1 monthOrder UNION
SELECT 'May' month, 2013 year, 2 monthOrder UNION
SELECT ... | I think you should simplify and use this hack...
basically you format the date in year/month format and group by it as a string, and count.
This query alone should give you all the report you need.
```
select
concat( DATE_FORMAT(date_entered ,'%Y%m')) as `yearmonth`,
count(*) as `total`
from
le... | Generate report by month and year in mysql | [
"",
"mysql",
"sql",
"report",
""
] |
I have a table with a column (`dateDT`), formatted as datetime and a variable input for the year (`@selYear`) in my Select, formatted as int.
How can I replace the year within a date from my table with the variable input and return the result in datetime format (within a Select) ?
**I have tried the following but thi... | A solution using [DATEADD](https://learn.microsoft.com/en-us/sql/t-sql/functions/dateadd-transact-sql) function:
```
DECLARE @selYear VARCHAR(4) = 2014
DECLARE @dateDT DATETIME = '2010-05-02 00:00:00.000'
SELECT DATEADD(YEAR,@selYear - YEAR(@dateDT),@dateDT)
```
---
This is example with smaller then current year:
... | You can use [DATEFROMPARTS](https://learn.microsoft.com/en-us/sql/t-sql/functions/datefromparts-transact-sql) in sqlserver 2012
```
DECLARE @selYear int = 2014
DECLARE @dateDT datetime = '2010-05-02'
SELECT DATEFROMPARTS(@selYear,
DATEPART(m, @dateDT),
DATEPART(d, @dateDT))
... | Replace year in datetime date | [
"",
"sql",
"sql-server",
"t-sql",
"datetime",
""
] |
I've noticed something odd with Rails (4.1) ActiveRecord, where `select` and `count` sometimes mix badly:
```
User.all.count
=> 103
User.all.size
=> 103
User.all.length
=> 103
```
So far, so good. I can select on `id`:
```
User.select(:id).all.count
=> 103
User.select(:id).all.size
=> 103
User.select(:id).all.l... | This is a bug in Rails 4.1. See <https://github.com/rails/rails/issues/13648> | When you use `select` and you have more than one columns for an argument, you need to put it in a string, in this format:
```
User.select("id, email")
```
In other words, the list of columns should only be passed in [pure string](http://guides.rubyonrails.org/active_record_querying.html#pure-string-conditions) format | Rails select() and count() don't seem to play nice | [
"",
"sql",
"ruby-on-rails",
"activerecord",
"ruby-on-rails-4",
"ruby-on-rails-4.1",
""
] |
I executed a Stored Procedure in SQL Server Management Studio 2005 but then i didn't check if the Stored Procedure executed succesfully.
I used below command:
```
exec [Stored Procedure name] '[param1]' , '[param2]'
```
Now, i want to find :
a) if the Stored Procedure executed succesfully
b)what were the results fr... | One other way would be to put the entire body of the sp into an `try-catch` block. At the end of the **try**, `insert into` an audit/log table some values that you are interested in (eg: scope\_identity for inserts, plain text like 'Done!', some time stamps to see when it was ran, etc..) while in the **catch** you do t... | if these are SELECT only, you can only see the output in Result Pane of SSMS or in the application that call the stored procedure. In the server the records will be loaded (cached).
To see what is cached in SQL Server memory, see this page
[What is cached by sql server](https://dba.stackexchange.com/questions/43572/ho... | Find results from execution of stored procedure | [
"",
"sql",
"sql-server",
"sql-server-2005",
"stored-procedures",
"exec",
""
] |
I'm using Oracle SQL and I have two tables:
```
Employee:
VARCHAR VARCHAR
EMP_NUM EMP_NAME
------- --------
1 Jane
1 Jane
1 Jane
1 Jane
2 Alex
2 Alex
2 Alex
3 Danny
3 Danny
Assignment:
NUMBER FLOAT FLOAT VARCHA... | The query should be like this, you need to list all fields in SELECT clause:
```
SELECT
Assignment.EMP_NUM,
Employee.EMP_LNAME,
SUM(Assignment.ASSIGN_HOURS) SUM_HOURS,
SUM(Assignment.ASSIGN_CHARGE) SUM_CHARGE
FROM Employee, Assignment
WHERE Employee.EMP_NUM = Assignment.EMP_NUM
GROUP BY Assignm... | You forgot to include `Employee.EMP_LNAME` in your `GROUP BY` clause.
Code should be:
```
SELECT
Assignment.EMP_NUM,
Employee.EMP_LNAME,
SUM(Assignment.ASSIGN_HOURS) SUM_HOURS,
SUM(Assignment.ASSIGN_CHARGE) SUM_CHARGE
FROM Employee, Assignment
WHERE Employee.EMP_NUM = Assignment.EMP_NUM
GROUP ... | How do I both sum 1 table and combine that result with another? | [
"",
"sql",
"oracle",
""
] |
I'm following the Stanford's Coursera database course, and there's this query I do not understand.
The instructor says that it returns colleges paired with the highest GPA of their applicants.
```
select distinct College.cName, state, GPA
from College, Apply, Student
where College.cName = Apply.cName
and Apply.sID ... | ```
College.cName = Apply.cName
```
This provides the limit to a particular college. Try removing it. | No, because the select statement following the "GPA >= ALL" statement is correlated to the outer clause - they share the same table correlation names "College" "Apply" "Student". That means that you'll effectively get a a look up against the "College" currently being referenced by the WHERE clause - i.e. for College\_A... | Not understanding this SQL query | [
"",
"sql",
"syntax",
""
] |
Now I union 3 table and select become below show.
```
|remark|totalA|totalB|tatalC|
-----------------------------
| a | 123 | NULL | NULL |
| a | NULL | 123 | NULL |
| a | NULL | NULL | 123 |
```
How to let it become 1 row as below show?
```
|remark|totalA|totalB|tatalC|
-----------------------------
|... | ```
select
remark,
sum(totalA) as totalA,
sum(totalB) as totalB,
sum(totalC) as totalC
from the_table
group by remark
``` | Use`sum` along with `group by` as
```
select remark, sum(totalA), sum(totalB), sum(totalC)
from table_name
group by remark
``` | MYSQL - How to let 3 row data become 1 row data | [
"",
"mysql",
"sql",
""
] |
I've got a small issue that I'm not sure how to resolve - I've never encountered it before. I'm using MS SQL and have a SQL JOIN query that queries two tables - Insurance and Creditors. The insurance table holds all the policy details, while the Creditor table holds the company details (Insurance Company/Broker name et... | You just need to use the table alias in the SELECT expression list:
```
SELECT i.sPolicyNumber,
i.dDatePaid,
i.dRenewal,
i.mLastPremium,
c.sCreditorName,
b.sCreditorName
FROM Insurance i
LEFT JOIN Creditor c ON c.lCreditorID = i.lCreditorID
LEFT JOIN Credito... | In you original query, you are refer "Creditor.sCreditorName", however you are using the alias cred in the join.
also, you are using inner joins, which may lead out some entries, in case the FK is null. Eg your entry with lInsuranceID = 1 would be missed out.
A correct query could be
```
SELECT ins.sPolicyNumber,
... | SQL Join Query - two FK, one field | [
"",
"sql",
"sql-server",
"join",
""
] |
In my Rails 4 app, I have the following models:
```
class Person < ActiveRecord::Base
has_many :addresses
end
class Address < ActiveRecord::Base
belongs_to :person
belongs_to :city
end
class City < ActiveRecord::Base
has_many :addresses
end
```
I'm using the `:includes` function to return query result i... | Have you tried this?
```
class Person < ActiveRecord::Base
has_many :addresses
has_many :cities, :through => :addresses
end
class Address < ActiveRecord::Base
belongs_to :person
belongs_to :city
end
class City < ActiveRecord::Base
has_many :addresses
end
```
Then:
```
Person.find(1).cities.pluck(:nam... | Did you try `select`?
```
Address.select(<output_columns>).includes(:person, :city).where("person_id = 1")
``` | Efficient way to return select columns from Rails 4 ActiveRecord nested query | [
"",
"sql",
"ruby-on-rails",
"ruby-on-rails-4",
"scope",
"rails-activerecord",
""
] |
I'll calculate the amount of employee performance:
```
select Job_Id, Sum(money1) as m1 from T1 where Job_Id='8'
group by Job_Id
```
Then I calculated the amount of his salary(in other Table = T2):
```
select Job_Id, Sum(money2) as m2 from T2 where Job_Id='8'
group by Job_Id
```
Now, I will get the following: `m1 -... | I found it:
```
select (select Sum(money1) from T1 where Job_Id='8') -
(select Sum(money2) from T2 where Job_Id='8')
``` | I think this will do what you want:
```
SELECT job, m1-m2 FROM
(
SELECT T1.Job_Id AS job, Sum(money1) as m1, Sum(money2) as m2
FROM T1 LEFT JOIN T2
ON T1.Job_id=T2.Job_id
WHERE T1.Job_Id='8'
group by T1.Job_Id
)
``` | Calculate the credit amount the employee | [
"",
"sql",
"sql-server",
""
] |
I have table article related to another table article\_has\_type
The structure of article table is
```
CREATE TABLE `articles` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`titre` VARCHAR(255) NULL DEFAULT NULL,
`description` TEXT NULL,
)
```
structure for table article\_has\_type is
```
CREATE TABLE `ar... | Since `id` column is `AUTO INCREMENT`, you can do this:
To get the last record in `articles`:
```
SELECT * FROM articles WHERE id=(SELECT MAX(id) FROM articles)
```
To get the details of last records in `arhastypes` for each types:
```
SELECT * FROM arhastypes WHERE id IN
(SELECT MAX(id) FROM arhastype... | Are looking for this?
```
Select * from articles where id in (select max(id) from articles)
Select * from arhastypes where id in (select max(id) from arhastypes)
``` | SQL query to retrieve the last record | [
"",
"sql",
""
] |
I have a table order\_history that is similar to the following:
```
+-------------------------------------------------------------+
| order_history_id | order_id | order_status_id | date_addded |
+-------------------------------------------------------------+
| 1 | 1 | 1 | 2014-03-2... | You can do so ,by joining your tables and count the statues shipped for each order by using expression in sum i.e `SUM(os.name ='shipped') shipped`
```
SELECT o.*
,SUM(os.name ='shipped') shipped
FROM
orders o
LEFT JOIN orders_status os USING(order_status_id)
WHERE o.date_addded < '2014-04-01'
GROUP BY o.order_id
HA... | You can use INNER JOIN with this, if I get what you really want you can try this:
```
SELECT DISTINCT order_id
FROM order_history A
INNER JOIN order_status B
ON A.order_status_id = B.order_status_id
WHERE (A.order_Status_id = '1' AND A.date_added < @date) AND (A.order_status_id = '3' AND A.date_added < @date)
``` | SQL select orders depending on status and date | [
"",
"mysql",
"sql",
"opencart",
""
] |
Using SQL Server 2005 I need to get the `datediff` of 2 dates that are in the same column, table looks like this:
```
OrderNo OpNo ResType LoadedStartDate
-----------------------------------------------------
12345 1 PAINT 2014-05-01 00:00:00.000
12345 2 PAINT 2014-05-02 00:00:... | Just join the table to itself:
```
SELECT t1.OrderNo,DATEDIFF(day,t1.LoadedStartDate,t2.LoadedStartDate)
FROM UnnamedTableFromQuestion t1
INNER JOIN
UnnamedTableFromQuestion t2
on
t1.OrderNo = t2.OrderNo
WHERE t1.OpNo = 1 and
t2.OpNo = 4
``` | Should be pretty straightforward
```
SELECT DATEDIFF(day,
(SELECT LoadedStartDate FROM Orders WHERE OrderNo = 12345 AND OpNo = 1),
(SELECT LoadedStartDate FROM Orders WHERE OrderNo = 12345 AND OpNo = 4)
)
```
Since inner selects return scalar values - they can be used as parameters for DATED... | DateDiff of 2 dates in the same column SQL | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I use SQL Server 2008 .
I try to Make an report and need to calculate a new Column about each row of my table .
I write this function :
```
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date, ,>
-- Description: <... | You may want to try a [table-valued function](http://technet.microsoft.com/en-us/library/ms189294%28v=sql.105%29.aspx) instead:
```
CREATE FUNCTION Calculated_Product_Stock (@toDate DATETIME,
@finYear INT,
@inventoryId INT = NULL)
RET... | I think this will work
```
CREATE FUNCTION [dbo].[usp_CalcProductStock] (
-- Add the parameters for the function here
@ProductID INT = NULL
,@ToDate DATETIME = NULL
,@FinYear INT = NULL
,@InventoryID INT = NULL
)
RETURNS FLOAT
AS
BEGIN
DECLARE @stock FLOAT
DECLARE @DocItems TABLE (
... | How to Optimize this SQL Script | [
"",
"sql",
"sql-server",
"performance",
"sql-server-2008",
"t-sql",
""
] |
I've spent a bit of time trying to bend regex to my will but its beaten me.
Here's the problem, for the following text...
```
--to be matched
UPDATE dbo.table
UPDATE TOP 10 PERCENT dbo.table
--do not match
UPDATE #temp
UPDATE TOP 10 PERCENT #temp
```
I'd like to match the first two updates statements and not match ... | I assume you're trying to parse real SQL syntax (looks like SQL Server) so I've tried something that is more suitable for that (rather than just detecting the presence of `#`).
You can try regex like:
```
UPDATE\s+(TOP.*?PERCENT\s+)?(?!(#|TOP.*?PERCENT|\s)).*
```
It checks for `UPDATE` followed by optional `TOP.*?PE... | As I understand it, you want a regex to interact with SQL code, not actually querying a database?
You can use a negative look ahead to check if the line has `#temp`:
```
(?m)^(?!.*#temp).*UPDATE
```
`(?!...)` will fail the whole match if what's inside it matches, `^` matches the beginning of the line when combined w... | Parse SQL with REGEX to find Physical Update | [
"",
"sql",
"regex",
""
] |
I have list of date in MySQL in the format of "MM-DD-YYYY" and When I was trying to fetch the latest date from table it just return the last date of a Year like `12-01-2014` instead of return latest date `03-16-2016`.
Payment history table:
```
to_date
03-16-2016
12-01-2014
11-07-2014
10-03-2014
01-09-2014
```... | You're working with strings, not native dates, so you're getting the maximum date.
Either convert those strings to ACTUAL mysql date/datetime values, or you'll have to go with ugly hacks, like
```
SELECT MAX(STR_TO_DATE(to_date, '%m-%d-%Y'))
```
and performance will be massively bad. MySQL's native date format is `y... | It sounds like your date column is actually a VARCHAR format since it is seeing 12-01-2014 as the last date which is only true if stored as a VARCHAR.
Be sure your to\_date column is a DATE type. | How to select latest date from database in MySQL | [
"",
"mysql",
"sql",
"max",
""
] |
we implement search on a table like this
```
create proc prcSearchMember
(
@UserId uniqueidentifier,
@MemberFirstName varchar(20),
@MemberMiddleName varchar(20),
@MemberLastName varchar(20),
@FamilyHeadName varchar(50),
@FatherName varchar(50),
@MotherName varchar(50),
@DOB datetime,
@GotraID int,
@SectID int,
@Bl... | Try the following,
```
DECLARE @ColName varchar(126) = 'col_name'
DECLARE @ColVal varchar(64) = 'col_val'
DECLARE @SQL AS nvarchar(MAX)
SET @SQL = ''
SELECT @SQL = @SQL + 'SELECT * FROM ' + IST.TABLE_SCHEMA + '.' + IST.TABLE_NAME
+' where '+ @ColName +' = '''+ @ColVal +''' ' + CHAR(13)
FROM
... | I'm not that sure what it is you're trying to achieve. Are you asking "Is there a beter way fo writing this search?". If so, then yes, absolutely. As far as I can see each `IF` branch selects the same columns so if you make sure all your stored proc arguments are defaulted to `NULL` in the declaration then you can do t... | Search query on multiple columns of a table? | [
"",
"sql",
"sql-server-2008",
"search",
""
] |
Why is there a syntax error near 'for' as SQL Server 2012 reports?
Is not DEFAULT FOR syntax available when creating a table, but when altering it? Here is a tutorial about altering a table and adding a default constraint [link](http://www.tutorialsqlserver.com/Create/Default-Value-in-Sql-Server.htm), but I can't get ... | It's a quirk of the [`CREATE TABLE`](http://technet.microsoft.com/en-us/library/ms174979.aspx) syntax that you can only declare a `DEFAULT` constraint inline, as per [StuartLC's answer](https://stackoverflow.com/a/23366968/15498). You *can* also create table constraints, but these are only:
```
< table_constraint > ::... | Add it immediately after the column definition and lose the `FOR`:
```
IsVege char NOT NULL CONSTRAINT Def_Meal_IsVege DEFAULT 't'
```
[Fiddle here](http://sqlfiddle.com/#!3/1c058) | SQL Server DEFAULT FOR Syntax | [
"",
"sql",
"sql-server",
"default-constraint",
""
] |
How to Write Query to Getting Below Output?
In database:
Table 1:
```
id Company_accountNo
1 123
2 235
3 456
```
Table 2:
```
id cheque_no company_accnopky amount
1 258 1 100
2 963 1 200
3 147 2 500
4 148 3 800
5 8... | Try This:
```
SELECT
T1.Company_accountNo As Account_no,
sum(T2.Amount) As Total_Amount,
count(T1.Company_accountNo) AS No_of_Cheque
FROM Table1 T1 Inner Join Table2 T2 ON T1.id = T2.company_accnopky
Group By T1.Company_accountNo
```
I Think You are Missing **Group By** | ```
SELECT a.Company_accountNo Account_no,
SUM(b.amount) Total_Amount,
COUNT(*) No_of_Cheque
FROM table1 a
LEFT JOIN table2 b
ON a.id=b.company_accnopky
GROUP BY a.Company_accountNo
``` | How to get each total from database? | [
"",
"sql",
"oracle",
"oracle9i",
""
] |
This is my Original Data:
```
Attempt Value Time
1 suspend 1391685762
2 suspend 1391686288
3 suspend 1391686413
4 suspend 1392648082
5 suspend 1392648230
6 suspend 1393255593
7 suspend 1393255953
8 suspend 1393257567
9 suspend 1393257738
9 75 139334184... | You could use a sub query to achieve this result.
```
SELECT Attempt,
min(Value) as Value,
(SELECT Time FROM t as t1
WHERE t1.Value = min(t.Value)
AND t.Attempt = t1.Attempt) as Time
FROM t as t
GROUP BY Attempt
``` | This is the solution I'd go for, which would in my opinion be the fastest:
```
SELECT DISTINCT(`attempt`) as `attempt`,
IF(MAX(`value`)=0,'suspend',MAX(`value`)) as `value`, `time`
FROM(
SELECT `attempt`, IF(`value`='suspend',0,`value`) as `value`, `time`
FROM `t`
) as `a`
GROUP BY `attempt`
``` | SQL picking one record over another | [
"",
"mysql",
"sql",
""
] |
I receive the syntax error message when I try to execute the code shown below
> Msg 156, Level 15, State 1, Line 3
> Incorrect syntax near the keyword 'join'.
> Msg 156, Level 15, State 1, Line 7
> Incorrect syntax near the keyword 'order'.
But when I execute the 2nd query without the brackets () the results ar... | The `where` clause comes after the `from` clause:
```
SELECT faknr, tot_bdr as verkooporderbedrag
FROM [001].[dbo].[frhkrg] faktuur
join
(SELECT SUM(amutas.bedrag) as totaalbedrag_regels,amutak.bkstnr,amutas.reknr,amutas.faktuurnr as faknr
FROM [001].[dbo].[amutak] inner join [amutas] on amutak.bkstn... | Move where clause after the JOIN ON clause and move ORDER BY clause outside subquery
```
SELECT faknr, tot_bdr as verkooporderbedrag
FROM [001].[dbo].[frhkrg] faktuur
join
(SELECT SUM(amutas.bedrag) as totaalbedrag_regels,amutak.bkstnr,amutas.reknr,amutas.faktuurnr as faknr
FROM [001].[dbo].... | SQL Server 2005 returns error when executing a query with a select query as join | [
"",
"sql",
"sql-server",
"syntax-error",
""
] |
Is there any fast way to get rows that are excluded by a query. For instance I run:
```
select * from tblUsers where user_type = 3
```
I'm looking for a fast to get the rows that were excluded by this query.
I understand I can easily change the where clause, but some queries are very complex and take some time to ch... | Dump the results of your super complex query into a temporary table.
ex.
```
create table #Temp
(
First varchar(50),
Last varchar(50)
)
go
select * from #Temp
```
then do a join off the original data to get what you are looking for. | For an actual exclusion, you could do:
```
select * from tblUsers
EXCEPT
select * from tblUsers where user_type = 3
```
But why not just do
```
select * from tblUsers where user_type <> 3
``` | get rows that were excluded by sql query | [
"",
"sql",
"sql-server",
""
] |
I have a SQLite table like this:
```
GroupID UserID
1 1
1 2
1 3
2 4
2 1
```
...and so on. Then, given a list of UserID, I would like to get a groupID that has all those userIDs and only those userIDs.
For example, in this table, given a list (1,2,3), the value returned should be 1. For ... | ```
select GroupID
from your_table
where UserID in (1,2,3)
GROUP BY GroupID
HAVING COUNT(*) = 3
``` | You are a little unclear in the question. Would "1" be returned if the list were 2 and 3?
This is an example of a set-within-sets subquery. The most general and flexible approach is to use aggregation with a `having` clause:
```
select GroupId
from table t
group by GroupId
having sum(case when UserId = 1 then 1 else ... | Select based on WHERE-clause on multiple rows | [
"",
"sql",
"sqlite",
""
] |
I can run the following query in SQL:
```
SELECT TOP 1000 [Sample ID]
FROM [database].[dbo].[table]
```
And it will output a table with values. I want to get the count of row for the table by doing the following:
```
SELECT COUNT([Sample ID]) FROM [database].[dbo].[table] AS [Total]
```
But I get the following erro... | Try this:
```
SELECT COUNT(*) [TOTAL] FROM [database].[dbo].[table]
``` | You probably mean
```
SELECT COUNT([Sample ID]) AS [Total] FROM [database].[dbo].[table]
``` | Why column name is invalid | [
"",
"sql",
"sql-server",
"date",
""
] |
I have a table
```
CREATE TABLE tblHistory
(
ID INT IDENTITY
PRIMARY KEY ,
Added DATETIME ,
value1 INT ,
Value2 INT
)
```
with a lot of history data.
As result I want a maximum of 100 rows but from the beginning to the end.
In this example [SQL Fiddle](http://sqlfiddle.... | If we assume that `id` has no gaps, the following should do what you want, relatively efficiently:
```
select h.*
from tblHistory h cross join
(select count(*) as cnt from tblHistory) as c
where floor(id * 100.0 / cnt) <> floor((id + 1) * 100.0 / cnt);
```
This will select about 100 rows evenly spaced in the dat... | to get every fifth entry try this:
```
select *
from tblHistory
where id % 5 = 0
```
so if you want to get around 100 entries, try something along the lines of this:
```
select *
from tblHistory
where id % (select round(count(*)/100,0) from tblHistory) = 0
```
where you take the number of records in tblHistor... | SQL Server 2005: Selecting number of data from a History (From start to end max 100 results) | [
"",
"sql",
"sql-server",
""
] |
I know how left join working for two tables, but how does it work for three (or more ) tables ?
```
SELECT col FROM table1 t1
LEFT JOIN table2 t2 ON t1.col = t2.col
LEFT JOIN table3 t3 ON t1.col = t3.col
LEFT JOIN table4 t4 ON t1.col = t4.col
-- ...
WHERE ...
```
How to interpret this statem... | There are different ways you can configure LEFT JOIN when you have 4 tables.
### Query 1
In the question you have (more or less):
```
SELECT t1.col, t2.info2, t3.info3, t4.info4
FROM table1 t1
LEFT JOIN table2 t2 ON t1.col = t2.col
LEFT JOIN table3 t3 ON t1.col = t3.col
LEFT JOIN table4 t4 ON t1.col = ... | When you use multiple LEFT JOIN like you post you have to interpret this as the possibility of null values on the tables. In your example, for your query to return values only Table1 needs to have records. You could have empty table2, table3 and table4 and your query will return values anyway. Take this query for insta... | How to understand A Left join B on .... Left join C on..? | [
"",
"sql",
"left-join",
""
] |
I have a table containing information about records. There can be several drafts of each record. To query the info for the highest draft I currently do:
```
select
record_id,
record_name,
record_date
from
RECSTABLE
where
record_number = XXXXX
AND record_draft = (select max(record_draft)
... | How about something like this:
```
SELECT RECORD_ID,
RECORD_NAME,
RECORD_DATE
FROM RECSTABLE r
INNER JOIN (SELECT RECORD_NUMBER,
MAX(RECORD_DRAFT) AS MAX_RECORD_DRAFT
FROM RECSTABLE
GROUP BY RECORD_NUMBER) m
ON (m.RECORD_NUMBER = r.RECORD_NUMBE... | Don't use analytic functions for this, but use [LAST](http://docs.oracle.com/cd/E16655_01/server.121/e17209/functions090.htm#SQLRF00653) aggregate function, because it's [faster](http://rwijk.blogspot.nl/2012/09/keep-clause.html).
Something like this:
```
select max(record_id) keep (dense_rank last order by record_... | Oracle 10g - SQL - Optimise query and call recursively | [
"",
"sql",
"oracle",
""
] |
I have two tables.
Videos;
ID,
Artist,
Title
runlog;
VideoID, 'joins to videos.ID
datetime
I'd like to run a query on the Videos table excluding records on three conditions. (as examples. I have multiple conditions, but if I get some help on these, I can probably figure everything else out.
* Any video that shows u... | This query enforces your latter two constraints explicitly and the first implicitly (enforcing the second implicitly enforces the first). It's untested but it should get you on the right track.
```
select ID, Artist, Title
from Video
where Artist not in (
select V.Artist
from Video V, Runlog R
where V.ID = R.Vid... | ```
SELECT ID, Artist, Title
FROM videos v join runlog l on l.videoID = v.id
WHERE
-- 1. All in past hour will not show
datetime < DATEADD(hour,-1,GETDATE())
-- 2.
and not exists
( select 1
from videos v2 join runlog l2 on l2.videoID = v2.id
where v2... | Exclude records from query based on table join results | [
"",
"sql",
"sql-server",
""
] |
In my sqlplus (for oracle) command line, the backespace doesn't work. How could I configure sqlplus for deleting characters from the command line with backspace? I don't use frequently sqlplus command line, only for making quickly interventions in my DB, it is very hazard for me the times I need to use.
Kind Regards. ... | which platform are you working on?
in case it's linux, have a look at [this section of a wikipedia article on the bash](http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29#Keyboard_shortcuts) for some keyboard shortcuts. you should be able to navigate the sqlplus command line with the same shortcuts when you call sqlpl... | Following the instructions [here](http://www.beyondoracle.com/2008/10/22/improve-sqlplus-before-you-get-crazy/) I was able to do the following and get this working:
1. Type `stty erase` in the terminal
2. Press `CTRL+v` on your keyboard
3. Press the `Backspace Key` on the keyboard (when I did this it put `^H` on the l... | Backspace doesn't work in sqlplus command line | [
"",
"sql",
"oracle",
"sqlplus",
""
] |
The only examples I can find addressing this sort of scenario are pretty old, and I'm wondering what the best way is to do this with the latest version of ORMLite...
Say I have two tables (simplified):
```
public class Patient
{
[Alias("PatientId")]
[Autoincrement]
public int Id { get; set; }
public strin... | An alternate more succinct example:
```
public void Put(CreatePatient request)
{
var patient = new Patient
{
Name = request.Name,
Insurances = request.Insurances.Map(x =>
new Insurance { Policy = i.Policy, Level = i.Level })
};
db.Save<Patient>(patient, references:true);
}
``` | References are here to save the day!
```
public class Patient
{
[Alias("PatientId")]
[Autoincrement]
public int Id { get; set; }
public string Name { get; set; }
[Reference]
public List<Insurance> Insurances { get; set; }
}
public class Insurance
{
[Alias("InsuranceId")]
[Autoincrement]
pub... | One-to-Many relationship with ORMLite | [
"",
"sql",
"json",
"ormlite",
"ormlite-servicestack",
""
] |
```
Level1 | Level2 | Level3 | Level4
key | value | key |value | key | value | key | value
---------------------|----------------|---------------------|-----------------
setting1 | true | | setting1 | true |setting1 | false
... | One approach would be to use CASE - WHEN structure.
See this [SQLFiddle](http://sqlfiddle.com/#!12/560b2/1)
```
SELECT CASE WHEN t1."key" IS NOT NULL
THEN t1."key"
ELSE CASE WHEN t2."key" IS NOT NULL
THEN t2."key"
ELSE CASE WHEN t3."key" IS NOT NULL
... | You want [DISTINCT ON](http://www.postgresql.org/docs/9.3/static/sql-select.html) with UNION ALL (although a straight UNION would work here too)
```
BEGIN;
CREATE TEMP TABLE settings1 (key text, value text, PRIMARY KEY (key));
CREATE TEMP TABLE settings2 (key text, value text, PRIMARY KEY (key));
CREATE TEMP TABLE se... | How to write postgres query for below issue? | [
"",
"sql",
"postgresql",
"select",
""
] |
For my database, having these four table
First one, DEPARTMENT
```
//DEPARTMENT
D# DNAME
------------------
1 RESEARCH
2 IT
3 SCIENCE
```
Second one, EMPLOYEE
```
//Employee
E# ENAME D#
-----------------------
1 ALI 1
2 SITI 2
3 JOHN ... | You should use an left join like this. You only need 2 tables `employee` and `workson`.
Try this query:
```
SELECT e_tbl.E#, e_tbl.ENAME, e_tbl.D#,
coalesce(SUM(w_tbl.Hours), 0) as "Total Hours/W"
FROM
EMPLOYEE e_tbl LEFT JOIN WORKSON w_tbl
ON e_tbl.E# = w_tbl.E#
GROUP BY e_tbl.E#
``` | You need to use GROUP BY and JOINS , in order to achieve your output | SELECT sql with four different tables with primary key and foreign key | [
"",
"mysql",
"sql",
"sql-server",
"oracle",
""
] |
I have the following table:
```
Date Value
4/13/2014 25
4/14/2014 35
4/15/2014 30
4/16/2014 25
4/17/2014 21
4/18/2014 20
4/19/2014 42
4/20/2014 54
4/21/2014 44
4/22/2014 47
4/23/2014 48
4/24/2014 34
4/25/2014 32
4/26/2014 18
4/27/2014 20
4/28/2014 ... | If I understand your question correctly, you'd like to get the `SUM` of the `Value` field within the timespan of the last Sunday-Saturday. Since you said that the table is updated daily, I'll assume that you mean the last *actual* week, and not just the last week that happens to be in the DB.
Here's one query that sum... | For Oracle you could try. IW - week number in a year, according to ISO standard:
```
SELECT to_char( Date , 'IW' ), SUM (Value)
FROM TableA
GROUP BY to_char( Date , 'IW' );
``` | How to get the last week date from Sunday to Saturday | [
"",
"sql",
"date",
""
] |
I have an event system and for my repeat events I am using a cron like system.
Repeat Event:
```
+----+----------+--------------+
| id | event_id | repeat_value |
+----+----------+--------------+
| 1 | 11 | *_*_* |
| 2 | 12 | *_*_2 |
| 3 | 13 | *_*_4/2 |
| 4 | 14 | 23_*_... | You could put a bandaid on this, but no one would be doing you any favors to tell you that that is the answer.
If your MySQL database can be changed I would strongly advise you to split your current column with underscores `day_month_day of year` to three separate columns, `day`, `month`, and `day_of_year`. I would al... | Try to write where condition using this:
```
substring_index(repeat_value,'_', 1)
```
instead of daily
```
substring_index(substring_index(repeat_value,'_', -2), '_', 1)
```
instead of monthly
and
```
substring_index(substring_index(repeat_value,'_', -1), '_', 1)
```
instead of dayOfWeek | mysql split a string in a where clause | [
"",
"mysql",
"sql",
""
] |
Say I have an table like this:
```
DROP TABLE tmp;
CREATE TABLE tmp (id SERIAL, name TEXT);
INSERT INTO tmp VALUES (1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five');
SELECT id, name FROM tmp;
```
It's like this:
```
id | name
----+-------
1 | one
2 | two
3 | three
4 | four
5 | five
(5 row... | To preserve the array order, it needs to be unnested with the index order (using `row_number()`), then joined to the `tmp` table:
```
SELECT array_agg(name ORDER BY f.ord)
FROM (
select row_number() over() as ord, a
FROM unnest(ARRAY[3, 1, 2]) AS a
) AS f
JOIN tmp ON tmp.id = f.a;
array_agg
-----------------
... | Use `unnest` function:
```
SELECT id, name FROM tmp
WHERE id IN (SELECT unnest(your_array));
```
There is a different technique as suggested by Eelke:
You can also use the `any` operator
```
SELECT id, name FROM tmp WHERE id = ANY ARRAY[3, 1, 2];
``` | How to SELECT by an array in postgresql? | [
"",
"sql",
"postgresql",
""
] |
I have a stored procedure that is run by the SQL Agent every x minutes. The stored procedure has a while loop that reads each row and does something with them.
I want to handle errors as they occur in the while loop. I need to use `Throw` in the `CATCH` block because then SQL Server Agent will not notify if an error o... | Replace your THROW with CONTINUE; this way the next record will be processed without Canceling the code.
(EDITED!)
since you log your errors with
```
EXEC dbo.LogError @Description;
```
i think you don't need to rethrow the error. Since you stated you don't want the program to end.
example of CONTINUE:
```
DECLAR... | Your `THROW` raises an exception which causes the SP to stop processing. Essentially you are catching any errors that occur but rethrowing them which will indeed break out of the `while` loop.
Remove it and the sp should then just continue as normal. | SQL Server Try Catch | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a problem with closing the SQLconnection in my application. My application is in VB.net. I have a reference in my application to a class with code to open and close the database connection and to execute all sql scripts.
The error occurs when i close my application. In the formClosing event of my main form I ca... | Thanks for your help. I finally solved the problem. All my code was executed in the FormClosing event of my form. But now i've separated the code in two pieces. The piece of code I left in the FormClosing event is the call of the delete function. I moved the code that called the function to close the database connectio... | I believe that you have two problem which have both been answered. Handling the connection and the formClosing event firing.
I see that "myConnection" and "myCommand" as not locally scoped. This objects should be not be held at class level (your form). You should open your connection in a using block and let the conne... | Error while closing SQL Connection | [
"",
"sql",
"sql-server",
"vb.net",
""
] |
Suppose I have a list of values, such as `1, 2, 3, 4, 5` and a table where some of those values exist in some column. Here is an example:
```
id name
1 Alice
3 Cindy
5 Elmore
6 Felix
```
I want to create a `SELECT` statement that will include all of the values from my list as well as the information from tho... | If in Microsoft SQL Server 2008 or later, then you can use [Table Value Constructor](http://technet.microsoft.com/en-us/library/dd776382.aspx)
```
Select v.valueId, m.name
From (values (1), (2), (3), (4), (5)) v(valueId)
left Join otherTable m
on m.id = v.valueId
```
Postgres also has this constructio... | the following solution for oracle is adopted from [this source](http://rebustechnologies.com/convert-a-csv-string-into-rows-using-oraclesql/). the basic idea is to exploit oracle's hierarchical queries. you have to specify a maximum length of the list (100 in the sample query below).
```
select d.lstid
, t.... | Joining a list of values with table rows in SQL | [
"",
"sql",
"sql-server",
"oracle",
""
] |
I am working on a simple SQL query in SQL Developer and I can't seem to get this one right. My query is: "Retrieve the names of all the tutors that have had *all their* appointments with 'place name here'"
Here is my SQL:
```
SELECT Appt.TUTOR_USER_ID, TUTORS.FIRST_NAME, TUTORS.LAST_NAME
FROM Appt,
(
SELECT Tut... | You are only looking for records that match that name, so there is currently nothing to count or exclude anything else. You could add a `and not exists` clause that queries for any other students; or since it's in your question title, a `minus` that does the same:
```
select a.tutor_user_id, tu.first_name, tu.last_nam... | Another way to go is to first filter the appointments to get the ones where the tutor only see a student, and use it as base for the main query
```
WITH tutor_appt As (
SELECT tutor_user_id
, MAX(student_user_id) student_user_id
FROM appt
GROUP BY tutor_user_id
HAVING COUNT(DISTINCT student_user_id) =... | SQL Query Select or Minus Help SQL Developer | [
"",
"sql",
"oracle",
"select",
"join",
"oracle-sqldeveloper",
""
] |
I have table `dbo.Students_Old` with columns :
> Name(varchar), DocNum(int), Group(varchar), Form(varchar).
It have no primary key and I need to normalize this table. So I am going to make three tables:
> dbo.Students(StudentId(int primary key), Name(varchar), Group(int fk),
> Form(int fk),
>
> dbo.Forms(FormId(int ... | Execute the below query on a new database
```
CREATE TABLE dbo.Groups(GroupId int IDENTITY(1,1) PRIMARY KEY, GName nvarchar(10));
GO
INSERT INTO dbo.Groups(GName)
select Group
from dbo.Students_Old
group by Group
GO
CREATE TABLE dbo.Forms(FormId int IDENTITY(1,1) PRIMARY KEY, Form nvarchar(20));
INSERT INT... | Not sure if that is the case, since you get the FOREIGN KEY error, but try avoiding column names like GROUP or other reserved words. While you can avoid errors on table creation step, you can face serious problems during modifications/updates on such tables. | Insert statement error | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I'm having an issue coming up with an SQL statement. CANNOT get my head around multi table interaction in MySQL.
So I have 2 tables:
This is my `users` table:

This is my `messages` table:

contacts
ON users.users_userid = contacts.user_i... | ```
SELECT users_name,users_university
FROM users
WHERE users_userid IN (SELECT messages_senderid
FROM messages WHERE messages_receiverid=1)
OR users_userid IN (SELECT messages_receiverid
FROM messages WHERE messages_senderid=1)
```
Another method
```
SELECT users... | INNER JOIN? Two table joining of userid with other userid | [
"",
"mysql",
"sql",
""
] |
I have a query in which date is in 'YYYY-MM-DD' format, and I am looking to sort this. So, I used
```
SELECT DATE_FORMAT(AudiEvent.EventDate,'%d-%m-20%y') as Event_Date
from AudiEvent
ORDER BY Event_Date
```
Actual Output -
```
Event_Date
06-12-2013
09-11-2013
18-12-2013
26-11-2013
```
Expected Output -
```
Event_... | You need to add `AudiEvent` before EventDate
```
SELECT DATE_FORMAT(AudiEvent.EventDate,'%d-%m-20%y') as Event_Date
from AudiEvent
ORDER BY AudiEvent.EventDate
``` | Please use `AudiEvent.EventDate` date field in sorting
```
SELECT DATE_FORMAT(AudiEvent.EventDate,'%d-%m-20%y') as Event_Date
from AudiEvent
ORDER BY AudiEvent.EventDate
``` | Sorting the date in ascending order | [
"",
"mysql",
"sql",
""
] |
My table has one record per employee per year. How do I select one record per employee getting the latest year for that employee?
Columns are `employee_ref, firstname, lastname, employment_year`.
Each `employee_ref` will have several records, each with different values of `employment_year`
I want to select one recor... | You can do this with a sub-selected:
```
SELECT employee_ref, firstname, lastname
FROM table
WHERE employment_year = (
SELECT MAX(employment_year)
FROM table b
WHERE b.employee_ref = table.employee_ref)
``` | Something like this should work.
```
select firstname, lastname, maxyear
from table join (
select employee_ref, max(employment_year) maxyear
from table
group by employee_ref) temp on table.employee_ref = temp.employee_ref
and employment_year = maxyear
``` | Table has one record per employee per year. How do I select the record for each employee for the latest year for that employee? | [
"",
"sql",
""
] |
I am not an expert in sql.
My wordpress started to return timeouts and respond really slow.
when I started digging, I noticed that the slow\_query log has a lot to tell me.
unfortunately I have a lot of slow queries.
for example:
```
# Time: 140425 17:03:29
# User@Host: geektime[geektime] @ localhost []
# Query_time: ... | > however, the columns ID and GUID are indexed twice, is it bad?
There are two different columns, so no, unless you're meaning that both have *two* indexes on them — in which case yes, it's bad and likely a bug in one of your theme or plugins (or a prior bug in WP itself).
> and there are 4 indexs with the same key\_... | Among other things, slow performance is caused by the use of functions like this:
```
AND CAST(wp_postmeta.meta_value AS CHAR) BETWEEN '2014-04-11' AND '2014-04-17')
```
Assuming that field is a date field, you will get better performance with something like this:
```
and wp_postmeta.meta_value >= AStartDateVariabl... | mysql slow queries and timeout in wordpress | [
"",
"mysql",
"sql",
"wordpress",
"indexing",
""
] |
I am trying to retrieve names and address of all guests with bookings for a hotel in London, alphabetically ordered by name in MySQL using subqueries and getting this Error:
```
Error Code: 1242. Subquery returns more than 1 row
```
Here's the query that I run:
```
select * from guest
where guest_no =
(
... | why not use join as
```
select
g.guest_no,
g.g_name,
g.g_address
from guest g
inner join booking b on b.guest_no = g.guest_no
inner join hotel h on h.hotel_no = b.hotel_no
where h.city = 'London'
``` | When you use '=', it means that the result of your subquery is exactly 1 row. If you expect multiple results, you need to use the `IN` keyword, like so:
```
select * from guest where guest_no IN (select guest_no from booking where hotel_no IN (select hotel_no from hotel where city = 'London'));
```
EDIT: As @flaschen... | MySQL subquery on multiple tables | [
"",
"mysql",
"sql",
""
] |
I have the following table
| ID | Name | CodSituation |
| --- | --- | --- |
| 1 | John | 1 |
| 2 | Mary | 2 |
| 3 | Mary | 3 |
| 4 | Mary | 4 |
| 5 | John | 5 |
| 6 | John | 2 |
| 7 | Mary | 1 |
I want to select the Names, ID's and CodSituation for all users where their last entry is CodSituation=2
In these results ... | I found an easier way concatenating fieds and using max solve this problem... Thanks!
```
SELECT
right(
max(
right(('0000000' + CONVERT(varchar,id) + '-'+ convert(varchar,codsituation)),4)),10),
name
FROM TABLE_NAME
GROUP BY name
HAVING
right(
max(
right(
('0000000' + CONVERT(varchar,id) + '-'+ convert(varchar,cod... | [FINAL EDIT]
After seeing what was posted at the end of this answer I figured out that the user was asking the wrong question:
What they were asking was 'show me everyone who has CodSituation=2' when they meant 'Show me all the users who's last entry in CodSituation field=2'
Here is the correct query for that:
```
s... | SQL Select list of last records with condition | [
"",
"sql",
"sql-server",
""
] |
I have `Table 1`:
```
ID UserString Date
-------------------------
1 KRBS 4/25/2014
2 WEFG 4/24/2014
```
And `Table 2`:
```
ID UserString + Other user info
----------------------------------
1 KRBS + . . .. .
```
I'm preforming insert into Table 1 but I would like to ma... | Best way to achieve this is to define a `FOREIGN KEY` on the table. This is the simplest and most implicit way to do it, some reference on that can be found on [MSDN](http://technet.microsoft.com/en-us/library/ms190273%28v=sql.105%29.aspx). That means you will not ever be able to a) insert an entry to this table if no ... | try this on mysql:
```
if {{ userId }} in (select UserString from Table2 where UserString = {{ userId }}) then
insert into Table1 (ID, UserString, Date) values ({{ id }}, {{ userId }}, '{{ date }}')
end if
```
or this on sql server
```
if {{ userId }} in (select UserString from Table2 where UserString = {{ userI... | SQL Insert - Only insert on this condition | [
"",
"sql",
"sql-server",
"database",
"insert",
""
] |
Let's say I have a table with 1,000,000 rows and running a `SELECT * FROM TableName` on this table takes around 10 seconds to return the data.
*Without* a NOLOCK statement (putting to one side issues around dirty reads) would this query lock the table for 10 seconds meaning that no other process could read or write to... | The `NOLOCK` table hint will cause that no shared locks will be taken for the table in question; same with `READUNCOMMITTED` isolation level, but this time applies not to a single table but rather to everything involved. So, the answer is 'no, it won't lock the table'. Note that possible schema locks will still be held... | Your query will try to obtain a table level lock as you're asking for all the data. So yes it will be held for the duration of the query and all other processes trying to acquire Exclusive locks on that table with be put on wait queues. Processes that are also trying to read from that table will not be blocked.
Any di... | Understanding the NOLOCK hint | [
"",
"sql",
"sql-server",
"transaction-isolation",
"nolock",
""
] |
Considering the following table
```
+-----+-----+-----+-----+-----+-----+
|Col01|Col02|Col03|Col04|Col05|Col06| <===header
+-----+-----+-----+-----+-----+-----+
|data1|data2|NULL |hi |Hello|Folks| <===a row
+-----+-----+-----+-----+-----+-----+
```
Now I would like to have a query which returns the name of colu... | Would something like this do?
```
select case
when col01 is null
then 'col1'
when col02 is null
then 'col2'
when col03 is null
then 'col3'
when col04 is null
then 'col4'
when col05 is null
then 'col5'
else null
end
which_col
fro... | This will return row for each column in your table that has null value.
```
SELECT 'Col1' FROM MyTable WHERE col1 IS NULL
UNION ALL
SELECT 'Col2' FROM MyTable WHERE col2 IS NULL
UNION ALL
SELECT 'Col3' FROM MyTable WHERE col3 IS NULL
``` | Query for retrieving columns with null value | [
"",
"sql",
"postgresql",
""
] |
I have two tables:
```
create table xyz
(campaign_id varchar(10)
,account_number varchar)
Insert into xyz
values ( 'A', '1'), ('A', '5'), ('A', '7'), ('A', '9'), ('A', '10'),
( 'B', '2'), ('B', '3'),
( 'C', '1'), ('C', '2'), ('C', '3'), ('C', '5'), ('C', '13'), ('C', '15'),
('D', '2'), ('D', '9')... | I think what you are after is a inner join. Not sure from your questions which way around you want your data. However this should give you a good clue how to procede and what keywords to lock for in the documentation to go further.
```
SELECT a.*
FROM xyz a
INNER JOIN abc b ON b.account_number = a.account_number;
```
... | ```
SELECT campaign_id
FROM (
SELECT campaign_id, COUNT(*) AS c, total_accounts
FROM xyz
JOIN abc ON xyz.account_number = abc.account_number
CROSS JOIN (SELECT COUNT(*) AS total_accounts
FROM abc) AS x
GROUP BY campaign_id
HAVING c = total_accounts) AS subq
```
[DEMO](http://www... | SQL - ALL, Including all values | [
"",
"sql",
"sap-iq",
""
] |
I have this sql query and this takes very long time to finish. How can i speed this up?
t\_inter\_specises\_interaction has 60k rows and t\_pathway has 100k. uniprot\_id\_1,uniprot\_id\_2,uniprot\_id are varchar types.
In this query, i want to select uniprot\_id\_1 and uniprot\_id\_2 which are both present in t\_path... | The subqueries are identical, therefore they can be merged into one, and moved to a join
```
SELECT DISTINCT i.uniprot_id_1, i.uniprot_id_2
FROM t_intra_species_interaction i
INNER JOIN t_pathway p ON p.uniprot_id IN (i.uniprot_id_1, i.uniprot_id_2)
```
**Second query**
It would have be better to open a n... | You may want to use INNER JOIN:
```
select distinct uniprot_id_1,uniprot_id_2 from t_intra_species_interaction i
inner join t_pathway p1
on p1.uniprod_id = t.uniprot_id_1
inner join t_pathway p2
on p2.uniprod_id = t_uniprot_id_2
``` | More Efficient Way For SQL IN Clause | [
"",
"mysql",
"sql",
"performance",
""
] |
I have two tables friends and birthdays.
birthdays schema: userid and birthday\_date
friends schema: userid and userid2.
How can I find out the friends of the people who have a birthday day today?
I am thinking something like this:
```
SELECT *
FROM friends
WHERE userid2 IN
(SELECT userid
FROM birthdays
... | TO make the query faster you need proper index on both tables in conjunction with the JOIN.
Here is an example
```
create table birthdays (userid int,birthday_date varchar(20));
insert into birthdays values (1,'1980-01-01');
insert into birthdays values(2,'1980-01-02');
insert into birthdays values(3,'1980-01-03');
i... | Try Below Query Example
```
SELECT friends.*
FROM friends inner join birthdays on friends.userid2 = birthdays.userid
WHERE birthdays.birthday_date='05/02/2014'
```
Always use `datetime` datatype for date values. | Simple mysql join for specific date | [
"",
"mysql",
"sql",
""
] |
```
SELECT * FROM products WHERE name LIKE '%a%'
```
This works fine when case sensitive, but how to search case insensitively?
Thx ahead | Simple answer:
```
SELECT * FROM products WHERE lower(name) LIKE '%a%'
``` | ```
SELECT * FROM products WHERE nam LIKE BINARY '%a%'
```
`collate` option can also be used and [here](http://dev.mysql.com/doc/refman/5.0/en/charset-collate.html) is how to make it case sensitive from mysql tutorial. | In SQL how to check if a string contains a substring in(case insensitive)? | [
"",
"sql",
"psql",
""
] |
Say we have this value in a column
```
<color="blue" size="5"><color="red">
```
How do I replace the "red" with blue using a SQL statement?
(the value dynamic so using regular REPLACE won't do)
I'm really puzzled by how to solve it. | [`REGEXP_REPLACE`](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions130.htm) uses regular expressions to allow you to specify a *pattern* you wish you replace in a given string. Since your two `color` tags differ in structure, you can take advantage of this to specify a pattern which matches the second in... | I would play around with [substrings](http://technet.microsoft.com/en-us/library/ms187748.aspx) and [patindex](http://technet.microsoft.com/en-us/library/ms188395.aspx).
```
DECLARE @COLOR varchar(20),
@YOUR_VALUE varchar(100)
SET @YOUR_VALUE = SUBSTRING(@YOUR_VALUE, 8, LEN(@YOUR_VALUE))
SET @COLOR = SUBSTRING(@YOUR... | Select column modification | [
"",
"sql",
""
] |
I would like to select `1` if current date falls between 2 dates through Oracle SQL.
I wrote an SQL after reading through other questions.
[https://stackoverflow.com/questions/2369222/oracle-date-between-query](https://stackoverflow.com/questions/2369222/oracle-date-between-query "Oracle date “Between” Query")
[http... | You don't need to apply `to_date()` to `sysdate`. It is already there:
```
select 1
from dual
WHERE sysdate BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND TO_DATE('20/06/2014', 'DD/MM/YYYY');
```
If you are concerned about the time component on the date, then use `trunc()`:
```
select 1
from dual
WHERE trunc(sysd... | ```
SELECT to_char(emp_login_date,'DD-MON-YYYY HH24:MI:SS'),A.*
FROM emp_log A
WHERE emp_login_date BETWEEN to_date(to_char('21-MAY-2015 11:50:14'),'DD-MON-YYYY HH24:MI:SS')
AND
to_date(to_char('22-MAY-2015 17:56:52'),'DD-MON-YYYY HH24:MI:SS')
ORDER BY emp_login_date
``` | Check if current date is between two dates Oracle SQL | [
"",
"sql",
"oracle",
"date",
"between",
"sysdate",
""
] |
i have one `SQL table` in which many records, i want to know how many names are in it and how much time one name in it.
Table NameMst
```
Name
john,smith,alax,rock
smith,alax,sira
john,rock
rock,sira
```
I want to find how much name are there and count of its.
expected output should be like this
```
Name ... | ```
SELECT y.Name, count(*) Count
FROM
(VALUES
('john,smith,alax,rock'),
('smith,alax,sira'),
('john,rock'),
('rock,sira')) x(names)
CROSS APPLY
(
SELECT t.c.value('.', 'VARCHAR(2000)') Name
FROM (
SELECT x = CAST('<t>' +
REPLACE(x.names, ',', '</t><t>') + '</t>' AS XML)
) a
CROS... | You can extract the names using a recursive CTE and some string parsing. The rest is just aggregation:
```
with cte as (
select (case when names like '%,%'
then left(names, charindex(',', names) - 1)
else names
end) as name,
(case when names like '... | split comma seprate value from table in sql server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2012",
""
] |
Just found out that this query:
```
SELECT 1 / 1000000;
```
will return `0`, which is a small catastrophe for our economical program when doing vat calculations. How to set the default number of decimals without changing every query?
**Edit**
The example at hand is to get the vat part from a net value, with 6% vat.... | As documented under [Arithmetic Operators](http://dev.mysql.com/doc/en/arithmetic-functions.html):
> In division performed with [`/`](http://dev.mysql.com/doc/en/arithmetic-functions.html#operator_divide), the scale of the result when using two exact-value operands is the scale of the first operand plus the value of t... | You can cast result to any data type. Below sql cast the result to decimal with precision 10.
```
select cast(1 / 1000000 as decimal(10,10));
```
**EDIT:**
Result depends on your data types. Try this:
SELECT 6.000000 / 106.000000;
If your data is decimal with required precision then your result will be decimal with... | MySQL, change default rounding to more than four digits | [
"",
"mysql",
"sql",
"precision",
""
] |
this is my first time asking a question on here, and I can usually find what I need just from seaching, however this time I'm stuck and I'm hoping someone here can help.
Here's the gist. I have created a database for a hair dressing studio. there are five tables. The only one's this question deals with is the Customer... | `UNION` your two queries together.
Then you'll have a table with all the costs.
From then you can treat that as the source for a new query, to total up these results
```
SELECT customer_ID, first_name, last_name, sum(hc_sales_total) as totalsales
FROM
(
SELECT c.customer_ID, c.first_Name, c.last_name,
SUM(h... | If you want all three sums, you can do this using a `union all`/`group by` approach:
```
SELECT c.customer_ID, c.first_Name, c.last_Name,
SUM(hp.hc_sales) as hp.hc_sales_total, SUM(hp.ps_sales) as hp.ps_sales_total,
SUM(hp.hc_sales_total + hp.ps_sales_total) as Total
FROM ((SELECT hc.customer_ID, hc.cost... | SQL total spent per customer | [
"",
"sql",
"sql-server",
"sqlite",
""
] |
I want data from past 1 year, for example today is 02-05-2014, i need data from May 2013, June 2013..till April 2014 as separate columns. If anybody can help with this code in t-sql that will be very helpful for me. Thanks
ok here i want the data. below is my column
```
created date
------------
02-05-2013
16-05-2013... | Although everyone was quick to suggest using `PIVOT`, that really won't work here because `PIVOT` would need to aggregate each column into one (max, min, whatever) date for that month and year.
I gave this question some attention because it was actually an interesting challenge. The reality is, this is best done by so... | Here is a way to do it without a dynamic pivot. I only did it for 2013, you can see what is needed to add more columns:
(working fiddle: <http://sqlfiddle.com/#!6/d9797/1>)
```
with nums as
(
select [create date],
MONTH([create date]) as M,
ROW_NUMBER() OVER (ORDER BY [create date] ASC) as RN
fr... | how can I get data from every month from past one year in t-sql and each month should be in different column | [
"",
"sql",
"sql-server",
""
] |
I am trying to calculate values in a column called Peak, but I need to apply different calculations dependant on the 'ChargeCode'.
Below is kind of what I am trying to do, but it results in 3 columns called Peak - Which I know is what I asked for :)
Can anyone help with the correct syntax, so that I end up with one c... | You want a `case` statement. I think this is what you are looking for:
```
Select Chargecode,
(case when chargecode = '1'
when chargecode = '1242' then 2
else 2 * Peak
end) as Peak,
CallType
from Daisy_March2014;
``` | Thanks Gordon, I have marked you response as Answered. Here is the final working code:
```
(case when chargecode in ('1') then 1 when chargecode in ('1264') then 2 else Peak*2 end) as Peak,
``` | SQL sub query logic | [
"",
"sql",
""
] |
I have three separate tables which stores data.
**Table1 (executes and stores weekly. use data from last week (e.g. 4/27 to 5/3))**:
```
Date Value1 Value2
5/3/2014 56 13
5/10/2014 12 25
5/17/2014 90 52
5/24/2014 82 36
5/31/2014 76 98
6/7/2... | To make sure you get all the months you need to have a reference table -- here I use a CTE but you could just make the table. You could also use a recursive CTE to build the table based on input instead of hard coding the values as I did here.
Note I'm using the technique that Gordon mentioned to join all the data tog... | This query lists the YEAR, MONTH, and totals for VALUE#s.
Even though the query may be long, it would run very quickly, because the joins operate on a smaller subset of Table1, Table2, and Table3 (because they are first filtered). Then, they are joined using the Month and Year parts of the Date column. Finally, the da... | How to get monthly data from three separate table | [
"",
"sql",
"sql-server",
"date",
""
] |
I have an entries table: id, name
Users can enter as many times as they want.
I want to retrieve the total of users who have entered 2 times.
So if the table looked like this:
```
user_id name
------- ----
3 chuck
4 larry
5 george
3 chuck
4 larry
```
The query would retu... | Try This:
```
select user_id , count(name) as c from table_name GROUP BY user_id having count(*) = 2
```
[**SQL FIDDLE**](http://sqlfiddle.com/#!2/1ab3de/7) | use `count(*)` method
```
select userid,count(*) as count
from (select count(*) as c,userid
from entries
here c>=2 group by user_id)
as dummy_table
``` | total of entries where record/row count equals 2 | [
"",
"mysql",
"sql",
""
] |
I want to search a column for all instances of a string
For example, if I have this a column with the value `all good all bad all better` I want to find the number of instances of `all`.
I tried
```
select instr(column, 'all') from test_table;
```
but that only returns the position of the first occurrence of `all`.... | Since you're on 11g, you can use the [`regexp_count` function](http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions135.htm#SQLRF20014). If you want to do a case-sensitive count
```
SELECT regexp_count( column, 'all' )
FROM table_name
```
If you want a case-insensitive count
```
SELECT regexp_count( colu... | ```
SELECT REGEXP_COUNT(column, 'all') AS Cnt
FROM test_table;
``` | Finding all instances of a word in a string with SQL | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
My below tables are excel sheet data converted as access table using VBA. I'm sorting the data where *EID<>7006* or *EID<>3456* i.e sorting all column data but not either EID=7006 or EID=3456. But sometimes EID=7006 won't present in the table based on the excel file i convert.
Table1 has EID=7006 and EID=3456
```
D... | Looks like your issue is using OR when you mean AND
```
SELECT Description,EID,Basecode from table2 where EID<>7006 AND EID<>3456
``` | A *slightly* cleaner query would be:
```
SELECT Description, EID, Basecode
FROM table2
WHERE EID NOT IN (7006, 3456)
``` | Sorting specified data in WHERE clause access sql | [
"",
"sql",
"ms-access-2010",
""
] |
I have a table in SQL Server called `Personal_Info`. Tthis table has a column called `Vol_ID` and the `(Is Identity)` property is `Yes`.
Now I inserted about 175568 rows as a test. And then I deleted about 568 rows, BUT when I insert the data again the column `Vol_ID` start from 175569 not from 175001.
I want to inse... | you need to reseed the identity column like below
```
DBCC CHECKIDENT(Personal_Info, RESEED, 175001)
```
Quoted from MSDN
> Permission:
>
> Caller must own the table, or be a member of the sysadmin fixed server
> role, the db\_owner fixed database role, or the db\_ddladmin fixed
> database role.
So. it's either the... | What you are trying to do is not what the identity column was made for - there is no guarantee that there won't be gaps, and deleting records does not re-use the missing identities.
If you really need a sequential, auto increment id field, with no gaps, then you are better of either using a stored procedure to do your... | How to reseed the identity column in SQL Server? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2008-r2",
""
] |
I am pretty new to SQL and might be doing something wrong here so I hope someone can help me with this.
I have a longer stored procedure that ends with the below.
The idea here is to combine two queries into one so that I don't need a separate stored procedure but still have the results separated as one selects by a c... | Please remove the ORDER BY and add it to the very end. You cannot place ORDER BY before UNION / UNION ALL.
**[Here](http://blog.sqlauthority.com/2012/10/30/sql-server-union-all-and-order-by-how-to-order-table-separately-while-using-union-all/)**'s more information about this syntax. | you can't include `ORDER BY` until after the last query in the `UNION`. | SQL Server: issue with UNION ALL and two Selects | [
"",
"sql",
"sql-server",
"select",
"union",
"union-all",
""
] |
I am trying to calculate the total amount for charity. Each row has a bid amount and a charity percentage.
The structure of the fields looks like this:
CurrentBid INT
CharityPercentage INT <-- 0-100, where 100 is donating all to charity
So i tried this:
```
SELECT CurrentBid, CharityPercentage, CurrentBid * (Charity... | Explicitly make at least one value a decimal/float/etc. In your case, you already have a literal numeric value, `100`; so, simply change it to, `100.0`:
```
CurrentBid * CharityPercentage / 100.0 AS TotalCharity
``` | don't CAST -- instead, just multiply by 1.00. This does the CASTing implicitly.
```
SELECT CurrentBid, CharityPercentage, (1.00 * CurrentBid * CharityPercentage) / 100 AS TotalCharity FROM Items
``` | Calculate percentage in MS SQL Server with int columns | [
"",
"sql",
"sql-server",
""
] |
Having these 3 tables
DEPARTMENT
```
//DEPARTMENT
DNAME
-----------
RESEARCH
IT
SCIENCE
```
PROJECT
```
//PROJECT
P# TITLE
----------------
1 COMPUTING
2 CODING
3 SEARCHING
```
DP <-- Assume constraint references done, just i didn't show the code here
```
//DP
DNAME P#
--... | Try this query
```
SELECT d.DNAME,P.TITLE from DEPARTMENT d
INNER JOIN DP ON d.DNAME=DP.DNAME
INNER JOIN PROJECT P ON P.P#=DP.P#
order by d.DNAME DESC, P.TITLE ASC
``` | Your `DEPARTMENT` data is already there in `DP` table. So use it.
```
select DNAME, TITLE
from DP d, PROJECT p
where d.p# = p.p#
order by 1
``` | SELECT clause using 3 different tables | [
"",
"sql",
"oracle",
""
] |
Considering the below table where is have 4 difference customers with more than 1 orders each.
I need to updated the column XYZ to 1 for each customer depending on the date created column.
```
Update the table1 set xyz = 1
```
condition only the latest ( date created ) order should have XYZ value as 0
```
Customerid... | DECLARE @customerid INT -- used for file name
DECLARE db\_cursor CURSOR FOR
SELECT distinct customerid
FROM orders
OPEN db\_cursor
FETCH NEXT FROM db\_cursor INTO @customerid
WHILE @@FETCH\_STATUS = 0
BEGIN
UPDATE Orders
set XYZ = 1
where Orderid <> (select top 1 Orderid from orders where Customerid = @custo... | ```
UPDATE thetable tt
SET xyz = 1
WHERE EXISTS (
SELECT * FROM thetable ex
WHERE ex.customerId = tt.customerId
AND ex.dateCreated > tt.dateCreated
);
``` | SQL table update all but the most recent record for every Id | [
"",
"mysql",
"sql",
""
] |
On my filter form i have two edit and they are give the result like this "01.12.2014"...
This is the turkish standard and format is dd.mm.yyyy
In the code section i have controlled them and convert the value with formatdatetime. and create aa select sql.
```
if edtTar1.Value>0 then tar1:=FormatDateTime('yyyymmdd',... | Yes, this should work
```
tarsart := ' and Sip_Tarih >= cast('+QuotedStr(tar1)+' as datetime)) '+
' and Sip_Tarih <= cast('+QuotedStr(tar2)+' as datetime)) ' ;
```
And depending on your SQL settings, this might work too
```
tarsart := ' and Sip_Tarih >= '+QuotedStr(tar1)+
' and Sip_Tarih <= '+QuotedStr(tar2) ;
``` | You should be able to do this easily by eliminating all the extra `Convert` statements:
```
tarsart := ' and (Sip_Tarih >= cast('+QuotedStr(tar1)+' as datetime) '+
' and Sip_Tarih <= cast('+QuotedStr(tar2)+' as datetime)) ';
```
Now, this said, it would also be a good idea for you to look into paramaterized SQL queri... | How to select records by date without using CAST? | [
"",
"sql",
"delphi",
""
] |
I'm having a problem with my SQL; the query selects only one row, even there are more rows it should select.
## Select statement
```
SELECT p.id,
p.product_name,
p.product_date,
coalesce(t.unique_hits, 0) AS unique_hits,
coalesce(t.total_hits, 0) AS total_hits,
coalesce(COUNT(s.prod... | You are missing group by while doing the aggregate function `sum()`
```
SELECT p.id,
p.product_name,
p.product_date,
coalesce(t.unique_hits, 0) AS unique_hits,
coalesce(t.total_hits, 0) AS total_hits,
coalesce(COUNT(s.product_id), 0) AS total_sales,
coalesce(SUM(s.amount), 0) ... | Here is your query:
```
SELECT p.id,
p.product_name,
p.product_date,
coalesce(t.unique_hits, 0) AS unique_hits,
coalesce(t.total_hits, 0) AS total_hits,
coalesce(COUNT(s.product_id), 0) AS total_sales,
coalesce(SUM(s.amount), 0) AS total_revenue
FROM products p
LEFT OUTER JOIN... | SQL Query With Joins Selects Only 1 row | [
"",
"mysql",
"sql",
""
] |
I am trying to do a `CASE` statement that combines two columns that are not alike. However, these two columns are names and the name could actually be the same except it might sometimes contain a suffix. So for instance, I want to bring back the following:
```
LastName1 | LastName2
------------------------
Ross ... | You can use left to take the first *n* characters. It is pretty clean LEFT(col, *n*)
```
SELECT
CASE
WHEN left(LastName1,4) <> left(LastName2,4)
THEN LastName1 + ', ' + LastName2
ELSE LastName1 END AS LastName
```
But this will be prone to getting false positives, be carful with your d... | I would extend your comparison using `like` comparison:
```
SELECT (CASE WHEN LastName1 like LastName2 + '%' THEN LastName1
WHEN LastName2 like LastName1 + '%' THEN LastName2
ELSE LastName1 + ', ' + LastName2
END) AS LastName
``` | CASE statement to combine two columns except when first characters not similar | [
"",
"sql",
"t-sql",
""
] |
**UPDATE**
I have modified the SQL Fiddle to make the department names more reflective of what I am trying to get to. If you look at the fiddle there are 3 select statements.
1. Lists the departments in the correct order from the data
2. Result from my attempt at a pivot
3. Fake select so show what I am TRYING to get... | Since you need to return 3 levels of a hierarchy data structure it might be significantly easier to use JOINs instead of using a PIVOT. You would start by returning the parent rows:
```
select p.departmentName
from dbo.department p
where p.departmentParentID is null;
```
This will get you all of the top level rows. T... | i created below sql based on your view sql. you almost get the result in there.
i use @temp table to remove the order by clause. probably you can remove the @temp table in the implementation.
please try below sql:
```
declare @temp table
(
id int identity,
departmentLevel1 int,
departmentLevel2 int,
departme... | SQL pivot with no aggregate | [
"",
"sql",
"sql-server",
"pivot",
""
] |
I would like to ask if my Mysql statement is correct or not.. When I run this under mysql it does not return any error but I cannot retrieve the row for it. Here's my statement:
```
SELECT * FROM timekeeping WHERE createddate = NOW()
```
Here's what my table looks like
 (only date, not time) with a datetime field](https://stackoverflow.com/questions/14533914/mysql-compare-now-only-date-not-time-with-a-datetime-field)
Try this:
```
SELECT * FROM timekeeping WHERE DATE(createddate) = DATE(NOW());
``` | Most likely the `createddate = NOW()` is an exact time comparison , you are probably only interested in the year, month, day being the the same.
See here for details on how to do what you are trying to do:
<http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html> | mysql statement (SELECT) based on date now | [
"",
"mysql",
"sql",
"select",
""
] |
I'm basically trying to fetch the next three future events including today from the database m below is my query and it says that derived tables must have an alias , I'm new to this .. what would be the fix ?
```
select * from events where event_start_date in
(select event_start_date from
(select distinct... | > "derived tables must have an alias"
That error means that when you use a subquery in the `FROM` clause, it's called a *derived table* and you must declare an alias for that.
Here's a simpler form of your query that should work:
```
SELECT events.* FROM events
JOIN (SELECT DISTINCT event_start_date FROM events
... | Assuming that you have a column named `rownum`:
```
select * from events where event_start_date in
(select distinct event_start_date
from events
where event_start_date >= '2014-05-02' AND rownum <= 3
order by event_start_date) T
```
**EDIT:**
If you are trying something like `rownum` as in oracle, you can us... | What's wrong with my SQL query ?? It won't fetch data | [
"",
"mysql",
"sql",
"phpmyadmin",
""
] |
I am trying to calculate running total in following query
```
select
a.ICode, MONTH(a.VDate), YEAR(a.vdate)
, sum(isnull(a.qty, 0))
, sum(isnull(a.qty, 0)) OVER (partition by a.icode order by a.icode) AS 'total'
from
t_Stock as a
group by
a.ICode, MONTH(a.VDate), YEAR(a.vdate)
order by
a.i... | When using window functions with aggregation, you actually need to nest the results. Here is a version of your query that should work:
```
select a.ICode, MONTH(a.VDate), YEAR(a.vdate),
sum(isnull(a.qty, 0)),
sum(sum(isnull(a.qty, 0))) OVER (partition by a.icode order by a.icode) AS total
from t_Stock a
... | write as:
```
select a.ICode,MONTH(a.VDate), YEAR(a.vdate)
, sum(isnull(a.qty,0)) OVER(partition by a.icode order by a.icode)
AS 'Runningtotal'
, sum(isnull(a.qty,0)) OVER(partition by a.icode,MONTH(a.VDate), YEAR(a.vdate)
order by a.icode,YEAR(a.vdate),MONTH(a.VDate)) AS 'total'
from
t_Stock as a
--group by a.... | sql server running total with over, partition | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.